ncurses 5.9 - patch 20140215
[ncurses.git] / ncurses / win32con / win_driver.c
1 /****************************************************************************
2  * Copyright (c) 1998-2013,2014 Free Software Foundation, Inc.              *
3  *                                                                          *
4  * Permission is hereby granted, free of charge, to any person obtaining a  *
5  * copy of this software and associated documentation files (the            *
6  * "Software"), to deal in the Software without restriction, including      *
7  * without limitation the rights to use, copy, modify, merge, publish,      *
8  * distribute, distribute with modifications, sublicense, and/or sell       *
9  * copies of the Software, and to permit persons to whom the Software is    *
10  * furnished to do so, subject to the following conditions:                 *
11  *                                                                          *
12  * The above copyright notice and this permission notice shall be included  *
13  * in all copies or substantial portions of the Software.                   *
14  *                                                                          *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22  *                                                                          *
23  * Except as contained in this notice, the name(s) of the above copyright   *
24  * holders shall not be used in advertising or otherwise to promote the     *
25  * sale, use or other dealings in this Software without prior written       *
26  * authorization.                                                           *
27  ****************************************************************************/
28
29 /****************************************************************************
30  *  Author: Juergen Pfeifer                                                 *
31  ****************************************************************************/
32
33 /*
34  * TODO - GetMousePos(POINT * result) from ntconio.c
35  * TODO - implement nodelay
36  * TODO - when $NCGDB is set, implement non-buffered output, like PDCurses
37  */
38
39 #include <curses.priv.h>
40 #define CUR my_term.type.
41
42 MODULE_ID("$Id: win_driver.c,v 1.23 2014/02/15 23:21:44 tom Exp $")
43
44 #define WINMAGIC NCDRV_MAGIC(NCDRV_WINCONSOLE)
45
46 #define EXP_OPTIMIZE 0
47
48 #define okConsoleHandle(TCB) (TCB != 0 && !InvalidConsoleHandle(TCB->hdl))
49
50 #define AssertTCB() assert(TCB != 0 && (TCB->magic == WINMAGIC))
51 #define SetSP()     assert(TCB->csp != 0); sp = TCB->csp; (void) sp
52
53 #define GenMap(vKey,key) MAKELONG(key, vKey)
54
55 #define AdjustY(p) ((p)->buffered ? 0 : (p)->SBI.srWindow.Top)
56
57 static const LONG keylist[] =
58 {
59     GenMap(VK_PRIOR, KEY_PPAGE),
60     GenMap(VK_NEXT, KEY_NPAGE),
61     GenMap(VK_END, KEY_END),
62     GenMap(VK_HOME, KEY_HOME),
63     GenMap(VK_LEFT, KEY_LEFT),
64     GenMap(VK_UP, KEY_UP),
65     GenMap(VK_RIGHT, KEY_RIGHT),
66     GenMap(VK_DOWN, KEY_DOWN),
67     GenMap(VK_DELETE, KEY_DC),
68     GenMap(VK_INSERT, KEY_IC)
69 };
70 #define N_INI ((int)(sizeof(keylist)/sizeof(keylist[0])))
71 #define FKEYS 24
72 #define MAPSIZE (FKEYS + N_INI)
73 #define NUMPAIRS 64
74
75 typedef struct props {
76     CONSOLE_SCREEN_BUFFER_INFO SBI;
77     bool progMode;
78     TERM_HANDLE lastOut;
79     DWORD map[MAPSIZE];
80     DWORD rmap[MAPSIZE];
81     WORD pairs[NUMPAIRS];
82     bool buffered;
83     COORD origin;
84     CHAR_INFO *save_screen;
85 } Properties;
86
87 #define PropOf(TCB) ((Properties*)TCB->prop)
88
89 int
90 _nc_mingw_ioctl(int fd GCC_UNUSED,
91                 long int request GCC_UNUSED,
92                 struct termios *arg GCC_UNUSED)
93 {
94     return 0;
95     endwin();
96     fprintf(stderr, "TERMINFO currently not supported on Windows.\n");
97     exit(1);
98 }
99
100 static WORD
101 MapColor(bool fore, int color)
102 {
103     static const int _cmap[] =
104     {0, 4, 2, 6, 1, 5, 3, 7};
105     int a;
106     if (color < 0 || color > 7)
107         a = fore ? 7 : 0;
108     else
109         a = _cmap[color];
110     if (!fore)
111         a = a << 4;
112     return (WORD) a;
113 }
114
115 static WORD
116 MapAttr(TERMINAL_CONTROL_BLOCK * TCB, WORD res, attr_t ch)
117 {
118     if (ch & A_COLOR) {
119         int p;
120         SCREEN *sp;
121
122         AssertTCB();
123         SetSP();
124         p = PairNumber(ch);
125         if (p > 0 && p < NUMPAIRS && TCB != 0 && sp != 0) {
126             WORD a;
127             a = PropOf(TCB)->pairs[p];
128             res = (res & 0xff00) | a;
129         }
130     }
131
132     if (ch & A_REVERSE)
133         res = ((res & 0xff00) | (((res & 0x07) << 4) | ((res & 0x70) >> 4)));
134
135     if (ch & A_STANDOUT)
136         res = ((res & 0xff00) | (((res & 0x07) << 4) | ((res & 0x70) >> 4))
137                | BACKGROUND_INTENSITY);
138
139     if (ch & A_BOLD)
140         res |= FOREGROUND_INTENSITY;
141
142     if (ch & A_DIM)
143         res |= BACKGROUND_INTENSITY;
144
145     return res;
146 }
147
148 #if USE_WIDEC_SUPPORT
149 /*
150  * TODO: support surrogate pairs
151  * TODO: support combining characters
152  * TODO: support acsc
153  * TODO: check wcwidth of base character, fill if needed for double-width
154  * TODO: _nc_wacs should be part of sp.
155  */
156 static BOOL
157 con_write16(TERMINAL_CONTROL_BLOCK * TCB, int y, int x, cchar_t *str, int limit)
158 {
159     int actual = 0;
160     CHAR_INFO ci[limit];
161     COORD loc, siz;
162     SMALL_RECT rec;
163     int i;
164     cchar_t ch;
165     SCREEN *sp;
166     Properties *p = PropOf(TCB);
167
168     AssertTCB();
169
170     SetSP();
171
172     for (i = actual = 0; i < limit; i++) {
173         ch = str[i];
174         if (isWidecExt(ch))
175             continue;
176         ci[actual].Char.UnicodeChar = CharOf(ch);
177         ci[actual].Attributes = MapAttr(TCB,
178                                         PropOf(TCB)->SBI.wAttributes,
179                                         AttrOf(ch));
180         if (AttrOf(ch) & A_ALTCHARSET) {
181             if (_nc_wacs) {
182                 int which = CharOf(ch);
183                 if (which > 0
184                     && which < ACS_LEN
185                     && CharOf(_nc_wacs[which]) != 0) {
186                     ci[actual].Char.UnicodeChar = CharOf(_nc_wacs[which]);
187                 } else {
188                     ci[actual].Char.UnicodeChar = ' ';
189                 }
190             }
191         }
192         ++actual;
193     }
194
195     loc.X = (short) 0;
196     loc.Y = (short) 0;
197     siz.X = (short) actual;
198     siz.Y = 1;
199
200     rec.Left = (short) x;
201     rec.Top = (short) y + AdjustY(p);
202     rec.Right = (short) (x + limit - 1);
203     rec.Bottom = rec.Top;
204
205     return WriteConsoleOutputW(TCB->hdl, ci, siz, loc, &rec);
206 }
207 #define con_write(tcb, y, x, str, n) con_write16(tcb, y, x, str, n)
208 #else
209 static BOOL
210 con_write8(TERMINAL_CONTROL_BLOCK * TCB, int y, int x, chtype *str, int n)
211 {
212     CHAR_INFO ci[n];
213     COORD loc, siz;
214     SMALL_RECT rec;
215     int i;
216     chtype ch;
217     SCREEN *sp;
218
219     AssertTCB();
220
221     SetSP();
222
223     for (i = 0; i < n; i++) {
224         ch = str[i];
225         ci[i].Char.AsciiChar = ChCharOf(ch);
226         ci[i].Attributes = MapAttr(TCB,
227                                    PropOf(TCB)->SBI.wAttributes,
228                                    ChAttrOf(ch));
229         if (ChAttrOf(ch) & A_ALTCHARSET) {
230             if (sp->_acs_map)
231                 ci[i].Char.AsciiChar =
232                 ChCharOf(NCURSES_SP_NAME(_nc_acs_char) (sp, ChCharOf(ch)));
233         }
234     }
235
236     loc.X = (short) 0;
237     loc.Y = (short) 0;
238     siz.X = (short) n;
239     siz.Y = 1;
240
241     rec.Left = (short) x;
242     rec.Top = (short) y;
243     rec.Right = (short) (x + n - 1);
244     rec.Bottom = rec.Top;
245
246     return WriteConsoleOutput(TCB->hdl, ci, siz, loc, &rec);
247 }
248 #define con_write(tcb, y, x, str, n) con_write8(tcb, y, x, str, n)
249 #endif
250
251 #if EXP_OPTIMIZE
252 /*
253  * Comparing new/current screens, determine the last column-index for a change
254  * beginning on the given row,col position.  Unlike a serial terminal, there is
255  * no cost for "moving" the "cursor" on the line as we update it.
256  */
257 static int
258 find_end_of_change(SCREEN *sp, int row, int col)
259 {
260     int result = col;
261     struct ldat *curdat = CurScreen(sp)->_line + row;
262     struct ldat *newdat = NewScreen(sp)->_line + row;
263
264     while (col <= newdat->lastchar) {
265 #if USE_WIDEC_SUPPORT
266         if (isWidecExt(curdat->text[col]) || isWidecExt(newdat->text[col])) {
267             result = col;
268         } else if (memcmp(&curdat->text[col],
269                           &newdat->text[col],
270                           sizeof(curdat->text[0]))) {
271             result = col;
272         } else {
273             break;
274         }
275 #else
276         if (curdat->text[col] != newdat->text[col]) {
277             result = col;
278         } else {
279             break;
280         }
281 #endif
282         ++col;
283     }
284     return result;
285 }
286
287 /*
288  * Given a row,col position at the end of a change-chunk, look for the
289  * beginning of the next change-chunk.
290  */
291 static int
292 find_next_change(SCREEN *sp, int row, int col)
293 {
294     struct ldat *curdat = CurScreen(sp)->_line + row;
295     struct ldat *newdat = NewScreen(sp)->_line + row;
296     int result = newdat->lastchar + 1;
297
298     while (++col <= newdat->lastchar) {
299 #if USE_WIDEC_SUPPORT
300         if (isWidecExt(curdat->text[col]) != isWidecExt(newdat->text[col])) {
301             result = col;
302             break;
303         } else if (memcmp(&curdat->text[col],
304                           &newdat->text[col],
305                           sizeof(curdat->text[0]))) {
306             result = col;
307             break;
308         }
309 #else
310         if (curdat->text[col] != newdat->text[col]) {
311             result = col;
312             break;
313         }
314 #endif
315     }
316     return result;
317 }
318
319 #define EndChange(first) \
320         find_end_of_change(sp, y, first)
321 #define NextChange(last) \
322         find_next_change(sp, y, last)
323
324 #endif /* EXP_OPTIMIZE */
325
326 #define MARK_NOCHANGE(win,row) \
327                 win->_line[row].firstchar = _NOCHANGE; \
328                 win->_line[row].lastchar  = _NOCHANGE
329
330 static void
331 selectActiveHandle(TERMINAL_CONTROL_BLOCK * TCB)
332 {
333     if (PropOf(TCB)->lastOut != TCB->hdl) {
334         PropOf(TCB)->lastOut = TCB->hdl;
335         SetConsoleActiveScreenBuffer(PropOf(TCB)->lastOut);
336     }
337 }
338
339 static int
340 drv_doupdate(TERMINAL_CONTROL_BLOCK * TCB)
341 {
342     int result = ERR;
343     int y, nonempty, n, x0, x1, Width, Height;
344     SCREEN *sp;
345
346     AssertTCB();
347     SetSP();
348
349     T((T_CALLED("win32con::drv_doupdate(%p)"), TCB));
350     if (okConsoleHandle(TCB)) {
351
352         Width = screen_columns(sp);
353         Height = screen_lines(sp);
354         nonempty = min(Height, NewScreen(sp)->_maxy + 1);
355
356         if ((CurScreen(sp)->_clear || NewScreen(sp)->_clear)) {
357             int x;
358 #if USE_WIDEC_SUPPORT
359             cchar_t empty[Width];
360             wchar_t blank[2] =
361             {
362                 L' ', L'\0'
363             };
364
365             for (x = 0; x < Width; x++)
366                 setcchar(&empty[x], blank, 0, 0, 0);
367 #else
368             chtype empty[Width];
369
370             for (x = 0; x < Width; x++)
371                 empty[x] = ' ';
372 #endif
373
374             for (y = 0; y < nonempty; y++) {
375                 con_write(TCB, y, 0, empty, Width);
376                 memcpy(empty,
377                        CurScreen(sp)->_line[y].text,
378                        Width * sizeof(empty[0]));
379             }
380             CurScreen(sp)->_clear = FALSE;
381             NewScreen(sp)->_clear = FALSE;
382             touchwin(NewScreen(sp));
383         }
384
385         for (y = 0; y < nonempty; y++) {
386             x0 = NewScreen(sp)->_line[y].firstchar;
387             if (x0 != _NOCHANGE) {
388 #if EXP_OPTIMIZE
389                 int x2;
390                 int limit = NewScreen(sp)->_line[y].lastchar;
391                 while ((x1 = EndChange(x0)) <= limit) {
392                     while ((x2 = NextChange(x1)) <= limit && x2 <= (x1 + 2)) {
393                         x1 = x2;
394                     }
395                     n = x1 - x0 + 1;
396                     memcpy(&CurScreen(sp)->_line[y].text[x0],
397                            &NewScreen(sp)->_line[y].text[x0],
398                            n * sizeof(CurScreen(sp)->_line[y].text[x0]));
399                     con_write(TCB,
400                               y,
401                               x0,
402                               &CurScreen(sp)->_line[y].text[x0], n);
403                     x0 = NextChange(x1);
404                 }
405
406                 /* mark line changed successfully */
407                 if (y <= NewScreen(sp)->_maxy) {
408                     MARK_NOCHANGE(NewScreen(sp), y);
409                 }
410                 if (y <= CurScreen(sp)->_maxy) {
411                     MARK_NOCHANGE(CurScreen(sp), y);
412                 }
413 #else
414                 x1 = NewScreen(sp)->_line[y].lastchar;
415                 n = x1 - x0 + 1;
416                 if (n > 0) {
417                     memcpy(&CurScreen(sp)->_line[y].text[x0],
418                            &NewScreen(sp)->_line[y].text[x0],
419                            n * sizeof(CurScreen(sp)->_line[y].text[x0]));
420                     con_write(TCB,
421                               y,
422                               x0,
423                               &CurScreen(sp)->_line[y].text[x0], n);
424
425                     /* mark line changed successfully */
426                     if (y <= NewScreen(sp)->_maxy) {
427                         MARK_NOCHANGE(NewScreen(sp), y);
428                     }
429                     if (y <= CurScreen(sp)->_maxy) {
430                         MARK_NOCHANGE(CurScreen(sp), y);
431                     }
432                 }
433 #endif
434             }
435         }
436
437         /* put everything back in sync */
438         for (y = nonempty; y <= NewScreen(sp)->_maxy; y++) {
439             MARK_NOCHANGE(NewScreen(sp), y);
440         }
441         for (y = nonempty; y <= CurScreen(sp)->_maxy; y++) {
442             MARK_NOCHANGE(CurScreen(sp), y);
443         }
444
445         if (!NewScreen(sp)->_leaveok) {
446             CurScreen(sp)->_curx = NewScreen(sp)->_curx;
447             CurScreen(sp)->_cury = NewScreen(sp)->_cury;
448
449             TCB->drv->hwcur(TCB,
450                             0, 0,
451                             CurScreen(sp)->_cury, CurScreen(sp)->_curx);
452         }
453         selectActiveHandle(TCB);
454         result = OK;
455     }
456     returnCode(result);
457 }
458
459 static bool
460 drv_CanHandle(TERMINAL_CONTROL_BLOCK * TCB,
461               const char *tname,
462               int *errret GCC_UNUSED)
463 {
464     bool code = FALSE;
465
466     T((T_CALLED("win32con::drv_CanHandle(%p)"), TCB));
467
468     assert(TCB != 0);
469     assert(tname != 0);
470
471     TCB->magic = WINMAGIC;
472     if (*tname == 0 || *tname == 0 || *tname == '#') {
473         code = TRUE;
474     } else {
475         TERMINAL my_term;
476         int status;
477
478         code = FALSE;
479 #if (NCURSES_USE_DATABASE || NCURSES_USE_TERMCAP)
480         status = _nc_setup_tinfo(tname, &my_term.type);
481 #else
482         status = TGETENT_NO;
483 #endif
484         if (status != TGETENT_YES) {
485             const TERMTYPE *fallback = _nc_fallback(tname);
486
487             if (fallback) {
488                 my_term.type = *fallback;
489                 status = TGETENT_YES;
490             } else if (!strcmp(tname, "unknown")) {
491                 code = TRUE;
492             }
493         }
494         if (status == TGETENT_YES) {
495             if (generic_type || hard_copy)
496                 code = TRUE;
497         }
498     }
499
500     if (code) {
501         if ((TCB->term.type.Booleans) == 0) {
502             _nc_init_termtype(&(TCB->term.type));
503         }
504     }
505
506     returnBool(code);
507 }
508
509 static int
510 drv_dobeepflash(TERMINAL_CONTROL_BLOCK * TCB,
511                 int beepFlag GCC_UNUSED)
512 {
513     SCREEN *sp;
514     int res = ERR;
515
516     AssertTCB();
517     SetSP();
518
519     return res;
520 }
521
522 static int
523 drv_print(TERMINAL_CONTROL_BLOCK * TCB,
524           char *data GCC_UNUSED,
525           int len GCC_UNUSED)
526 {
527     SCREEN *sp;
528
529     AssertTCB();
530     SetSP();
531
532     return ERR;
533 }
534
535 static int
536 drv_defaultcolors(TERMINAL_CONTROL_BLOCK * TCB,
537                   int fg GCC_UNUSED,
538                   int bg GCC_UNUSED)
539 {
540     SCREEN *sp;
541     int code = ERR;
542
543     AssertTCB();
544     SetSP();
545
546     return (code);
547 }
548
549 static bool
550 get_SBI(TERMINAL_CONTROL_BLOCK * TCB)
551 {
552     bool rc = FALSE;
553     Properties *p = PropOf(TCB);
554     if (GetConsoleScreenBufferInfo(TCB->hdl, &(p->SBI))) {
555         T(("GetConsoleScreenBufferInfo"));
556         T(("... buffer(X:%d Y:%d)",
557            p->SBI.dwSize.X,
558            p->SBI.dwSize.Y));
559         T(("... window(X:%d Y:%d)",
560            p->SBI.dwMaximumWindowSize.X,
561            p->SBI.dwMaximumWindowSize.Y));
562         T(("... cursor(X:%d Y:%d)",
563            p->SBI.dwCursorPosition.X,
564            p->SBI.dwCursorPosition.Y));
565         T(("... display(Top:%d Bottom:%d Left:%d Right:%d)",
566            p->SBI.srWindow.Top,
567            p->SBI.srWindow.Bottom,
568            p->SBI.srWindow.Left,
569            p->SBI.srWindow.Right));
570         if (p->buffered) {
571             p->origin.X = 0;
572             p->origin.Y = 0;
573         } else {
574             p->origin.X = p->SBI.srWindow.Left;
575             p->origin.Y = p->SBI.srWindow.Top;
576         }
577         rc = TRUE;
578     } else {
579         T(("GetConsoleScreenBufferInfo ERR"));
580     }
581     return rc;
582 }
583
584 static void
585 drv_setcolor(TERMINAL_CONTROL_BLOCK * TCB,
586              int fore,
587              int color,
588              int (*outc) (SCREEN *, int) GCC_UNUSED)
589 {
590     AssertTCB();
591
592     if (okConsoleHandle(TCB) &&
593         PropOf(TCB) != 0) {
594         WORD a = MapColor(fore, color);
595         a = ((PropOf(TCB)->SBI.wAttributes) & (fore ? 0xfff8 : 0xff8f)) | a;
596         SetConsoleTextAttribute(TCB->hdl, a);
597         get_SBI(TCB);
598     }
599 }
600
601 static bool
602 drv_rescol(TERMINAL_CONTROL_BLOCK * TCB)
603 {
604     bool res = FALSE;
605
606     AssertTCB();
607     if (okConsoleHandle(TCB)) {
608         WORD a = FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN;
609         SetConsoleTextAttribute(TCB->hdl, a);
610         get_SBI(TCB);
611         res = TRUE;
612     }
613     return res;
614 }
615
616 static bool
617 drv_rescolors(TERMINAL_CONTROL_BLOCK * TCB)
618 {
619     int result = FALSE;
620     SCREEN *sp;
621
622     AssertTCB();
623     SetSP();
624
625     return result;
626 }
627
628 static int
629 drv_size(TERMINAL_CONTROL_BLOCK * TCB, int *Lines, int *Cols)
630 {
631     int result = ERR;
632
633     AssertTCB();
634
635     T((T_CALLED("win32con::drv_size(%p)"), TCB));
636
637     if (okConsoleHandle(TCB) &&
638         PropOf(TCB) != 0 &&
639         Lines != NULL &&
640         Cols != NULL) {
641         if (PropOf(TCB)->buffered) {
642             *Lines = (int) (PropOf(TCB)->SBI.dwSize.Y);
643             *Cols = (int) (PropOf(TCB)->SBI.dwSize.X);
644         } else {
645             *Lines = (int) (PropOf(TCB)->SBI.srWindow.Bottom + 1 -
646                             PropOf(TCB)->SBI.srWindow.Top);
647             *Cols = (int) (PropOf(TCB)->SBI.srWindow.Right + 1 -
648                            PropOf(TCB)->SBI.srWindow.Left);
649         }
650         result = OK;
651     }
652     returnCode(result);
653 }
654
655 static int
656 drv_setsize(TERMINAL_CONTROL_BLOCK * TCB GCC_UNUSED,
657             int l GCC_UNUSED,
658             int c GCC_UNUSED)
659 {
660     AssertTCB();
661     return ERR;
662 }
663
664 static int
665 drv_sgmode(TERMINAL_CONTROL_BLOCK * TCB, int setFlag, TTY * buf)
666 {
667     DWORD dwFlag = 0;
668     tcflag_t iflag;
669     tcflag_t lflag;
670
671     AssertTCB();
672
673     if (TCB == 0 || buf == NULL)
674         return ERR;
675
676     if (setFlag) {
677         iflag = buf->c_iflag;
678         lflag = buf->c_lflag;
679
680         GetConsoleMode(TCB->inp, &dwFlag);
681
682         if (lflag & ICANON)
683             dwFlag |= ENABLE_LINE_INPUT;
684         else
685             dwFlag &= ~ENABLE_LINE_INPUT;
686
687         if (lflag & ECHO)
688             dwFlag |= ENABLE_ECHO_INPUT;
689         else
690             dwFlag &= ~ENABLE_ECHO_INPUT;
691
692         if (iflag & BRKINT)
693             dwFlag |= ENABLE_PROCESSED_INPUT;
694         else
695             dwFlag &= ~ENABLE_PROCESSED_INPUT;
696
697         dwFlag |= ENABLE_MOUSE_INPUT;
698
699         buf->c_iflag = iflag;
700         buf->c_lflag = lflag;
701         SetConsoleMode(TCB->inp, dwFlag);
702         TCB->term.Nttyb = *buf;
703     } else {
704         iflag = TCB->term.Nttyb.c_iflag;
705         lflag = TCB->term.Nttyb.c_lflag;
706         GetConsoleMode(TCB->inp, &dwFlag);
707
708         if (dwFlag & ENABLE_LINE_INPUT)
709             lflag |= ICANON;
710         else
711             lflag &= ~ICANON;
712
713         if (dwFlag & ENABLE_ECHO_INPUT)
714             lflag |= ECHO;
715         else
716             lflag &= ~ECHO;
717
718         if (dwFlag & ENABLE_PROCESSED_INPUT)
719             iflag |= BRKINT;
720         else
721             iflag &= ~BRKINT;
722
723         TCB->term.Nttyb.c_iflag = iflag;
724         TCB->term.Nttyb.c_lflag = lflag;
725
726         *buf = TCB->term.Nttyb;
727     }
728     return OK;
729 }
730
731 static int
732 drv_mode(TERMINAL_CONTROL_BLOCK * TCB, int progFlag, int defFlag)
733 {
734     SCREEN *sp;
735     TERMINAL *_term = (TERMINAL *) TCB;
736     int code = ERR;
737
738     AssertTCB();
739     sp = TCB->csp;
740
741     PropOf(TCB)->progMode = progFlag;
742     PropOf(TCB)->lastOut = progFlag ? TCB->hdl : TCB->out;
743     SetConsoleActiveScreenBuffer(PropOf(TCB)->lastOut);
744
745     if (progFlag) /* prog mode */  {
746         if (defFlag) {
747             if ((drv_sgmode(TCB, FALSE, &(_term->Nttyb)) == OK)) {
748                 _term->Nttyb.c_oflag &= ~OFLAGS_TABS;
749                 code = OK;
750             }
751         } else {
752             /* reset_prog_mode */
753             if (drv_sgmode(TCB, TRUE, &(_term->Nttyb)) == OK) {
754                 if (sp) {
755                     if (sp->_keypad_on)
756                         _nc_keypad(sp, TRUE);
757                     NC_BUFFERED(sp, TRUE);
758                 }
759                 code = OK;
760             }
761         }
762     } else {                    /* shell mode */
763         if (defFlag) {
764             /* def_shell_mode */
765             if (drv_sgmode(TCB, FALSE, &(_term->Ottyb)) == OK) {
766                 code = OK;
767             }
768         } else {
769             /* reset_shell_mode */
770             if (sp) {
771                 _nc_keypad(sp, FALSE);
772                 NCURSES_SP_NAME(_nc_flush) (sp);
773                 NC_BUFFERED(sp, FALSE);
774             }
775             code = drv_sgmode(TCB, TRUE, &(_term->Ottyb));
776         }
777     }
778
779     return (code);
780 }
781
782 static void
783 drv_screen_init(SCREEN *sp GCC_UNUSED)
784 {
785 }
786
787 static void
788 drv_wrap(SCREEN *sp GCC_UNUSED)
789 {
790 }
791
792 static int
793 rkeycompare(const void *el1, const void *el2)
794 {
795     WORD key1 = (LOWORD((*((const LONG *) el1)))) & 0x7fff;
796     WORD key2 = (LOWORD((*((const LONG *) el2)))) & 0x7fff;
797
798     return ((key1 < key2) ? -1 : ((key1 == key2) ? 0 : 1));
799 }
800
801 static int
802 keycompare(const void *el1, const void *el2)
803 {
804     WORD key1 = HIWORD((*((const LONG *) el1)));
805     WORD key2 = HIWORD((*((const LONG *) el2)));
806
807     return ((key1 < key2) ? -1 : ((key1 == key2) ? 0 : 1));
808 }
809
810 static int
811 MapKey(TERMINAL_CONTROL_BLOCK * TCB, WORD vKey)
812 {
813     WORD nKey = 0;
814     void *res;
815     LONG key = GenMap(vKey, 0);
816     int code = -1;
817
818     AssertTCB();
819
820     res = bsearch(&key,
821                   PropOf(TCB)->map,
822                   (size_t) (N_INI + FKEYS),
823                   sizeof(keylist[0]),
824                   keycompare);
825     if (res) {
826         key = *((LONG *) res);
827         nKey = LOWORD(key);
828         code = (int) (nKey & 0x7fff);
829         if (nKey & 0x8000)
830             code = -code;
831     }
832     return code;
833 }
834
835 static void
836 drv_release(TERMINAL_CONTROL_BLOCK * TCB)
837 {
838     T((T_CALLED("win32con::drv_release(%p)"), TCB));
839
840     AssertTCB();
841     if (TCB->prop)
842         free(TCB->prop);
843
844     returnVoid;
845 }
846
847 /*
848  * Attempt to save the screen contents.  PDCurses does this if
849  * PDC_RESTORE_SCREEN is set, giving the same visual appearance on restoration
850  * as if the library had allocated a console buffer.
851  */
852 static bool
853 save_original_screen(TERMINAL_CONTROL_BLOCK * TCB)
854 {
855     bool result = FALSE;
856     Properties *p = PropOf(TCB);
857     COORD bufferSize;
858     COORD bufferCoord;
859     SMALL_RECT readRegion;
860     size_t want;
861
862     bufferSize.X = p->SBI.dwSize.X;
863     bufferSize.Y = p->SBI.dwSize.Y;
864     want = bufferSize.X * bufferSize.Y;
865
866     if ((p->save_screen = malloc(want * sizeof(CHAR_INFO))) != 0) {
867         bufferCoord.X = bufferCoord.Y = 0;
868
869         readRegion.Top = 0;
870         readRegion.Left = 0;
871         readRegion.Bottom = bufferSize.Y - 1;
872         readRegion.Right = bufferSize.X - 1;
873
874         T(("... reading console buffer %dx%d into %d,%d - %d,%d at %d,%d",
875            bufferSize.Y, bufferSize.X,
876            readRegion.Top,
877            readRegion.Left,
878            readRegion.Bottom,
879            readRegion.Right,
880            bufferCoord.Y,
881            bufferCoord.X));
882
883         if (ReadConsoleOutput(TCB->hdl,
884                               p->save_screen,
885                               bufferSize,
886                               bufferCoord,
887                               &readRegion)) {
888             result = TRUE;
889         } else {
890             T((" error %#lx", (unsigned long) GetLastError()));
891             FreeAndNull(p->save_screen);
892
893             bufferSize.X = p->SBI.srWindow.Right - p->SBI.srWindow.Left + 1;
894             bufferSize.Y = p->SBI.srWindow.Bottom - p->SBI.srWindow.Top + 1;
895             want = bufferSize.X * bufferSize.Y;
896
897             if ((p->save_screen = malloc(want * sizeof(CHAR_INFO))) != 0) {
898                 bufferCoord.X = bufferCoord.Y = 0;
899
900                 readRegion.Top = p->SBI.srWindow.Top;
901                 readRegion.Left = p->SBI.srWindow.Left;
902                 readRegion.Bottom = p->SBI.srWindow.Bottom;
903                 readRegion.Right = p->SBI.srWindow.Right;
904
905                 T(("... reading console window %dx%d into %d,%d - %d,%d at %d,%d",
906                    bufferSize.Y, bufferSize.X,
907                    readRegion.Top,
908                    readRegion.Left,
909                    readRegion.Bottom,
910                    readRegion.Right,
911                    bufferCoord.Y,
912                    bufferCoord.X));
913
914                 if (ReadConsoleOutput(TCB->hdl,
915                                       p->save_screen,
916                                       bufferSize,
917                                       bufferCoord,
918                                       &readRegion)) {
919                     result = TRUE;
920                 } else {
921                     T((" error %#lx", (unsigned long) GetLastError()));
922                 }
923             }
924         }
925     }
926
927     T(("... save original screen contents %s", result ? "ok" : "err"));
928     return result;
929 }
930
931 static void
932 drv_init(TERMINAL_CONTROL_BLOCK * TCB)
933 {
934     DWORD num_buttons;
935
936     T((T_CALLED("win32con::drv_init(%p)"), TCB));
937
938     AssertTCB();
939
940     if (TCB) {
941         BOOL b = AllocConsole();
942         WORD a;
943         int i;
944         bool buffered = TRUE;
945
946         if (!b)
947             b = AttachConsole(ATTACH_PARENT_PROCESS);
948
949         TCB->inp = GetStdHandle(STD_INPUT_HANDLE);
950         TCB->out = GetStdHandle(STD_OUTPUT_HANDLE);
951
952         if (getenv("NCGDB")) {
953             TCB->hdl = TCB->out;
954             buffered = FALSE;
955         } else {
956             TCB->hdl = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE,
957                                                  0,
958                                                  NULL,
959                                                  CONSOLE_TEXTMODE_BUFFER,
960                                                  NULL);
961         }
962
963         if (InvalidConsoleHandle(TCB->hdl)) {
964             returnVoid;
965         } else if ((TCB->prop = typeCalloc(Properties, 1)) != 0) {
966             PropOf(TCB)->buffered = buffered;
967             if (!get_SBI(TCB)) {
968                 FreeAndNull(TCB->prop);         /* force error in drv_size */
969                 returnVoid;
970             }
971             if (!buffered) {
972                 if (!save_original_screen(TCB)) {
973                     FreeAndNull(TCB->prop);     /* force error in drv_size */
974                     returnVoid;
975                 }
976             }
977         }
978
979         TCB->info.initcolor = TRUE;
980         TCB->info.canchange = FALSE;
981         TCB->info.hascolor = TRUE;
982         TCB->info.caninit = TRUE;
983
984         TCB->info.maxpairs = NUMPAIRS;
985         TCB->info.maxcolors = 8;
986         TCB->info.numlabels = 0;
987         TCB->info.labelwidth = 0;
988         TCB->info.labelheight = 0;
989         TCB->info.nocolorvideo = 1;
990         TCB->info.tabsize = 8;
991
992         if (GetNumberOfConsoleMouseButtons(&num_buttons)) {
993             T(("mouse has %ld buttons", num_buttons));
994             TCB->info.numbuttons = num_buttons;
995         } else {
996             TCB->info.numbuttons = 1;
997         }
998
999         TCB->info.defaultPalette = _nc_cga_palette;
1000
1001         for (i = 0; i < (N_INI + FKEYS); i++) {
1002             if (i < N_INI)
1003                 PropOf(TCB)->rmap[i] = PropOf(TCB)->map[i] = keylist[i];
1004             else
1005                 PropOf(TCB)->rmap[i] = PropOf(TCB)->map[i] =
1006                     GenMap((VK_F1 + (i - N_INI)), (KEY_F(1) + (i - N_INI)));
1007         }
1008         qsort(PropOf(TCB)->map,
1009               (size_t) (MAPSIZE),
1010               sizeof(keylist[0]),
1011               keycompare);
1012         qsort(PropOf(TCB)->rmap,
1013               (size_t) (MAPSIZE),
1014               sizeof(keylist[0]),
1015               rkeycompare);
1016
1017         a = MapColor(true, COLOR_WHITE) | MapColor(false, COLOR_BLACK);
1018         for (i = 0; i < NUMPAIRS; i++)
1019             PropOf(TCB)->pairs[i] = a;
1020     }
1021     returnVoid;
1022 }
1023
1024 static void
1025 drv_initpair(TERMINAL_CONTROL_BLOCK * TCB,
1026              int pair,
1027              int f,
1028              int b)
1029 {
1030     SCREEN *sp;
1031
1032     AssertTCB();
1033     SetSP();
1034
1035     if ((pair > 0) && (pair < NUMPAIRS) && (f >= 0) && (f < 8)
1036         && (b >= 0) && (b < 8)) {
1037         PropOf(TCB)->pairs[pair] = MapColor(true, f) | MapColor(false, b);
1038     }
1039 }
1040
1041 static void
1042 drv_initcolor(TERMINAL_CONTROL_BLOCK * TCB,
1043               int color GCC_UNUSED,
1044               int r GCC_UNUSED,
1045               int g GCC_UNUSED,
1046               int b GCC_UNUSED)
1047 {
1048     SCREEN *sp;
1049
1050     AssertTCB();
1051     SetSP();
1052 }
1053
1054 static void
1055 drv_do_color(TERMINAL_CONTROL_BLOCK * TCB,
1056              int old_pair GCC_UNUSED,
1057              int pair GCC_UNUSED,
1058              int reverse GCC_UNUSED,
1059              int (*outc) (SCREEN *, int) GCC_UNUSED
1060 )
1061 {
1062     SCREEN *sp;
1063
1064     AssertTCB();
1065     SetSP();
1066 }
1067
1068 static void
1069 drv_initmouse(TERMINAL_CONTROL_BLOCK * TCB)
1070 {
1071     SCREEN *sp;
1072
1073     AssertTCB();
1074     SetSP();
1075
1076     sp->_mouse_type = M_TERM_DRIVER;
1077 }
1078
1079 static int
1080 drv_testmouse(TERMINAL_CONTROL_BLOCK * TCB, int delay)
1081 {
1082     int rc = 0;
1083     SCREEN *sp;
1084
1085     AssertTCB();
1086     SetSP();
1087
1088     if (sp->_drv_mouse_head < sp->_drv_mouse_tail) {
1089         rc = TW_MOUSE;
1090     } else {
1091         rc = TCBOf(sp)->drv->twait(TCBOf(sp),
1092                                    TWAIT_MASK,
1093                                    delay,
1094                                    (int *) 0
1095                                    EVENTLIST_2nd(evl));
1096     }
1097
1098     return rc;
1099 }
1100
1101 static int
1102 drv_mvcur(TERMINAL_CONTROL_BLOCK * TCB,
1103           int yold GCC_UNUSED, int xold GCC_UNUSED,
1104           int y, int x)
1105 {
1106     int ret = ERR;
1107     if (okConsoleHandle(TCB)) {
1108         Properties *p = PropOf(TCB);
1109         COORD loc;
1110         loc.X = (short) x;
1111         loc.Y = (short) y + AdjustY(p);
1112         SetConsoleCursorPosition(TCB->hdl, loc);
1113         ret = OK;
1114     }
1115     return ret;
1116 }
1117
1118 static void
1119 drv_hwlabel(TERMINAL_CONTROL_BLOCK * TCB,
1120             int labnum GCC_UNUSED,
1121             char *text GCC_UNUSED)
1122 {
1123     SCREEN *sp;
1124
1125     AssertTCB();
1126     SetSP();
1127 }
1128
1129 static void
1130 drv_hwlabelOnOff(TERMINAL_CONTROL_BLOCK * TCB,
1131                  int OnFlag GCC_UNUSED)
1132 {
1133     SCREEN *sp;
1134
1135     AssertTCB();
1136     SetSP();
1137 }
1138
1139 static chtype
1140 drv_conattr(TERMINAL_CONTROL_BLOCK * TCB GCC_UNUSED)
1141 {
1142     chtype res = A_NORMAL;
1143     res |= (A_BOLD | A_DIM | A_REVERSE | A_STANDOUT | A_COLOR);
1144     return res;
1145 }
1146
1147 static void
1148 drv_setfilter(TERMINAL_CONTROL_BLOCK * TCB)
1149 {
1150     SCREEN *sp;
1151
1152     AssertTCB();
1153     SetSP();
1154 }
1155
1156 static void
1157 drv_initacs(TERMINAL_CONTROL_BLOCK * TCB,
1158             chtype *real_map GCC_UNUSED,
1159             chtype *fake_map GCC_UNUSED)
1160 {
1161 #define DATA(a,b) { a, b }
1162     static struct {
1163         int acs_code;
1164         int use_code;
1165     } table[] = {
1166         DATA('a', 0xb1),        /* ACS_CKBOARD  */
1167             DATA('f', 0xf8),    /* ACS_DEGREE   */
1168             DATA('g', 0xf1),    /* ACS_PLMINUS  */
1169             DATA('j', 0xd9),    /* ACS_LRCORNER */
1170             DATA('l', 0xda),    /* ACS_ULCORNER */
1171             DATA('k', 0xbf),    /* ACS_URCORNER */
1172             DATA('m', 0xc0),    /* ACS_LLCORNER */
1173             DATA('n', 0xc5),    /* ACS_PLUS     */
1174             DATA('q', 0xc4),    /* ACS_HLINE    */
1175             DATA('t', 0xc3),    /* ACS_LTEE     */
1176             DATA('u', 0xb4),    /* ACS_RTEE     */
1177             DATA('v', 0xc1),    /* ACS_BTEE     */
1178             DATA('w', 0xc2),    /* ACS_TTEE     */
1179             DATA('x', 0xb3),    /* ACS_VLINE    */
1180             DATA('y', 0xf3),    /* ACS_LEQUAL   */
1181             DATA('z', 0xf2),    /* ACS_GEQUAL   */
1182             DATA('0', 0xdb),    /* ACS_BLOCK    */
1183             DATA('{', 0xe3),    /* ACS_PI       */
1184             DATA('}', 0x9c),    /* ACS_STERLING */
1185             DATA(',', 0xae),    /* ACS_LARROW   */
1186             DATA('+', 0xaf),    /* ACS_RARROW   */
1187             DATA('~', 0xf9),    /* ACS_BULLET   */
1188     };
1189 #undef DATA
1190     unsigned n;
1191
1192     SCREEN *sp;
1193     AssertTCB();
1194     SetSP();
1195
1196     for (n = 0; n < SIZEOF(table); ++n) {
1197         real_map[table[n].acs_code] = table[n].use_code | A_ALTCHARSET;
1198         if (sp != 0)
1199             sp->_screen_acs_map[table[n].acs_code] = TRUE;
1200     }
1201 }
1202
1203 static ULONGLONG
1204 tdiff(FILETIME fstart, FILETIME fend)
1205 {
1206     ULARGE_INTEGER ustart;
1207     ULARGE_INTEGER uend;
1208     ULONGLONG diff;
1209
1210     ustart.LowPart = fstart.dwLowDateTime;
1211     ustart.HighPart = fstart.dwHighDateTime;
1212     uend.LowPart = fend.dwLowDateTime;
1213     uend.HighPart = fend.dwHighDateTime;
1214
1215     diff = (uend.QuadPart - ustart.QuadPart) / 10000;
1216     return diff;
1217 }
1218
1219 static int
1220 Adjust(int milliseconds, int diff)
1221 {
1222     if (milliseconds == INFINITY)
1223         return milliseconds;
1224     milliseconds -= diff;
1225     if (milliseconds < 0)
1226         milliseconds = 0;
1227     return milliseconds;
1228 }
1229
1230 #define BUTTON_MASK (FROM_LEFT_1ST_BUTTON_PRESSED | \
1231                      FROM_LEFT_2ND_BUTTON_PRESSED | \
1232                      FROM_LEFT_3RD_BUTTON_PRESSED | \
1233                      FROM_LEFT_4TH_BUTTON_PRESSED | \
1234                      RIGHTMOST_BUTTON_PRESSED)
1235
1236 static int
1237 decode_mouse(TERMINAL_CONTROL_BLOCK * TCB, int mask)
1238 {
1239     SCREEN *sp;
1240     int result = 0;
1241
1242     AssertTCB();
1243     SetSP();
1244
1245     if (mask & FROM_LEFT_1ST_BUTTON_PRESSED)
1246         result |= BUTTON1_PRESSED;
1247     if (mask & FROM_LEFT_2ND_BUTTON_PRESSED)
1248         result |= BUTTON2_PRESSED;
1249     if (mask & FROM_LEFT_3RD_BUTTON_PRESSED)
1250         result |= BUTTON3_PRESSED;
1251     if (mask & FROM_LEFT_4TH_BUTTON_PRESSED)
1252         result |= BUTTON4_PRESSED;
1253
1254     if (mask & RIGHTMOST_BUTTON_PRESSED) {
1255         switch (TCB->info.numbuttons) {
1256         case 1:
1257             result |= BUTTON1_PRESSED;
1258             break;
1259         case 2:
1260             result |= BUTTON2_PRESSED;
1261             break;
1262         case 3:
1263             result |= BUTTON3_PRESSED;
1264             break;
1265         case 4:
1266             result |= BUTTON4_PRESSED;
1267             break;
1268         }
1269     }
1270
1271     return result;
1272 }
1273
1274 static int
1275 drv_twait(TERMINAL_CONTROL_BLOCK * TCB,
1276           int mode,
1277           int milliseconds,
1278           int *timeleft
1279           EVENTLIST_2nd(_nc_eventlist * evl))
1280 {
1281     SCREEN *sp;
1282     INPUT_RECORD inp_rec;
1283     BOOL b;
1284     DWORD nRead = 0, rc = -1;
1285     int code = 0;
1286     FILETIME fstart;
1287     FILETIME fend;
1288     int diff;
1289     bool isImmed = (milliseconds == 0);
1290
1291 #define CONSUME() ReadConsoleInput(TCB->inp,&inp_rec,1,&nRead)
1292
1293     AssertTCB();
1294     SetSP();
1295
1296     TR(TRACE_IEVENT, ("start twait: %d milliseconds, mode: %d",
1297                       milliseconds, mode));
1298
1299     if (milliseconds < 0)
1300         milliseconds = INFINITY;
1301
1302     memset(&inp_rec, 0, sizeof(inp_rec));
1303
1304     while (true) {
1305         GetSystemTimeAsFileTime(&fstart);
1306         rc = WaitForSingleObject(TCB->inp, milliseconds);
1307         GetSystemTimeAsFileTime(&fend);
1308         diff = (int) tdiff(fstart, fend);
1309         milliseconds = Adjust(milliseconds, diff);
1310
1311         if (!isImmed && milliseconds == 0)
1312             break;
1313
1314         if (rc == WAIT_OBJECT_0) {
1315             if (mode) {
1316                 b = GetNumberOfConsoleInputEvents(TCB->inp, &nRead);
1317                 if (b && nRead > 0) {
1318                     b = PeekConsoleInput(TCB->inp, &inp_rec, 1, &nRead);
1319                     if (b && nRead > 0) {
1320                         switch (inp_rec.EventType) {
1321                         case KEY_EVENT:
1322                             if (mode & TW_INPUT) {
1323                                 WORD vk = inp_rec.Event.KeyEvent.wVirtualKeyCode;
1324                                 char ch = inp_rec.Event.KeyEvent.uChar.AsciiChar;
1325
1326                                 if (inp_rec.Event.KeyEvent.bKeyDown) {
1327                                     if (0 == ch) {
1328                                         int nKey = MapKey(TCB, vk);
1329                                         if ((nKey < 0) || FALSE == sp->_keypad_on) {
1330                                             CONSUME();
1331                                             continue;
1332                                         }
1333                                     }
1334                                     code = TW_INPUT;
1335                                     goto end;
1336                                 } else {
1337                                     CONSUME();
1338                                 }
1339                             }
1340                             continue;
1341                         case MOUSE_EVENT:
1342                             if (decode_mouse(TCB,
1343                                              (inp_rec.Event.MouseEvent.dwButtonState
1344                                               & BUTTON_MASK)) == 0) {
1345                                 CONSUME();
1346                             } else if (mode & TW_MOUSE) {
1347                                 code = TW_MOUSE;
1348                                 goto end;
1349                             }
1350                             continue;
1351                         default:
1352                             selectActiveHandle(TCB);
1353                             continue;
1354                         }
1355                     }
1356                 }
1357             }
1358             continue;
1359         } else {
1360             if (rc != WAIT_TIMEOUT) {
1361                 code = -1;
1362                 break;
1363             } else {
1364                 code = 0;
1365                 break;
1366             }
1367         }
1368     }
1369   end:
1370
1371     TR(TRACE_IEVENT, ("end twait: returned %d (%d), remaining time %d msec",
1372                       code, errno, milliseconds));
1373
1374     if (timeleft)
1375         *timeleft = milliseconds;
1376
1377     return code;
1378 }
1379
1380 static bool
1381 handle_mouse(TERMINAL_CONTROL_BLOCK * TCB, MOUSE_EVENT_RECORD mer)
1382 {
1383     SCREEN *sp;
1384     MEVENT work;
1385     bool result = FALSE;
1386
1387     AssertTCB();
1388     SetSP();
1389
1390     sp->_drv_mouse_old_buttons = sp->_drv_mouse_new_buttons;
1391     sp->_drv_mouse_new_buttons = mer.dwButtonState & BUTTON_MASK;
1392
1393     /*
1394      * We're only interested if the button is pressed or released.
1395      * FIXME: implement continuous event-tracking.
1396      */
1397     if (sp->_drv_mouse_new_buttons != sp->_drv_mouse_old_buttons) {
1398         Properties *p = PropOf(TCB);
1399
1400         memset(&work, 0, sizeof(work));
1401
1402         if (sp->_drv_mouse_new_buttons) {
1403
1404             work.bstate |= decode_mouse(TCB, sp->_drv_mouse_new_buttons);
1405
1406         } else {
1407
1408             /* cf: BUTTON_PRESSED, BUTTON_RELEASED */
1409             work.bstate |= (decode_mouse(TCB, sp->_drv_mouse_old_buttons) >> 1);
1410
1411             result = TRUE;
1412         }
1413
1414         work.x = mer.dwMousePosition.X;
1415         work.y = mer.dwMousePosition.Y - AdjustY(p);
1416
1417         sp->_drv_mouse_fifo[sp->_drv_mouse_tail] = work;
1418         sp->_drv_mouse_tail += 1;
1419     }
1420
1421     return result;
1422 }
1423
1424 static int
1425 drv_read(TERMINAL_CONTROL_BLOCK * TCB, int *buf)
1426 {
1427     SCREEN *sp;
1428     int n = 1;
1429     INPUT_RECORD inp_rec;
1430     BOOL b;
1431     DWORD nRead;
1432     WORD vk;
1433
1434     AssertTCB();
1435     assert(buf);
1436     SetSP();
1437
1438     memset(&inp_rec, 0, sizeof(inp_rec));
1439
1440     T((T_CALLED("win32con::drv_read(%p)"), TCB));
1441     while ((b = ReadConsoleInput(TCB->inp, &inp_rec, 1, &nRead))) {
1442         if (b && nRead > 0) {
1443             if (inp_rec.EventType == KEY_EVENT) {
1444                 if (!inp_rec.Event.KeyEvent.bKeyDown)
1445                     continue;
1446                 *buf = (int) inp_rec.Event.KeyEvent.uChar.AsciiChar;
1447                 vk = inp_rec.Event.KeyEvent.wVirtualKeyCode;
1448                 if (*buf == 0) {
1449                     if (sp->_keypad_on) {
1450                         *buf = MapKey(TCB, vk);
1451                         if (0 > (*buf))
1452                             continue;
1453                         else
1454                             break;
1455                     } else
1456                         continue;
1457                 } else {        /* *buf != 0 */
1458                     break;
1459                 }
1460             } else if (inp_rec.EventType == MOUSE_EVENT) {
1461                 if (handle_mouse(TCB, inp_rec.Event.MouseEvent)) {
1462                     *buf = KEY_MOUSE;
1463                     break;
1464                 }
1465             }
1466             continue;
1467         }
1468     }
1469     returnCode(n);
1470 }
1471
1472 static int
1473 drv_nap(TERMINAL_CONTROL_BLOCK * TCB GCC_UNUSED, int ms)
1474 {
1475     T((T_CALLED("win32con::drv_nap(%p, %d)"), TCB, ms));
1476     Sleep(ms);
1477     returnCode(OK);
1478 }
1479
1480 static bool
1481 drv_kyExist(TERMINAL_CONTROL_BLOCK * TCB, int keycode)
1482 {
1483     SCREEN *sp;
1484     WORD nKey;
1485     void *res;
1486     bool found = FALSE;
1487     LONG key = GenMap(0, (WORD) keycode);
1488
1489     AssertTCB();
1490     SetSP();
1491
1492     AssertTCB();
1493
1494     T((T_CALLED("win32con::drv_kyExist(%p, %d)"), TCB, keycode));
1495     res = bsearch(&key,
1496                   PropOf(TCB)->rmap,
1497                   (size_t) (N_INI + FKEYS),
1498                   sizeof(keylist[0]),
1499                   rkeycompare);
1500     if (res) {
1501         key = *((LONG *) res);
1502         nKey = LOWORD(key);
1503         if (!(nKey & 0x8000))
1504             found = TRUE;
1505     }
1506     returnCode(found);
1507 }
1508
1509 static int
1510 drv_kpad(TERMINAL_CONTROL_BLOCK * TCB, int flag GCC_UNUSED)
1511 {
1512     SCREEN *sp;
1513     int code = ERR;
1514
1515     AssertTCB();
1516     sp = TCB->csp;
1517
1518     T((T_CALLED("win32con::drv_kpad(%p, %d)"), TCB, flag));
1519     if (sp) {
1520         code = OK;
1521     }
1522     returnCode(code);
1523 }
1524
1525 static int
1526 drv_keyok(TERMINAL_CONTROL_BLOCK * TCB, int keycode, int flag)
1527 {
1528     int code = ERR;
1529     SCREEN *sp;
1530     WORD nKey;
1531     WORD vKey;
1532     void *res;
1533     LONG key = GenMap(0, (WORD) keycode);
1534
1535     AssertTCB();
1536     SetSP();
1537
1538     T((T_CALLED("win32con::drv_keyok(%p, %d, %d)"), TCB, keycode, flag));
1539     if (sp) {
1540         res = bsearch(&key,
1541                       PropOf(TCB)->rmap,
1542                       (size_t) (N_INI + FKEYS),
1543                       sizeof(keylist[0]),
1544                       rkeycompare);
1545         if (res) {
1546             key = *((LONG *) res);
1547             vKey = HIWORD(key);
1548             nKey = (LOWORD(key)) & 0x7fff;
1549             if (!flag)
1550                 nKey |= 0x8000;
1551             *(LONG *) res = GenMap(vKey, nKey);
1552         }
1553     }
1554     returnCode(code);
1555 }
1556
1557 NCURSES_EXPORT_VAR (TERM_DRIVER) _nc_WIN_DRIVER = {
1558     FALSE,
1559         drv_CanHandle,          /* CanHandle */
1560         drv_init,               /* init */
1561         drv_release,            /* release */
1562         drv_size,               /* size */
1563         drv_sgmode,             /* sgmode */
1564         drv_conattr,            /* conattr */
1565         drv_mvcur,              /* hwcur */
1566         drv_mode,               /* mode */
1567         drv_rescol,             /* rescol */
1568         drv_rescolors,          /* rescolors */
1569         drv_setcolor,           /* color */
1570         drv_dobeepflash,        /* DoBeepFlash */
1571         drv_initpair,           /* initpair */
1572         drv_initcolor,          /* initcolor */
1573         drv_do_color,           /* docolor */
1574         drv_initmouse,          /* initmouse */
1575         drv_testmouse,          /* testmouse */
1576         drv_setfilter,          /* setfilter */
1577         drv_hwlabel,            /* hwlabel */
1578         drv_hwlabelOnOff,       /* hwlabelOnOff */
1579         drv_doupdate,           /* update */
1580         drv_defaultcolors,      /* defaultcolors */
1581         drv_print,              /* print */
1582         drv_size,               /* getsize */
1583         drv_setsize,            /* setsize */
1584         drv_initacs,            /* initacs */
1585         drv_screen_init,        /* scinit */
1586         drv_wrap,               /* scexit */
1587         drv_twait,              /* twait */
1588         drv_read,               /* read */
1589         drv_nap,                /* nap */
1590         drv_kpad,               /* kpad */
1591         drv_keyok,              /* kyOk */
1592         drv_kyExist             /* kyExist */
1593 };