]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tinfo/lib_win32con.c
ncurses 6.4 - patch 20230211
[ncurses.git] / ncurses / tinfo / lib_win32con.c
1 /****************************************************************************
2  * Copyright 2020-2021,2023 Thomas E. Dickey                                *
3  * Copyright 1998-2009,2010 Free Software Foundation, Inc.                  *
4  *                                                                          *
5  * Permission is hereby granted, free of charge, to any person obtaining a  *
6  * copy of this software and associated documentation files (the            *
7  * "Software"), to deal in the Software without restriction, including      *
8  * without limitation the rights to use, copy, modify, merge, publish,      *
9  * distribute, distribute with modifications, sublicense, and/or sell       *
10  * copies of the Software, and to permit persons to whom the Software is    *
11  * furnished to do so, subject to the following conditions:                 *
12  *                                                                          *
13  * The above copyright notice and this permission notice shall be included  *
14  * in all copies or substantial portions of the Software.                   *
15  *                                                                          *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
19  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
23  *                                                                          *
24  * Except as contained in this notice, the name(s) of the above copyright   *
25  * holders shall not be used in advertising or otherwise to promote the     *
26  * sale, use or other dealings in this Software without prior written       *
27  * authorization.                                                           *
28  ****************************************************************************/
29
30 /****************************************************************************
31  *  Author: Juergen Pfeifer                                                 *
32  *     and: Thomas E. Dickey                                                *
33  ****************************************************************************/
34
35 /*
36  * TODO - GetMousePos(POINT * result) from ntconio.c
37  */
38
39 #include <curses.priv.h>
40
41 MODULE_ID("$Id: lib_win32con.c,v 1.11 2023/02/12 00:31:33 tom Exp $")
42
43 #ifdef _NC_WINDOWS
44
45 #ifdef _NC_MINGW
46 #include <wchar.h>
47 #else
48 #include <tchar.h>
49 #endif
50
51 #include <io.h>
52
53 #if USE_WIDEC_SUPPORT
54 #define write_screen WriteConsoleOutputW
55 #define read_screen  ReadConsoleOutputW
56 #else
57 #define write_screen WriteConsoleOutput
58 #define read_screen  ReadConsoleOutput
59 #endif
60
61 static BOOL IsConsoleHandle(HANDLE hdl);
62 static bool save_original_screen(void);
63 static bool restore_original_screen(void) GCC_UNUSED;
64 static bool read_screen_data(void);
65 static int Adjust(int milliseconds, int diff);
66 static int decode_mouse(SCREEN *sp, int mask);
67 static bool handle_mouse(SCREEN *sp, MOUSE_EVENT_RECORD mer);
68 static int rkeycompare(const void *el1, const void *el2);
69 static int keycompare(const void *el1, const void *el2);
70 static int MapKey(WORD vKey);
71 static int AnsiKey(WORD vKey);
72
73 static ULONGLONG tdiff(FILETIME fstart, FILETIME fend);
74
75 #define GenMap(vKey,key) MAKELONG(key, vKey)
76 static const LONG keylist[] =
77 {
78     GenMap(VK_PRIOR, KEY_PPAGE),
79     GenMap(VK_NEXT, KEY_NPAGE),
80     GenMap(VK_END, KEY_END),
81     GenMap(VK_HOME, KEY_HOME),
82     GenMap(VK_LEFT, KEY_LEFT),
83     GenMap(VK_UP, KEY_UP),
84     GenMap(VK_RIGHT, KEY_RIGHT),
85     GenMap(VK_DOWN, KEY_DOWN),
86     GenMap(VK_DELETE, KEY_DC),
87     GenMap(VK_INSERT, KEY_IC)
88 };
89 static const LONG ansi_keys[] =
90 {
91     GenMap(VK_PRIOR, 'I'),
92     GenMap(VK_NEXT, 'Q'),
93     GenMap(VK_END, 'O'),
94     GenMap(VK_HOME, 'H'),
95     GenMap(VK_LEFT, 'K'),
96     GenMap(VK_UP, 'H'),
97     GenMap(VK_RIGHT, 'M'),
98     GenMap(VK_DOWN, 'P'),
99     GenMap(VK_DELETE, 'S'),
100     GenMap(VK_INSERT, 'R')
101 };
102 #define array_length(a) (sizeof(a)/sizeof(a[0]))
103 #define N_INI ((int)array_length(keylist))
104 #define FKEYS 24
105 #define MAPSIZE (FKEYS + N_INI)
106
107 /*   A process can only have a single console, so it is safe
108      to maintain all the information about it in a single
109      static structure.
110  */
111 NCURSES_EXPORT_VAR(ConsoleInfo) _nc_CONSOLE;
112 static bool console_initialized = FALSE;
113
114 #define EnsureInit() (void)(console_initialized ? TRUE : _nc_console_checkinit(TRUE, TRUE))
115
116 #define REQUIRED_MAX_V (DWORD)10
117 #define REQUIRED_MIN_V (DWORD)0
118 #define REQUIRED_BUILD (DWORD)17763
119 /*
120   This function returns 0 if the Windows version has no support for
121   the modern Console interface, otherwise it returns 1
122  */
123 NCURSES_EXPORT(int)
124 _nc_console_vt_supported(void)
125 {
126     OSVERSIONINFO osvi;
127     int res = 0;
128
129     T((T_CALLED("lib_win32con::_nc_console_vt_supported")));
130     ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
131     osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
132
133     GetVersionEx(&osvi);
134     T(("GetVersionEx returnedMajor=%ld, Minor=%ld, Build=%ld",
135        osvi.dwMajorVersion,
136        osvi.dwMinorVersion,
137        osvi.dwBuildNumber));
138     if (osvi.dwMajorVersion >= REQUIRED_MAX_V) {
139         if (osvi.dwMajorVersion == REQUIRED_MAX_V) {
140             if (((osvi.dwMinorVersion == REQUIRED_MIN_V) &&
141                  (osvi.dwBuildNumber >= REQUIRED_BUILD)) ||
142                 ((osvi.dwMinorVersion > REQUIRED_MIN_V)))
143                 res = 1;
144         } else
145             res = 1;
146     }
147     returnCode(res);
148 }
149
150 NCURSES_EXPORT(void)
151 _nc_console_size(int *Lines, int *Cols)
152 {
153     EnsureInit();
154     if (Lines != NULL && Cols != NULL) {
155         if (WINCONSOLE.buffered) {
156             *Lines = (int) (WINCONSOLE.SBI.dwSize.Y);
157             *Cols = (int) (WINCONSOLE.SBI.dwSize.X);
158         } else {
159             *Lines = (int) (WINCONSOLE.SBI.srWindow.Bottom + 1 -
160                             WINCONSOLE.SBI.srWindow.Top);
161             *Cols = (int) (WINCONSOLE.SBI.srWindow.Right + 1 -
162                            WINCONSOLE.SBI.srWindow.Left);
163         }
164     }
165 }
166
167 /* Convert a file descriptor into a HANDLE
168    That's not necessarily a console HANDLE
169 */
170 NCURSES_EXPORT(HANDLE)
171 _nc_console_handle(int fd)
172 {
173     intptr_t value = _get_osfhandle(fd);
174     return (HANDLE) value;
175 }
176
177 /* Validate that a HANDLE is actually a
178    console HANDLE
179 */
180 static BOOL
181 IsConsoleHandle(HANDLE hdl)
182 {
183     DWORD dwFlag = 0;
184     BOOL result = FALSE;
185
186     T((T_CALLED("lib_win32con::IsConsoleHandle(HANDLE=%p"), hdl));
187
188     EnsureInit();
189
190     if (!GetConsoleMode(hdl, &dwFlag)) {
191         T(("GetConsoleMode failed"));
192     } else {
193         result = TRUE;
194     }
195
196     returnBool(result);
197 }
198
199 /*   This is used when running in terminfo mode to discover,
200      whether or not the "terminal" is actually a Windows
201      Console. It is the responsibility of the console to deal
202      with the terminal escape sequences that are sent by
203      terminfo.
204  */
205 NCURSES_EXPORT(int)
206 _nc_console_test(int fd)
207 {
208     int code = 0;
209     HANDLE hdl = INVALID_HANDLE_VALUE;
210     T((T_CALLED("lib_win32con::_nc_console_test(%d)"), fd));
211     hdl = _nc_console_handle(fd);
212     code = (int) IsConsoleHandle(hdl);
213     returnCode(code);
214 }
215
216 #define OutHandle() ((WINCONSOLE.isTermInfoConsole || WINCONSOLE.progMode) ? WINCONSOLE.hdl : WINCONSOLE.out)
217
218 NCURSES_EXPORT(void)
219 _nc_console_selectActiveHandle(void)
220 {
221     if (WINCONSOLE.lastOut != WINCONSOLE.hdl) {
222         WINCONSOLE.lastOut = WINCONSOLE.hdl;
223         SetConsoleActiveScreenBuffer(WINCONSOLE.lastOut);
224     }
225 }
226
227 NCURSES_EXPORT(HANDLE)
228 _nc_console_fd2handle(int fd)
229 {
230     HANDLE hdl = _nc_console_handle(fd);
231     if (hdl == WINCONSOLE.inp) {
232         T(("lib_win32con:validateHandle %d -> WINCONSOLE.inp", fd));
233     } else if (hdl == WINCONSOLE.hdl) {
234         T(("lib_win32con:validateHandle %d -> WINCONSOLE.hdl", fd));
235     } else if (hdl == WINCONSOLE.out) {
236         T(("lib_win32con:validateHandle %d -> WINCONSOLE.out", fd));
237     } else {
238         T(("lib_win32con:validateHandle %d maps to unknown HANDLE", fd));
239         hdl = INVALID_HANDLE_VALUE;
240     }
241 #if 1
242     assert(hdl != INVALID_HANDLE_VALUE);
243 #endif
244     if (hdl != INVALID_HANDLE_VALUE) {
245         if (hdl != WINCONSOLE.inp && (!WINCONSOLE.isTermInfoConsole && WINCONSOLE.progMode)) {
246             if (hdl == WINCONSOLE.out && hdl != WINCONSOLE.hdl) {
247                 T(("lib_win32con:validateHandle forcing WINCONSOLE.out -> WINCONSOLE.hdl"));
248                 hdl = WINCONSOLE.hdl;
249             }
250         }
251     }
252     return hdl;
253 }
254
255 NCURSES_EXPORT(int)
256 _nc_console_setmode(HANDLE hdl, const TTY * arg)
257 {
258     DWORD dwFlag = 0;
259     int code = ERR;
260     HANDLE alt;
261
262     if (arg) {
263 #ifdef TRACE
264         TTY TRCTTY;
265 #define TRCTTYOUT(flag) TRCTTY.dwFlagOut = flag
266 #define TRCTTYIN(flag)  TRCTTY.dwFlagIn = flag
267 #else
268 #define TRCTTYOUT(flag)
269 #define TRCTTYIN(flag)
270 #endif
271         T(("lib_win32con:_nc_console_setmode %s", _nc_trace_ttymode(arg)));
272         if (hdl == WINCONSOLE.inp) {
273             dwFlag = arg->dwFlagIn | ENABLE_MOUSE_INPUT | VT_FLAG_IN;
274             if (WINCONSOLE.isTermInfoConsole)
275                 dwFlag |= (VT_FLAG_IN);
276             else
277                 dwFlag &= (DWORD) ~ (VT_FLAG_IN);
278             TRCTTYIN(dwFlag);
279             SetConsoleMode(hdl, dwFlag);
280
281             alt = OutHandle();
282             dwFlag = arg->dwFlagOut;
283             if (WINCONSOLE.isTermInfoConsole)
284                 dwFlag |= (VT_FLAG_OUT);
285             else
286                 dwFlag |= (VT_FLAG_OUT);
287             TRCTTYOUT(dwFlag);
288             SetConsoleMode(alt, dwFlag);
289         } else {
290             dwFlag = arg->dwFlagOut;
291             if (WINCONSOLE.isTermInfoConsole)
292                 dwFlag |= (VT_FLAG_OUT);
293             else
294                 dwFlag |= (VT_FLAG_OUT);
295             TRCTTYOUT(dwFlag);
296             SetConsoleMode(hdl, dwFlag);
297
298             alt = WINCONSOLE.inp;
299             dwFlag = arg->dwFlagIn | ENABLE_MOUSE_INPUT;
300             if (WINCONSOLE.isTermInfoConsole)
301                 dwFlag |= (VT_FLAG_IN);
302             else
303                 dwFlag &= (DWORD) ~ (VT_FLAG_IN);
304             TRCTTYIN(dwFlag);
305             SetConsoleMode(alt, dwFlag);
306             T(("effective mode set %s", _nc_trace_ttymode(&TRCTTY)));
307         }
308         code = OK;
309     }
310     return (code);
311 }
312
313 NCURSES_EXPORT(int)
314 _nc_console_getmode(HANDLE hdl, TTY * arg)
315 {
316     int code = ERR;
317
318     if (arg) {
319         DWORD dwFlag = 0;
320         HANDLE alt;
321
322         if (hdl == WINCONSOLE.inp) {
323             if (GetConsoleMode(hdl, &dwFlag)) {
324                 arg->dwFlagIn = dwFlag;
325                 alt = OutHandle();
326                 if (GetConsoleMode(alt, &dwFlag)) {
327                     arg->dwFlagOut = dwFlag;
328                     code = OK;
329                 }
330             }
331         } else {
332             if (GetConsoleMode(hdl, &dwFlag)) {
333                 arg->dwFlagOut = dwFlag;
334                 alt = WINCONSOLE.inp;
335                 if (GetConsoleMode(alt, &dwFlag)) {
336                     arg->dwFlagIn = dwFlag;
337                     code = OK;
338                 }
339             }
340         }
341     }
342     T(("lib_win32con:_nc_console_getmode %s", _nc_trace_ttymode(arg)));
343     return (code);
344 }
345
346 NCURSES_EXPORT(int)
347 _nc_console_flush(HANDLE hdl)
348 {
349     int code = OK;
350
351     T((T_CALLED("lib_win32con::_nc_console_flush(hdl=%p"), hdl));
352
353     if (hdl != INVALID_HANDLE_VALUE) {
354         if (hdl == WINCONSOLE.hdl ||
355             hdl == WINCONSOLE.inp ||
356             hdl == WINCONSOLE.out) {
357             if (!FlushConsoleInputBuffer(WINCONSOLE.inp))
358                 code = ERR;
359         } else {
360             code = ERR;
361             T(("_nc_console_flush not requesting a handle owned by console."));
362         }
363     }
364     returnCode(code);
365 }
366
367 NCURSES_EXPORT(WORD)
368 _nc_console_MapColor(bool fore, int color)
369 {
370     static const int _cmap[] =
371     {0, 4, 2, 6, 1, 5, 3, 7};
372     int a;
373     if (color < 0 || color > 7)
374         a = fore ? 7 : 0;
375     else
376         a = _cmap[color];
377     if (!fore)
378         a = a << 4;
379     return (WORD) a;
380 }
381
382 /*
383  * Attempt to save the screen contents.  PDCurses does this if
384  * PDC_RESTORE_SCREEN is set, giving the same visual appearance on
385  * restoration as if the library had allocated a console buffer.  MSDN
386  * says that the data which can be read is limited to 64Kb (and may be
387  * less).
388  */
389 static bool
390 save_original_screen(void)
391 {
392     bool result = FALSE;
393
394     WINCONSOLE.save_region.Top = 0;
395     WINCONSOLE.save_region.Left = 0;
396     WINCONSOLE.save_region.Bottom = (SHORT) (WINCONSOLE.SBI.dwSize.Y - 1);
397     WINCONSOLE.save_region.Right = (SHORT) (WINCONSOLE.SBI.dwSize.X - 1);
398
399     if (read_screen_data()) {
400         result = TRUE;
401     } else {
402
403         WINCONSOLE.save_region.Top = WINCONSOLE.SBI.srWindow.Top;
404         WINCONSOLE.save_region.Left = WINCONSOLE.SBI.srWindow.Left;
405         WINCONSOLE.save_region.Bottom = WINCONSOLE.SBI.srWindow.Bottom;
406         WINCONSOLE.save_region.Right = WINCONSOLE.SBI.srWindow.Right;
407
408         WINCONSOLE.window_only = TRUE;
409
410         if (read_screen_data()) {
411             result = TRUE;
412         }
413     }
414
415     T(("... save original screen contents %s", result ? "ok" : "err"));
416     return result;
417 }
418
419 static bool
420 restore_original_screen(void)
421 {
422     COORD bufferCoord;
423     bool result = FALSE;
424     SMALL_RECT save_region = WINCONSOLE.save_region;
425
426     T(("... restoring %s",
427        WINCONSOLE.window_only ? "window" : "entire buffer"));
428
429     bufferCoord.X = (SHORT) (WINCONSOLE.window_only ?
430                              WINCONSOLE.SBI.srWindow.Left : 0);
431     bufferCoord.Y = (SHORT) (WINCONSOLE.window_only ?
432                              WINCONSOLE.SBI.srWindow.Top : 0);
433
434     if (write_screen(WINCONSOLE.hdl,
435                      WINCONSOLE.save_screen,
436                      WINCONSOLE.save_size,
437                      bufferCoord,
438                      &save_region)) {
439         result = TRUE;
440         mvcur(-1, -1, LINES - 2, 0);
441         T(("... restore original screen contents ok %dx%d (%d,%d - %d,%d)",
442            WINCONSOLE.save_size.Y,
443            WINCONSOLE.save_size.X,
444            save_region.Top,
445            save_region.Left,
446            save_region.Bottom,
447            save_region.Right));
448     } else {
449         T(("... restore original screen contents err"));
450     }
451     return result;
452 }
453
454 static bool
455 read_screen_data(void)
456 {
457     bool result = FALSE;
458     COORD bufferCoord;
459     size_t want;
460
461     WINCONSOLE.save_size.X = (SHORT) (WINCONSOLE.save_region.Right
462                                       - WINCONSOLE.save_region.Left + 1);
463     WINCONSOLE.save_size.Y = (SHORT) (WINCONSOLE.save_region.Bottom
464                                       - WINCONSOLE.save_region.Top + 1);
465
466     want = (size_t) (WINCONSOLE.save_size.X * WINCONSOLE.save_size.Y);
467
468     if ((WINCONSOLE.save_screen = malloc(want * sizeof(CHAR_INFO))) != 0) {
469         bufferCoord.X = (SHORT) (WINCONSOLE.window_only ?
470                                  WINCONSOLE.SBI.srWindow.Left : 0);
471         bufferCoord.Y = (SHORT) (WINCONSOLE.window_only ?
472                                  WINCONSOLE.SBI.srWindow.Top : 0);
473
474         T(("... reading console %s %dx%d into %d,%d - %d,%d at %d,%d",
475            WINCONSOLE.window_only ? "window" : "buffer",
476            WINCONSOLE.save_size.Y, WINCONSOLE.save_size.X,
477            WINCONSOLE.save_region.Top,
478            WINCONSOLE.save_region.Left,
479            WINCONSOLE.save_region.Bottom,
480            WINCONSOLE.save_region.Right,
481            bufferCoord.Y,
482            bufferCoord.X));
483
484         if (read_screen(WINCONSOLE.hdl,
485                         WINCONSOLE.save_screen,
486                         WINCONSOLE.save_size,
487                         bufferCoord,
488                         &WINCONSOLE.save_region)) {
489             result = TRUE;
490         } else {
491             T((" error %#lx", (unsigned long) GetLastError()));
492             FreeAndNull(WINCONSOLE.save_screen);
493         }
494     }
495
496     return result;
497 }
498
499 NCURSES_EXPORT(bool)
500 _nc_console_get_SBI(void)
501 {
502     bool rc = FALSE;
503     if (GetConsoleScreenBufferInfo(WINCONSOLE.hdl, &(WINCONSOLE.SBI))) {
504         T(("GetConsoleScreenBufferInfo"));
505         T(("... buffer(X:%d Y:%d)",
506            WINCONSOLE.SBI.dwSize.X,
507            WINCONSOLE.SBI.dwSize.Y));
508         T(("... window(X:%d Y:%d)",
509            WINCONSOLE.SBI.dwMaximumWindowSize.X,
510            WINCONSOLE.SBI.dwMaximumWindowSize.Y));
511         T(("... cursor(X:%d Y:%d)",
512            WINCONSOLE.SBI.dwCursorPosition.X,
513            WINCONSOLE.SBI.dwCursorPosition.Y));
514         T(("... display(Top:%d Bottom:%d Left:%d Right:%d)",
515            WINCONSOLE.SBI.srWindow.Top,
516            WINCONSOLE.SBI.srWindow.Bottom,
517            WINCONSOLE.SBI.srWindow.Left,
518            WINCONSOLE.SBI.srWindow.Right));
519         if (WINCONSOLE.buffered) {
520             WINCONSOLE.origin.X = 0;
521             WINCONSOLE.origin.Y = 0;
522         } else {
523             WINCONSOLE.origin.X = WINCONSOLE.SBI.srWindow.Left;
524             WINCONSOLE.origin.Y = WINCONSOLE.SBI.srWindow.Top;
525         }
526         rc = TRUE;
527     } else {
528         T(("GetConsoleScreenBufferInfo ERR"));
529     }
530     return rc;
531 }
532
533 #define MIN_WIDE 80
534 #define MIN_HIGH 24
535
536 /*
537  * In "normal" mode, reset the buffer- and window-sizes back to their original values.
538  */
539 NCURSES_EXPORT(void)
540 _nc_console_set_scrollback(bool normal, CONSOLE_SCREEN_BUFFER_INFO * info)
541 {
542     SMALL_RECT rect;
543     COORD coord;
544     bool changed = FALSE;
545
546     T((T_CALLED("lib_win32con::_nc_console_set_scrollback(%s)"),
547        (normal
548         ? "normal"
549         : "application")));
550
551     T(("... SBI.srWindow %d,%d .. %d,%d",
552        info->srWindow.Top,
553        info->srWindow.Left,
554        info->srWindow.Bottom,
555        info->srWindow.Right));
556     T(("... SBI.dwSize %dx%d",
557        info->dwSize.Y,
558        info->dwSize.X));
559
560     if (normal) {
561         rect = info->srWindow;
562         coord = info->dwSize;
563         if (memcmp(info, &WINCONSOLE.SBI, sizeof(*info)) != 0) {
564             changed = TRUE;
565             WINCONSOLE.SBI = *info;
566         }
567     } else {
568         int high = info->srWindow.Bottom - info->srWindow.Top + 1;
569         int wide = info->srWindow.Right - info->srWindow.Left + 1;
570
571         if (high < MIN_HIGH) {
572             T(("... height %d < %d", high, MIN_HIGH));
573             high = MIN_HIGH;
574             changed = TRUE;
575         }
576         if (wide < MIN_WIDE) {
577             T(("... width %d < %d", wide, MIN_WIDE));
578             wide = MIN_WIDE;
579             changed = TRUE;
580         }
581
582         rect.Left =
583             rect.Top = 0;
584         rect.Right = (SHORT) (wide - 1);
585         rect.Bottom = (SHORT) (high - 1);
586
587         coord.X = (SHORT) wide;
588         coord.Y = (SHORT) high;
589
590         if (info->dwSize.Y != high ||
591             info->dwSize.X != wide ||
592             info->srWindow.Top != 0 ||
593             info->srWindow.Left != 0) {
594             changed = TRUE;
595         }
596
597     }
598
599     if (changed) {
600         T(("... coord %d,%d", coord.Y, coord.X));
601         T(("... rect %d,%d - %d,%d",
602            rect.Top, rect.Left,
603            rect.Bottom, rect.Right));
604         SetConsoleScreenBufferSize(WINCONSOLE.hdl, coord);      /* dwSize */
605         SetConsoleWindowInfo(WINCONSOLE.hdl, TRUE, &rect);      /* srWindow */
606         _nc_console_get_SBI();
607     }
608     returnVoid;
609 }
610
611 static ULONGLONG
612 tdiff(FILETIME fstart, FILETIME fend)
613 {
614     ULARGE_INTEGER ustart;
615     ULARGE_INTEGER uend;
616     ULONGLONG diff;
617
618     ustart.LowPart = fstart.dwLowDateTime;
619     ustart.HighPart = fstart.dwHighDateTime;
620     uend.LowPart = fend.dwLowDateTime;
621     uend.HighPart = fend.dwHighDateTime;
622
623     diff = (uend.QuadPart - ustart.QuadPart) / 10000;
624     return diff;
625 }
626
627 static int
628 Adjust(int milliseconds, int diff)
629 {
630     if (milliseconds != INFINITY) {
631         milliseconds -= diff;
632         if (milliseconds < 0)
633             milliseconds = 0;
634     }
635     return milliseconds;
636 }
637
638 #define BUTTON_MASK (FROM_LEFT_1ST_BUTTON_PRESSED | \
639                      FROM_LEFT_2ND_BUTTON_PRESSED | \
640                      FROM_LEFT_3RD_BUTTON_PRESSED | \
641                      FROM_LEFT_4TH_BUTTON_PRESSED | \
642                      RIGHTMOST_BUTTON_PRESSED)
643
644 static int
645 decode_mouse(SCREEN *sp, int mask)
646 {
647     int result = 0;
648
649     (void) sp;
650     assert(sp && console_initialized);
651
652     if (mask & FROM_LEFT_1ST_BUTTON_PRESSED)
653         result |= BUTTON1_PRESSED;
654     if (mask & FROM_LEFT_2ND_BUTTON_PRESSED)
655         result |= BUTTON2_PRESSED;
656     if (mask & FROM_LEFT_3RD_BUTTON_PRESSED)
657         result |= BUTTON3_PRESSED;
658     if (mask & FROM_LEFT_4TH_BUTTON_PRESSED)
659         result |= BUTTON4_PRESSED;
660
661     if (mask & RIGHTMOST_BUTTON_PRESSED) {
662         switch (WINCONSOLE.numButtons) {
663         case 1:
664             result |= BUTTON1_PRESSED;
665             break;
666         case 2:
667             result |= BUTTON2_PRESSED;
668             break;
669         case 3:
670             result |= BUTTON3_PRESSED;
671             break;
672         case 4:
673             result |= BUTTON4_PRESSED;
674             break;
675         }
676     }
677
678     return result;
679 }
680
681 #define AdjustY() (WINCONSOLE.buffered ? 0 : (int) WINCONSOLE.SBI.srWindow.Top)
682
683 static bool
684 handle_mouse(SCREEN *sp, MOUSE_EVENT_RECORD mer)
685 {
686     MEVENT work;
687     bool result = FALSE;
688
689     assert(sp);
690
691     sp->_drv_mouse_old_buttons = sp->_drv_mouse_new_buttons;
692     sp->_drv_mouse_new_buttons = mer.dwButtonState & BUTTON_MASK;
693
694     /*
695      * We're only interested if the button is pressed or released.
696      * FIXME: implement continuous event-tracking.
697      */
698     if (sp->_drv_mouse_new_buttons != sp->_drv_mouse_old_buttons) {
699         memset(&work, 0, sizeof(work));
700
701         if (sp->_drv_mouse_new_buttons) {
702             work.bstate |=
703                 (mmask_t) decode_mouse(sp,
704                                        sp->_drv_mouse_new_buttons);
705         } else {
706             /* cf: BUTTON_PRESSED, BUTTON_RELEASED */
707             work.bstate |=
708                 (mmask_t) (decode_mouse(sp,
709                                         sp->_drv_mouse_old_buttons)
710                            >> 1);
711             result = TRUE;
712         }
713
714         work.x = mer.dwMousePosition.X;
715         work.y = mer.dwMousePosition.Y - AdjustY();
716
717         sp->_drv_mouse_fifo[sp->_drv_mouse_tail] = work;
718         sp->_drv_mouse_tail += 1;
719     }
720     return result;
721 }
722
723 static int
724 rkeycompare(const void *el1, const void *el2)
725 {
726     WORD key1 = (LOWORD((*((const LONG *) el1)))) & 0x7fff;
727     WORD key2 = (LOWORD((*((const LONG *) el2)))) & 0x7fff;
728
729     return ((key1 < key2) ? -1 : ((key1 == key2) ? 0 : 1));
730 }
731
732 static int
733 keycompare(const void *el1, const void *el2)
734 {
735     WORD key1 = HIWORD((*((const LONG *) el1)));
736     WORD key2 = HIWORD((*((const LONG *) el2)));
737
738     return ((key1 < key2) ? -1 : ((key1 == key2) ? 0 : 1));
739 }
740
741 static int
742 MapKey(WORD vKey)
743 {
744     int code = -1;
745
746     if (!WINCONSOLE.isTermInfoConsole) {
747         WORD nKey = 0;
748         void *res;
749         LONG key = GenMap(vKey, 0);
750
751         res = bsearch(&key,
752                       WINCONSOLE.map,
753                       (size_t) (N_INI + FKEYS),
754                       sizeof(keylist[0]),
755                       keycompare);
756         if (res) {
757             key = *((LONG *) res);
758             nKey = LOWORD(key);
759             code = (int) (nKey & 0x7fff);
760             if (nKey & 0x8000)
761                 code = -code;
762         }
763     }
764     return code;
765 }
766
767 static int
768 AnsiKey(WORD vKey)
769 {
770     int code = -1;
771
772     if (!WINCONSOLE.isTermInfoConsole) {
773         WORD nKey = 0;
774         void *res;
775         LONG key = GenMap(vKey, 0);
776
777         res = bsearch(&key,
778                       WINCONSOLE.ansi_map,
779                       (size_t) (N_INI + FKEYS),
780                       sizeof(keylist[0]),
781                       keycompare);
782         if (res) {
783             key = *((LONG *) res);
784             nKey = LOWORD(key);
785             code = (int) (nKey & 0x7fff);
786             if (nKey & 0x8000)
787                 code = -code;
788         }
789     }
790     return code;
791 }
792
793 NCURSES_EXPORT(int)
794 _nc_console_keyok(int keycode, int flag)
795 {
796     int code = ERR;
797     WORD nKey;
798     WORD vKey;
799     void *res;
800     LONG key = GenMap(0, (WORD) keycode);
801
802     T((T_CALLED("lib_win32con::_nc_console_keyok(%d, %d)"), keycode, flag));
803
804     res = bsearch(&key,
805                   WINCONSOLE.rmap,
806                   (size_t) (N_INI + FKEYS),
807                   sizeof(keylist[0]),
808                   rkeycompare);
809     if (res) {
810         key = *((LONG *) res);
811         vKey = HIWORD(key);
812         nKey = (LOWORD(key)) & 0x7fff;
813         if (!flag)
814             nKey |= 0x8000;
815         *(LONG *) res = GenMap(vKey, nKey);
816     }
817     returnCode(code);
818 }
819
820 NCURSES_EXPORT(bool)
821 _nc_console_keyExist(int keycode)
822 {
823     WORD nKey;
824     void *res;
825     bool found = FALSE;
826     LONG key = GenMap(0, (WORD) keycode);
827
828     T((T_CALLED("lib_win32con::_nc_console_keyExist(%d)"), keycode));
829     res = bsearch(&key,
830                   WINCONSOLE.rmap,
831                   (size_t) (N_INI + FKEYS),
832                   sizeof(keylist[0]),
833                   rkeycompare);
834     if (res) {
835         key = *((LONG *) res);
836         nKey = LOWORD(key);
837         if (!(nKey & 0x8000))
838             found = TRUE;
839     }
840     returnCode(found);
841 }
842
843 NCURSES_EXPORT(int)
844 _nc_console_twait(
845                      SCREEN *sp,
846                      HANDLE hdl,
847                      int mode,
848                      int milliseconds,
849                      int *timeleft
850                      EVENTLIST_2nd(_nc_eventlist * evl))
851 {
852     INPUT_RECORD inp_rec;
853     BOOL b;
854     DWORD nRead = 0, rc = (DWORD) (-1);
855     int code = 0;
856     FILETIME fstart;
857     FILETIME fend;
858     int diff;
859     bool isNoDelay = (milliseconds == 0);
860
861 #ifdef NCURSES_WGETCH_EVENTS
862     (void) evl;                 /* TODO: implement wgetch-events */
863 #endif
864
865 #define IGNORE_CTRL_KEYS (SHIFT_PRESSED|LEFT_ALT_PRESSED|RIGHT_ALT_PRESSED| \
866                           LEFT_CTRL_PRESSED|RIGHT_CTRL_PRESSED)
867 #define CONSUME() ReadConsoleInput(hdl, &inp_rec, 1, &nRead)
868
869     assert(sp);
870
871     TR(TRACE_IEVENT, ("start twait: hdl=%p, %d milliseconds, mode: %d",
872                       hdl, milliseconds, mode));
873
874     if (milliseconds < 0)
875         milliseconds = INFINITY;
876
877     memset(&inp_rec, 0, sizeof(inp_rec));
878
879     while (true) {
880         if (!isNoDelay) {
881             GetSystemTimeAsFileTime(&fstart);
882             rc = WaitForSingleObject(hdl, (DWORD) milliseconds);
883             GetSystemTimeAsFileTime(&fend);
884             diff = (int) tdiff(fstart, fend);
885             milliseconds = Adjust(milliseconds, diff);
886             if (milliseconds < 0)
887                 break;
888         }
889
890         if (isNoDelay || (rc == WAIT_OBJECT_0)) {
891             if (mode) {
892                 nRead = 0;
893                 b = GetNumberOfConsoleInputEvents(hdl, &nRead);
894                 if (!b) {
895                     T(("twait:err GetNumberOfConsoleInputEvents"));
896                 }
897                 if (isNoDelay && b) {
898                     T(("twait: Events Available: %ld", nRead));
899                     if (nRead == 0) {
900                         code = 0;
901                         goto end;
902                     } else {
903                         DWORD n = 0;
904                         INPUT_RECORD *pInpRec =
905                         TypeAlloca(INPUT_RECORD, nRead);
906                         if (pInpRec != NULL) {
907                             DWORD i;
908                             BOOL f;
909                             memset(pInpRec, 0, sizeof(INPUT_RECORD) * nRead);
910                             f = PeekConsoleInput(hdl, pInpRec, nRead, &n);
911                             if (f) {
912                                 for (i = 0; i < n; i++) {
913                                     if (pInpRec[i].EventType == KEY_EVENT) {
914                                         if (pInpRec[i].Event.KeyEvent.bKeyDown) {
915                                             DWORD ctrlMask =
916                                             (pInpRec[i].Event.KeyEvent.dwControlKeyState &
917                                              IGNORE_CTRL_KEYS);
918                                             if (!ctrlMask) {
919                                                 code = TW_INPUT;
920                                                 goto end;
921                                             }
922                                         }
923                                     }
924                                 }
925                             } else {
926                                 T(("twait:err PeekConsoleInput"));
927                             }
928                             code = 0;
929                             goto end;
930                         } else {
931                             T(("twait:err could not alloca input records"));
932                         }
933                     }
934                 }
935                 if (b && nRead > 0) {
936                     b = PeekConsoleInput(hdl, &inp_rec, 1, &nRead);
937                     if (!b) {
938                         T(("twait:err PeekConsoleInput"));
939                     }
940                     if (b && nRead > 0) {
941                         switch (inp_rec.EventType) {
942                         case KEY_EVENT:
943                             if (mode & TW_INPUT) {
944                                 WORD vk =
945                                 inp_rec.Event.KeyEvent.wVirtualKeyCode;
946                                 char ch =
947                                 inp_rec.Event.KeyEvent.uChar.AsciiChar;
948                                 T(("twait:event KEY_EVENT"));
949                                 T(("twait vk=%d, ch=%d, keydown=%d",
950                                    vk, ch, inp_rec.Event.KeyEvent.bKeyDown));
951                                 if (inp_rec.Event.KeyEvent.bKeyDown) {
952                                     T(("twait:event KeyDown"));
953                                     if (!WINCONSOLE.isTermInfoConsole &&
954                                         (0 == ch)) {
955                                         int nKey = MapKey(vk);
956                                         if (nKey < 0) {
957                                             CONSUME();
958                                             continue;
959                                         }
960                                     }
961                                     code = TW_INPUT;
962                                     goto end;
963                                 } else {
964                                     CONSUME();
965                                 }
966                             }
967                             continue;
968                         case MOUSE_EVENT:
969                             T(("twait:event MOUSE_EVENT"));
970                             if (decode_mouse(sp,
971                                              (inp_rec.Event.MouseEvent.dwButtonState
972                                               & BUTTON_MASK)) == 0) {
973                                 CONSUME();
974                             } else if (mode & TW_MOUSE) {
975                                 code = TW_MOUSE;
976                                 goto end;
977                             }
978                             continue;
979                             /* e.g., FOCUS_EVENT */
980                         default:
981                             T(("twait:event Tyoe %d", inp_rec.EventType));
982                             CONSUME();
983                             _nc_console_selectActiveHandle();
984                             continue;
985                         }
986                     }
987                 }
988             }
989             continue;
990         } else {
991             if (rc != WAIT_TIMEOUT) {
992                 code = -1;
993                 break;
994             } else {
995                 code = 0;
996                 break;
997             }
998         }
999     }
1000   end:
1001
1002     TR(TRACE_IEVENT, ("end twait: returned %d (%lu), remaining time %d msec",
1003                       code, GetLastError(), milliseconds));
1004
1005     if (timeleft)
1006         *timeleft = milliseconds;
1007
1008     return code;
1009 }
1010
1011 NCURSES_EXPORT(int)
1012 _nc_console_testmouse(
1013                          SCREEN *sp,
1014                          HANDLE hdl,
1015                          int delay
1016                          EVENTLIST_2nd(_nc_eventlist * evl))
1017 {
1018     int rc = 0;
1019
1020     assert(sp);
1021
1022     if (sp->_drv_mouse_head < sp->_drv_mouse_tail) {
1023         rc = TW_MOUSE;
1024     } else {
1025         rc = _nc_console_twait(sp,
1026                                hdl,
1027                                TWAIT_MASK,
1028                                delay,
1029                                (int *) 0
1030                                EVENTLIST_2nd(evl));
1031     }
1032     return rc;
1033 }
1034
1035 NCURSES_EXPORT(int)
1036 _nc_console_read(
1037                     SCREEN *sp,
1038                     HANDLE hdl,
1039                     int *buf)
1040 {
1041     int rc = -1;
1042     INPUT_RECORD inp_rec;
1043     BOOL b;
1044     DWORD nRead;
1045     WORD vk;
1046
1047     assert(sp);
1048     assert(buf);
1049
1050     memset(&inp_rec, 0, sizeof(inp_rec));
1051
1052     T((T_CALLED("lib_win32con::_nc_console_read(%p)"), sp));
1053
1054     while ((b = ReadConsoleInput(hdl, &inp_rec, 1, &nRead))) {
1055         if (b && nRead > 0) {
1056             if (rc < 0)
1057                 rc = 0;
1058             rc = rc + (int) nRead;
1059             if (inp_rec.EventType == KEY_EVENT) {
1060                 if (!inp_rec.Event.KeyEvent.bKeyDown)
1061                     continue;
1062                 *buf = (int) inp_rec.Event.KeyEvent.uChar.AsciiChar;
1063                 vk = inp_rec.Event.KeyEvent.wVirtualKeyCode;
1064                 /*
1065                  * There are 24 virtual function-keys, and typically
1066                  * 12 function-keys on a keyboard.  Use the shift-modifier
1067                  * to provide the remaining 12 keys.
1068                  */
1069                 if (vk >= VK_F1 && vk <= VK_F12) {
1070                     if (inp_rec.Event.KeyEvent.dwControlKeyState &
1071                         SHIFT_PRESSED) {
1072                         vk = (WORD) (vk + 12);
1073                     }
1074                 }
1075                 if (*buf == 0) {
1076                     int key = MapKey(vk);
1077                     if (key < 0)
1078                         continue;
1079                     if (sp->_keypad_on) {
1080                         *buf = key;
1081                     } else {
1082                         ungetch('\0');
1083                         *buf = AnsiKey(vk);
1084                     }
1085                 }
1086                 break;
1087             } else if (inp_rec.EventType == MOUSE_EVENT) {
1088                 if (handle_mouse(sp,
1089                                  inp_rec.Event.MouseEvent)) {
1090                     *buf = KEY_MOUSE;
1091                     break;
1092                 }
1093             }
1094             continue;
1095         }
1096     }
1097     returnCode(rc);
1098 }
1099
1100 /*   Our replacement for the systems _isatty to include also
1101      a test for mintty. This is called from the NC_ISATTY macro
1102      defined in curses.priv.h
1103
1104      Return codes:
1105      - 0 : Not a TTY
1106      - 1 : A Windows character device detected by _isatty
1107      - 2 : A future implementation may return 2 for mintty
1108  */
1109 NCURSES_EXPORT(int)
1110 _nc_console_isatty(int fd)
1111 {
1112     int result = 0;
1113     T((T_CALLED("lib_win32con::_nc_console_isatty(%d"), fd));
1114
1115     if (_isatty(fd))
1116         result = 1;
1117 #ifdef _NC_CHECK_MINTTY
1118     else {
1119         if (_nc_console_checkmintty(fd, NULL)) {
1120             result = 2;
1121             fprintf(stderr,
1122                     "ncurses on Windows must run in a Windows console.\n"
1123                     "On newer versions of Windows, the calling program should create a PTY-like.\n"
1124                     "device using the CreatePseudoConsole Windows API call.\n");
1125             exit(EXIT_FAILURE);
1126         }
1127     }
1128 #endif
1129     returnCode(result);
1130 }
1131
1132 NCURSES_EXPORT(bool)
1133 _nc_console_checkinit(bool initFlag, bool assumeTermInfo)
1134 {
1135     bool res = FALSE;
1136
1137     T((T_CALLED("lib_win32con::_nc_console_checkinit(initFlag=%d, assumeTermInfo=%d)"),
1138        initFlag, assumeTermInfo));
1139
1140     if (!initFlag) {
1141         res = console_initialized;
1142     } else {
1143         /* initialize once, or not at all */
1144         if (!console_initialized) {
1145             int i;
1146             DWORD num_buttons;
1147             WORD a;
1148             BOOL buffered = FALSE;
1149             BOOL b;
1150
1151             START_TRACE();
1152             WINCONSOLE.isTermInfoConsole = assumeTermInfo;
1153
1154             WINCONSOLE.map = (LPDWORD) malloc(sizeof(DWORD) * MAPSIZE);
1155             WINCONSOLE.rmap = (LPDWORD) malloc(sizeof(DWORD) * MAPSIZE);
1156             WINCONSOLE.ansi_map = (LPDWORD) malloc(sizeof(DWORD) * MAPSIZE);
1157
1158             for (i = 0; i < (N_INI + FKEYS); i++) {
1159                 if (i < N_INI) {
1160                     WINCONSOLE.rmap[i] = WINCONSOLE.map[i] =
1161                         (DWORD) keylist[i];
1162                     WINCONSOLE.ansi_map[i] = (DWORD) ansi_keys[i];
1163                 } else {
1164                     WINCONSOLE.rmap[i] = WINCONSOLE.map[i] =
1165                         (DWORD) GenMap((VK_F1 + (i - N_INI)),
1166                                        (KEY_F(1) + (i - N_INI)));
1167                     WINCONSOLE.ansi_map[i] =
1168                         (DWORD) GenMap((VK_F1 + (i - N_INI)),
1169                                        (';' + (i - N_INI)));
1170                 }
1171             }
1172             qsort(WINCONSOLE.ansi_map,
1173                   (size_t) (MAPSIZE),
1174                   sizeof(keylist[0]),
1175                   keycompare);
1176             qsort(WINCONSOLE.map,
1177                   (size_t) (MAPSIZE),
1178                   sizeof(keylist[0]),
1179                   keycompare);
1180             qsort(WINCONSOLE.rmap,
1181                   (size_t) (MAPSIZE),
1182                   sizeof(keylist[0]),
1183                   rkeycompare);
1184
1185             if (GetNumberOfConsoleMouseButtons(&num_buttons)) {
1186                 WINCONSOLE.numButtons = (int) num_buttons;
1187             } else {
1188                 WINCONSOLE.numButtons = 1;
1189             }
1190
1191             a = _nc_console_MapColor(true, COLOR_WHITE) |
1192                 _nc_console_MapColor(false, COLOR_BLACK);
1193             for (i = 0; i < CON_NUMPAIRS; i++)
1194                 WINCONSOLE.pairs[i] = a;
1195
1196 #define SaveConsoleMode(handle, data) \
1197             GetConsoleMode(WINCONSOLE.handle, &WINCONSOLE.originalMode.value)
1198
1199             if (WINCONSOLE.isTermInfoConsole) {
1200                 WINCONSOLE.inp = GetStdHandle(STD_INPUT_HANDLE);
1201                 WINCONSOLE.out = GetStdHandle(STD_OUTPUT_HANDLE);
1202                 WINCONSOLE.hdl = WINCONSOLE.out;
1203
1204                 SaveConsoleMode(inp, dwFlagIn);
1205                 SaveConsoleMode(out, dwFlagOut);
1206
1207             } else {
1208                 b = AllocConsole();
1209
1210                 if (!b)
1211                     b = AttachConsole(ATTACH_PARENT_PROCESS);
1212
1213                 WINCONSOLE.inp = GetDirectHandle("CONIN$", FILE_SHARE_READ);
1214                 WINCONSOLE.out = GetDirectHandle("CONOUT$", FILE_SHARE_WRITE);
1215
1216                 SaveConsoleMode(inp, dwFlagIn);
1217                 SaveConsoleMode(out, dwFlagOut);
1218
1219                 if (getenv("NCGDB") || getenv("NCURSES_CONSOLE2")) {
1220                     WINCONSOLE.hdl = WINCONSOLE.out;
1221                     T(("... will not buffer console"));
1222                 } else {
1223                     T(("... creating console buffer"));
1224                     WINCONSOLE.hdl =
1225                         CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE,
1226                                                   FILE_SHARE_READ | FILE_SHARE_WRITE,
1227                                                   NULL,
1228                                                   CONSOLE_TEXTMODE_BUFFER,
1229                                                   NULL);
1230                     buffered = TRUE;
1231                 }
1232             }
1233
1234             /* We set binary I/O even when using the console
1235                driver to cover the situation, that the
1236                TERM variable is set to #win32con, but actually
1237                Windows supports virtual terminal processing.
1238                So if terminfo functions are used in this setup,
1239                they actually may work.
1240              */
1241             _setmode(fileno(stdin), _O_BINARY);
1242             _setmode(fileno(stdout), _O_BINARY);
1243
1244             if (WINCONSOLE.hdl != INVALID_HANDLE_VALUE) {
1245                 WINCONSOLE.buffered = buffered;
1246                 _nc_console_get_SBI();
1247                 WINCONSOLE.save_SBI = WINCONSOLE.SBI;
1248                 if (!buffered) {
1249                     save_original_screen();
1250                     _nc_console_set_scrollback(FALSE, &WINCONSOLE.SBI);
1251                 }
1252                 GetConsoleCursorInfo(WINCONSOLE.hdl, &WINCONSOLE.save_CI);
1253                 T(("... initial cursor is %svisible, %d%%",
1254                    (WINCONSOLE.save_CI.bVisible ? "" : "not-"),
1255                    (int) WINCONSOLE.save_CI.dwSize));
1256             }
1257
1258             WINCONSOLE.initialized = TRUE;
1259             console_initialized = TRUE;
1260         }
1261         res = (WINCONSOLE.hdl != INVALID_HANDLE_VALUE);
1262     }
1263     returnBool(res);
1264 }
1265
1266 #endif // _NC_WINDOWS