ncurses 5.7 - patch 20100206
[ncurses.git] / ncurses / win32con / win_driver.c
1 /****************************************************************************
2  * Copyright (c) 1998-2009,2010 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 /*
35  * TODO - GetMousePos(POINT * result) from ntconio.c
36  * TODO - implement nodelay
37  */
38
39 #include <curses.priv.h>
40
41 MODULE_ID("$Id: win_driver.c,v 1.6 2010/02/06 19:55:44 tom Exp $")
42
43 #define WINMAGIC NCDRV_MAGIC(NCDRV_WINCONSOLE)
44
45 #define AssertTCB() assert(TCB!=0 && TCB->magic==WINMAGIC)
46 #define SetSP() assert(TCB->csp!=0); sp = TCB->csp
47
48 #define GenMap(vKey,key) MAKELONG(key, vKey)
49
50 static const LONG keylist[] =
51 {
52     GenMap(VK_PRIOR, KEY_PPAGE),
53     GenMap(VK_NEXT, KEY_NPAGE),
54     GenMap(VK_END, KEY_END),
55     GenMap(VK_HOME, KEY_HOME),
56     GenMap(VK_LEFT, KEY_LEFT),
57     GenMap(VK_UP, KEY_UP),
58     GenMap(VK_RIGHT, KEY_RIGHT),
59     GenMap(VK_DOWN, KEY_DOWN),
60     GenMap(VK_DELETE, KEY_DC),
61     GenMap(VK_INSERT, KEY_IC)
62 };
63 #define N_INI ((int)(sizeof(keylist)/sizeof(keylist[0])))
64 #define FKEYS 24
65 #define MAPSIZE (FKEYS + N_INI)
66 #define NUMPAIRS 64
67
68 typedef struct props {
69     CONSOLE_SCREEN_BUFFER_INFO SBI;
70     bool progMode;
71     DWORD map[MAPSIZE];
72     DWORD rmap[MAPSIZE];
73     WORD pairs[NUMPAIRS];
74 } Properties;
75
76 #define PropOf(TCB) ((Properties*)TCB->prop)
77
78 int
79 _nc_mingw_ioctl(int fd GCC_UNUSED,
80                 long int request GCC_UNUSED,
81                 struct termios *arg GCC_UNUSED)
82 {
83     return 0;
84     endwin();
85     fprintf(stderr, "TERMINFO currently not supported on Windows.\n");
86     exit(1);
87 }
88
89 static WORD
90 MapColor(bool fore, int color)
91 {
92     static const int _cmap[] =
93     {0, 4, 2, 6, 1, 5, 3, 7};
94     int a;
95     if (color < 0 || color > 7)
96         a = fore ? 7 : 0;
97     else
98         a = _cmap[color];
99     if (!fore)
100         a = a << 4;
101     return (WORD) a;
102 }
103
104 static WORD
105 MapAttr(TERMINAL_CONTROL_BLOCK * TCB, WORD res, chtype ch)
106 {
107     if (ch & A_COLOR) {
108         int p;
109         SCREEN *sp;
110
111         AssertTCB();
112         SetSP();
113         p = PAIR_NUMBER(ch);
114         if (p > 0 && p < NUMPAIRS && TCB != 0 && sp != 0) {
115             WORD a;
116             a = PropOf(TCB)->pairs[p];
117             res = (res & 0xff00) | a;
118         }
119     }
120
121     if (ch & A_REVERSE)
122         res = ((res & 0xff00) | (((res & 0x07) << 4) | ((res & 0x70) >> 4)));
123
124     if (ch & A_STANDOUT)
125         res = ((res & 0xff00) | (((res & 0x07) << 4) | ((res & 0x70) >> 4))
126                | BACKGROUND_INTENSITY);
127
128     if (ch & A_BOLD)
129         res |= FOREGROUND_INTENSITY;
130
131     if (ch & A_DIM)
132         res |= BACKGROUND_INTENSITY;
133
134     return res;
135 }
136
137 static BOOL
138 con_write(TERMINAL_CONTROL_BLOCK * TCB, int y, int x, chtype *str, int n)
139 {
140     CHAR_INFO ci[n];
141     COORD loc, siz;
142     SMALL_RECT rec;
143     int i;
144     chtype ch;
145     SCREEN *sp;
146
147     AssertTCB();
148
149     if (TCB == 0 || InvalidConsoleHandle(TCB->hdl))
150         return FALSE;
151
152     SetSP();
153
154     for (i = 0; i < n; i++) {
155         ch = str[i];
156         ci[i].Char.AsciiChar = ChCharOf(ch);
157         ci[i].Attributes = MapAttr(TCB,
158                                    PropOf(TCB)->SBI.wAttributes,
159                                    ChAttrOf(ch));
160         if (ChAttrOf(ch) & A_ALTCHARSET) {
161             if (sp->_acs_map)
162                 ci[i].Char.AsciiChar =
163                     ChCharOf(NCURSES_SP_NAME(_nc_acs_char) (sp, ChCharOf(ch)));
164         }
165     }
166
167     loc.X = (short) 0;
168     loc.Y = (short) 0;
169     siz.X = (short) n;
170     siz.Y = 1;
171
172     rec.Left = (short) x;
173     rec.Top = (short) y;
174     rec.Right = (short) (x + n - 1);
175     rec.Bottom = rec.Top;
176
177     return WriteConsoleOutput(TCB->hdl, ci, siz, loc, &rec);
178 }
179
180 #define MARK_NOCHANGE(win,row) \
181                 win->_line[row].firstchar = _NOCHANGE; \
182                 win->_line[row].lastchar  = _NOCHANGE
183
184 static int
185 drv_doupdate(TERMINAL_CONTROL_BLOCK * TCB)
186 {
187     int y, nonempty, n, x0, x1, Width, Height;
188     SCREEN *sp;
189
190     AssertTCB();
191     SetSP();
192
193     Width = screen_columns(sp);
194     Height = screen_lines(sp);
195     nonempty = min(Height, NewScreen(sp)->_maxy + 1);
196
197     if ((CurScreen(sp)->_clear || NewScreen(sp)->_clear)) {
198         int x;
199         chtype empty[Width];
200
201         for (x = 0; x < Width; x++)
202             empty[x] = ' ';
203
204         for (y = 0; y < nonempty; y++) {
205             con_write(TCB, y, 0, empty, Width);
206             memcpy(empty,
207                    CurScreen(sp)->_line[y].text,
208                    Width * sizeof(chtype));
209         }
210         CurScreen(sp)->_clear = FALSE;
211         NewScreen(sp)->_clear = FALSE;
212         touchwin(NewScreen(sp));
213     }
214
215     for (y = 0; y < nonempty; y++) {
216         x0 = NewScreen(sp)->_line[y].firstchar;
217         if (x0 != _NOCHANGE) {
218             x1 = NewScreen(sp)->_line[y].lastchar;
219             n = x1 - x0 + 1;
220             if (n > 0) {
221                 memcpy(CurScreen(sp)->_line[y].text + x0,
222                        NewScreen(sp)->_line[y].text + x0,
223                        n * sizeof(chtype));
224                 con_write(TCB,
225                           y,
226                           x0,
227                           ((chtype *) CurScreen(sp)->_line[y].text) + x0, n);
228
229                 /* mark line changed successfully */
230                 if (y <= NewScreen(sp)->_maxy) {
231                     MARK_NOCHANGE(NewScreen(sp), y);
232                 }
233                 if (y <= CurScreen(sp)->_maxy) {
234                     MARK_NOCHANGE(CurScreen(sp), y);
235                 }
236             }
237         }
238     }
239
240     /* put everything back in sync */
241     for (y = nonempty; y <= NewScreen(sp)->_maxy; y++) {
242         MARK_NOCHANGE(NewScreen(sp), y);
243     }
244     for (y = nonempty; y <= CurScreen(sp)->_maxy; y++) {
245         MARK_NOCHANGE(CurScreen(sp), y);
246     }
247
248     if (!NewScreen(sp)->_leaveok) {
249         CurScreen(sp)->_curx = NewScreen(sp)->_curx;
250         CurScreen(sp)->_cury = NewScreen(sp)->_cury;
251
252         TCB->drv->hwcur(TCB, 0, 0, CurScreen(sp)->_cury, CurScreen(sp)->_curx);
253     }
254     SetConsoleActiveScreenBuffer(TCB->hdl);
255     return OK;
256 }
257
258 static bool
259 drv_CanHandle(TERMINAL_CONTROL_BLOCK * TCB,
260               const char *tname,
261               int *errret GCC_UNUSED)
262 {
263     bool code = FALSE;
264
265     T((T_CALLED("drv_CanHandle(%p)"), TCB));
266
267     assert(TCB != 0);
268     assert(tname != 0);
269
270     TCB->magic = WINMAGIC;
271     if (*tname == 0 || *tname == 0 || strcmp(tname, "unknown") == 0) {
272         code = TRUE;
273         if ((TCB->term.type.Booleans) == 0) {
274             _nc_init_entry(&(TCB->term.type));
275         }
276     }
277
278     returnBool(code);
279 }
280
281 static int
282 drv_dobeepflash(TERMINAL_CONTROL_BLOCK * TCB,
283                 bool beepFlag GCC_UNUSED)
284 {
285     SCREEN *sp;
286     int res = ERR;
287
288     AssertTCB();
289     SetSP();
290
291     return res;
292 }
293
294 static int
295 drv_print(TERMINAL_CONTROL_BLOCK * TCB,
296           char *data GCC_UNUSED,
297           int len GCC_UNUSED)
298 {
299     SCREEN *sp;
300
301     AssertTCB();
302     SetSP();
303
304     return ERR;
305 }
306
307 static int
308 drv_defaultcolors(TERMINAL_CONTROL_BLOCK * TCB,
309                   int fg GCC_UNUSED,
310                   int bg GCC_UNUSED)
311 {
312     SCREEN *sp;
313     int code = ERR;
314
315     AssertTCB();
316     SetSP();
317
318     return (code);
319 }
320
321 static void
322 drv_setcolor(TERMINAL_CONTROL_BLOCK * TCB,
323              bool fore,
324              int color,
325              int (*outc) (SCREEN *, int) GCC_UNUSED)
326 {
327     AssertTCB();
328
329     if (TCB && !InvalidConsoleHandle(TCB->hdl)) {
330         WORD a = MapColor(fore, color);
331         a = ((PropOf(TCB)->SBI.wAttributes) & (fore ? 0xfff8 : 0xff8f)) | a;
332         SetConsoleTextAttribute(TCB->hdl, a);
333         GetConsoleScreenBufferInfo(TCB->hdl, &(PropOf(TCB)->SBI));
334     }
335 }
336
337 static bool
338 drv_rescol(TERMINAL_CONTROL_BLOCK * TCB)
339 {
340     bool res = FALSE;
341
342     AssertTCB();
343     if (TCB && !InvalidConsoleHandle(TCB->hdl)) {
344         WORD a = FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN;
345         SetConsoleTextAttribute(TCB->hdl, a);
346         GetConsoleScreenBufferInfo(TCB->hdl, &(PropOf(TCB)->SBI));
347         res = TRUE;
348     }
349     return res;
350 }
351
352 static bool
353 drv_rescolors(TERMINAL_CONTROL_BLOCK * TCB)
354 {
355     int result = FALSE;
356     SCREEN *sp;
357
358     AssertTCB();
359     SetSP();
360
361     return result;
362 }
363
364 static int
365 drv_size(TERMINAL_CONTROL_BLOCK * TCB, int *Lines, int *Cols)
366 {
367     AssertTCB();
368
369     if (TCB == NULL || Lines == NULL || Cols == NULL || InvalidConsoleHandle(TCB->hdl))
370         return ERR;
371
372     *Lines = (int) (PropOf(TCB)->SBI.dwSize.Y);
373     *Cols = (int) (PropOf(TCB)->SBI.dwSize.X);
374     return OK;
375 }
376
377 static int
378 drv_setsize(TERMINAL_CONTROL_BLOCK * TCB GCC_UNUSED,
379             int l GCC_UNUSED,
380             int c GCC_UNUSED)
381 {
382     AssertTCB();
383     return ERR;
384 }
385
386 static int
387 drv_sgmode(TERMINAL_CONTROL_BLOCK * TCB, bool setFlag, TTY * buf)
388 {
389     DWORD dwFlag = 0;
390     tcflag_t iflag;
391     tcflag_t lflag;
392
393     AssertTCB();
394
395     if (TCB == 0 || buf == NULL)
396         return ERR;
397
398     if (setFlag) {
399         iflag = buf->c_iflag;
400         lflag = buf->c_lflag;
401
402         GetConsoleMode(TCB->inp, &dwFlag);
403
404         if (lflag & ICANON)
405             dwFlag |= ENABLE_LINE_INPUT;
406         else
407             dwFlag &= ~ENABLE_LINE_INPUT;
408
409         if (lflag & ECHO)
410             dwFlag |= ENABLE_ECHO_INPUT;
411         else
412             dwFlag &= ~ENABLE_ECHO_INPUT;
413
414         if (iflag & BRKINT)
415             dwFlag |= ENABLE_PROCESSED_INPUT;
416         else
417             dwFlag &= ~ENABLE_PROCESSED_INPUT;
418
419         dwFlag |= ENABLE_MOUSE_INPUT;
420
421         buf->c_iflag = iflag;
422         buf->c_lflag = lflag;
423         SetConsoleMode(TCB->inp, dwFlag);
424         TCB->term.Nttyb = *buf;
425     } else {
426         iflag = TCB->term.Nttyb.c_iflag;
427         lflag = TCB->term.Nttyb.c_lflag;
428         GetConsoleMode(TCB->inp, &dwFlag);
429
430         if (dwFlag & ENABLE_LINE_INPUT)
431             lflag |= ICANON;
432         else
433             lflag &= ~ICANON;
434
435         if (dwFlag & ENABLE_ECHO_INPUT)
436             lflag |= ECHO;
437         else
438             lflag &= ~ECHO;
439
440         if (dwFlag & ENABLE_PROCESSED_INPUT)
441             iflag |= BRKINT;
442         else
443             iflag &= ~BRKINT;
444
445         TCB->term.Nttyb.c_iflag = iflag;
446         TCB->term.Nttyb.c_lflag = lflag;
447
448         *buf = TCB->term.Nttyb;
449     }
450     return OK;
451 }
452
453 static int
454 drv_mode(TERMINAL_CONTROL_BLOCK * TCB, bool progFlag, bool defFlag)
455 {
456     SCREEN *sp;
457     TERMINAL *_term = (TERMINAL *) TCB;
458     int code = ERR;
459
460     AssertTCB();
461     sp = TCB->csp;
462
463     PropOf(TCB)->progMode = progFlag;
464     SetConsoleActiveScreenBuffer(progFlag ? TCB->hdl : TCB->out);
465
466     if (progFlag) /* prog mode */  {
467         if (defFlag) {
468             if ((drv_sgmode(TCB, FALSE, &(_term->Nttyb)) == OK)) {
469                 _term->Nttyb.c_oflag &= ~OFLAGS_TABS;
470                 code = OK;
471             }
472         } else {
473             /* reset_prog_mode */
474             if (drv_sgmode(TCB, TRUE, &(_term->Nttyb)) == OK) {
475                 if (sp) {
476                     if (sp->_keypad_on)
477                         _nc_keypad(sp, TRUE);
478                     NC_BUFFERED(sp, TRUE);
479                 }
480                 code = OK;
481             }
482         }
483     } else {                    /* shell mode */
484         if (defFlag) {
485             /* def_shell_mode */
486             if (drv_sgmode(TCB, FALSE, &(_term->Ottyb)) == OK) {
487                 code = OK;
488             }
489         } else {
490             /* reset_shell_mode */
491             if (sp) {
492                 _nc_keypad(sp, FALSE);
493                 NCURSES_SP_NAME(_nc_flush) (sp);
494                 NC_BUFFERED(sp, FALSE);
495             }
496             code = drv_sgmode(TCB, TRUE, &(_term->Ottyb));
497         }
498     }
499
500     return (code);
501 }
502
503 static void
504 drv_screen_init(SCREEN *sp GCC_UNUSED)
505 {
506 }
507
508 static void
509 drv_wrap(SCREEN *sp GCC_UNUSED)
510 {
511 }
512
513 static int
514 rkeycompare(const void *el1, const void *el2)
515 {
516     WORD key1 = (LOWORD((*((const LONG *) el1)))) & 0x7fff;
517     WORD key2 = (LOWORD((*((const LONG *) el2)))) & 0x7fff;
518
519     return ((key1 < key2) ? -1 : ((key1 == key2) ? 0 : 1));
520 }
521
522 static int
523 keycompare(const void *el1, const void *el2)
524 {
525     WORD key1 = HIWORD((*((const LONG *) el1)));
526     WORD key2 = HIWORD((*((const LONG *) el2)));
527
528     return ((key1 < key2) ? -1 : ((key1 == key2) ? 0 : 1));
529 }
530
531 static int
532 MapKey(TERMINAL_CONTROL_BLOCK * TCB, WORD vKey)
533 {
534     WORD nKey = 0;
535     void *res;
536     LONG key = GenMap(vKey, 0);
537     int code = -1;
538
539     AssertTCB();
540
541     res = bsearch(&key,
542                   PropOf(TCB)->map,
543                   (size_t) (N_INI + FKEYS),
544                   sizeof(keylist[0]),
545                   keycompare);
546     if (res) {
547         key = *((LONG *) res);
548         nKey = LOWORD(key);
549         code = (int) (nKey & 0x7fff);
550         if (nKey & 0x8000)
551             code = -code;
552     }
553     return code;
554 }
555
556 static void
557 drv_release(TERMINAL_CONTROL_BLOCK * TCB)
558 {
559     T((T_CALLED("drv_release(%p)"), TCB));
560
561     AssertTCB();
562     if (TCB->prop)
563         free(TCB->prop);
564
565     returnVoid;
566 }
567
568 static void
569 drv_init(TERMINAL_CONTROL_BLOCK * TCB)
570 {
571     T((T_CALLED("drv_init(%p)"), TCB));
572
573     AssertTCB();
574
575     if (TCB) {
576         BOOL b = AllocConsole();
577         WORD a;
578         int i;
579
580         if (!b)
581             b = AttachConsole(ATTACH_PARENT_PROCESS);
582
583         TCB->inp = GetStdHandle(STD_INPUT_HANDLE);
584         TCB->out = GetStdHandle(STD_OUTPUT_HANDLE);
585
586         if (getenv("NCGDB"))
587             TCB->hdl = TCB->out;
588         else
589             TCB->hdl = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE,
590                                                  0,
591                                                  NULL,
592                                                  CONSOLE_TEXTMODE_BUFFER,
593                                                  NULL);
594
595         if (!InvalidConsoleHandle(TCB->hdl)) {
596             TCB->prop = typeCalloc(Properties, 1);
597             GetConsoleScreenBufferInfo(TCB->hdl, &(PropOf(TCB)->SBI));
598         }
599
600         TCB->info.initcolor = TRUE;
601         TCB->info.canchange = FALSE;
602         TCB->info.hascolor = TRUE;
603         TCB->info.caninit = TRUE;
604
605         TCB->info.maxpairs = NUMPAIRS;
606         TCB->info.maxcolors = 8;
607         TCB->info.numlabels = 0;
608         TCB->info.labelwidth = 0;
609         TCB->info.labelheight = 0;
610         TCB->info.nocolorvideo = 1;
611         TCB->info.tabsize = 8;
612
613         TCB->info.defaultPalette = _nc_cga_palette;
614
615         for (i = 0; i < (N_INI + FKEYS); i++) {
616             if (i < N_INI)
617                 PropOf(TCB)->rmap[i] = PropOf(TCB)->map[i] = keylist[i];
618             else
619                 PropOf(TCB)->rmap[i] = PropOf(TCB)->map[i] =
620                     GenMap((VK_F1 + (i - N_INI)), (KEY_F(1) + (i - N_INI)));
621         }
622         qsort(PropOf(TCB)->map,
623               (size_t) (MAPSIZE),
624               sizeof(keylist[0]),
625               keycompare);
626         qsort(PropOf(TCB)->rmap,
627               (size_t) (MAPSIZE),
628               sizeof(keylist[0]),
629               rkeycompare);
630
631         a = MapColor(true, COLOR_WHITE) | MapColor(false, COLOR_BLACK);
632         for (i = 0; i < NUMPAIRS; i++)
633             PropOf(TCB)->pairs[i] = a;
634     }
635     returnVoid;
636 }
637
638 static void
639 drv_initpair(TERMINAL_CONTROL_BLOCK * TCB,
640              short pair,
641              short f,
642              short b)
643 {
644     SCREEN *sp;
645
646     AssertTCB();
647     SetSP();
648
649     if ((pair > 0) && (pair < NUMPAIRS) && (f >= 0) && (f < 8)
650         && (b >= 0) && (b < 8)) {
651         PropOf(TCB)->pairs[pair] = MapColor(true, f) | MapColor(false, b);
652     }
653 }
654
655 static void
656 drv_initcolor(TERMINAL_CONTROL_BLOCK * TCB,
657               short color GCC_UNUSED,
658               short r GCC_UNUSED,
659               short g GCC_UNUSED,
660               short b GCC_UNUSED)
661 {
662     SCREEN *sp;
663
664     AssertTCB();
665     SetSP();
666 }
667
668 static void
669 drv_do_color(TERMINAL_CONTROL_BLOCK * TCB,
670              short old_pair GCC_UNUSED,
671              short pair GCC_UNUSED,
672              bool reverse GCC_UNUSED,
673              int (*outc) (SCREEN *, int) GCC_UNUSED
674 )
675 {
676     SCREEN *sp;
677
678     AssertTCB();
679     SetSP();
680 }
681
682 static void
683 drv_initmouse(TERMINAL_CONTROL_BLOCK * TCB)
684 {
685     SCREEN *sp;
686
687     AssertTCB();
688     SetSP();
689
690     sp->_mouse_type = M_TERM_DRIVER;
691 }
692
693 static int
694 drv_mvcur(TERMINAL_CONTROL_BLOCK * TCB,
695           int yold GCC_UNUSED, int xold GCC_UNUSED,
696           int y, int x)
697 {
698     int ret = ERR;
699     if (TCB && !InvalidConsoleHandle(TCB->hdl)) {
700         COORD loc;
701         loc.X = (short) x;
702         loc.Y = (short) y;
703         SetConsoleCursorPosition(TCB->hdl, loc);
704         ret = OK;
705     }
706     return ret;
707 }
708
709 static void
710 drv_hwlabel(TERMINAL_CONTROL_BLOCK * TCB,
711             int labnum GCC_UNUSED,
712             char *text GCC_UNUSED)
713 {
714     SCREEN *sp;
715
716     AssertTCB();
717     SetSP();
718 }
719
720 static void
721 drv_hwlabelOnOff(TERMINAL_CONTROL_BLOCK * TCB,
722                  bool OnFlag GCC_UNUSED)
723 {
724     SCREEN *sp;
725
726     AssertTCB();
727     SetSP();
728 }
729
730 static chtype
731 drv_conattr(TERMINAL_CONTROL_BLOCK * TCB GCC_UNUSED)
732 {
733     chtype res = A_NORMAL;
734     res |= (A_BOLD | A_DIM | A_REVERSE | A_STANDOUT | A_COLOR);
735     return res;
736 }
737
738 static void
739 drv_setfilter(TERMINAL_CONTROL_BLOCK * TCB)
740 {
741     SCREEN *sp;
742
743     AssertTCB();
744     SetSP();
745 }
746
747 static void
748 drv_initacs(TERMINAL_CONTROL_BLOCK * TCB,
749             chtype *real_map GCC_UNUSED,
750             chtype *fake_map GCC_UNUSED)
751 {
752 #define DATA(a,b) { a, b }
753     static struct {
754         int acs_code;
755         int use_code;
756     } table[] = {
757         DATA('a', 0xb1),        /* ACS_CKBOARD  */
758             DATA('f', 0xf8),    /* ACS_DEGREE   */
759             DATA('g', 0xf1),    /* ACS_PLMINUS  */
760             DATA('j', 0xd9),    /* ACS_LRCORNER */
761             DATA('l', 0xda),    /* ACS_ULCORNER */
762             DATA('k', 0xbf),    /* ACS_URCORNER */
763             DATA('m', 0xc0),    /* ACS_LLCORNER */
764             DATA('n', 0xc5),    /* ACS_PLUS     */
765             DATA('q', 0xc4),    /* ACS_HLINE    */
766             DATA('t', 0xc3),    /* ACS_LTEE     */
767             DATA('u', 0xb4),    /* ACS_RTEE     */
768             DATA('v', 0xc1),    /* ACS_BTEE     */
769             DATA('w', 0xc2),    /* ACS_TTEE     */
770             DATA('x', 0xb3),    /* ACS_VLINE    */
771             DATA('y', 0xf3),    /* ACS_LEQUAL   */
772             DATA('z', 0xf2),    /* ACS_GEQUAL   */
773             DATA('0', 0xdb),    /* ACS_BLOCK    */
774             DATA('{', 0xe3),    /* ACS_PI       */
775             DATA('}', 0x9c),    /* ACS_STERLING */
776             DATA(',', 0xae),    /* ACS_LARROW   */
777             DATA('+', 0xaf),    /* ACS_RARROW   */
778             DATA('~', 0xf9),    /* ACS_BULLET   */
779     };
780 #undef DATA
781     unsigned n;
782
783     SCREEN *sp;
784     AssertTCB();
785     SetSP();
786
787     for (n = 0; n < SIZEOF(table); ++n) {
788         real_map[table[n].acs_code] = table[n].use_code | A_ALTCHARSET;
789         if (sp != 0)
790             sp->_screen_acs_map[table[n].acs_code] = TRUE;
791     }
792 }
793
794 static ULONGLONG
795 tdiff(FILETIME fstart, FILETIME fend)
796 {
797     ULARGE_INTEGER ustart;
798     ULARGE_INTEGER uend;
799     ULONGLONG diff;
800
801     ustart.LowPart = fstart.dwLowDateTime;
802     ustart.HighPart = fstart.dwHighDateTime;
803     uend.LowPart = fend.dwLowDateTime;
804     uend.HighPart = fend.dwHighDateTime;
805
806     diff = (uend.QuadPart - ustart.QuadPart) / 10000;
807     return diff;
808 }
809
810 static int
811 Adjust(int milliseconds, int diff)
812 {
813     if (milliseconds == INFINITY)
814         return milliseconds;
815     milliseconds -= diff;
816     if (milliseconds < 0)
817         milliseconds = 0;
818     return milliseconds;
819 }
820
821 static int
822 drv_twait(TERMINAL_CONTROL_BLOCK * TCB,
823           int mode,
824           int milliseconds,
825           int *timeleft
826           EVENTLIST_2nd(_nc_eventlist * evl))
827 {
828     SCREEN *sp;
829     INPUT_RECORD inp;
830     BOOL b;
831     DWORD nRead = 0, rc = -1;
832     int code = 0;
833     FILETIME fstart;
834     FILETIME fend;
835     int diff;
836     bool isImmed = (milliseconds == 0);
837
838 #define CONSUME() ReadConsoleInput(TCB->inp,&inp,1,&nRead)
839
840     AssertTCB();
841     SetSP();
842
843     if (milliseconds < 0)
844         milliseconds = INFINITY;
845
846     memset(&inp, 0, sizeof(inp));
847
848     while (true) {
849         GetSystemTimeAsFileTime(&fstart);
850         rc = WaitForSingleObject(TCB->inp, milliseconds);
851         GetSystemTimeAsFileTime(&fend);
852         diff = (int) tdiff(fstart, fend);
853         milliseconds = Adjust(milliseconds, diff);
854
855         if (!isImmed && milliseconds == 0)
856             break;
857
858         if (rc == WAIT_OBJECT_0) {
859             if (mode) {
860                 b = GetNumberOfConsoleInputEvents(TCB->inp, &nRead);
861                 if (b && nRead > 0) {
862                     b = PeekConsoleInput(TCB->inp, &inp, 1, &nRead);
863                     if (b && nRead > 0) {
864                         switch (inp.EventType) {
865                         case KEY_EVENT:
866                             if (mode & TW_INPUT) {
867                                 WORD vk = inp.Event.KeyEvent.wVirtualKeyCode;
868                                 char ch = inp.Event.KeyEvent.uChar.AsciiChar;
869
870                                 if (inp.Event.KeyEvent.bKeyDown) {
871                                     if (0 == ch) {
872                                         int nKey = MapKey(TCB, vk);
873                                         if ((nKey < 0) || FALSE == sp->_keypad_on) {
874                                             CONSUME();
875                                             continue;
876                                         }
877                                     }
878                                     code = TW_INPUT;
879                                     goto end;
880                                 } else {
881                                     CONSUME();
882                                 }
883                             }
884                             continue;
885                         case MOUSE_EVENT:
886                             if (0 && mode & TW_MOUSE) {
887                                 code = TW_MOUSE;
888                                 goto end;
889                             } else
890                                 continue;
891                         default:
892                             SetConsoleActiveScreenBuffer(!PropOf(TCB)->progMode ?
893                                                          TCB->hdl : TCB->out);
894                             continue;
895                         }
896                     }
897                 }
898             }
899             continue;
900         } else {
901             if (rc != WAIT_TIMEOUT) {
902                 code = -1;
903                 break;
904             } else {
905                 code = 0;
906                 break;
907             }
908         }
909     }
910   end:
911     if (timeleft)
912         *timeleft = milliseconds;
913
914     return code;
915 }
916
917 #define BUTTON_MASK (FROM_LEFT_1ST_BUTTON_PRESSED | \
918                      FROM_LEFT_2ND_BUTTON_PRESSED | \
919                      FROM_LEFT_3RD_BUTTON_PRESSED)
920
921 static bool
922 handle_mouse(SCREEN *sp, MOUSE_EVENT_RECORD mer)
923 {
924     MEVENT work;
925     bool result = FALSE;
926
927     sp->_drv_mouse_old_buttons = sp->_drv_mouse_new_buttons;
928     sp->_drv_mouse_new_buttons = mer.dwButtonState & BUTTON_MASK;
929
930     /*
931      * We're only interested if the button is pressed or released.
932      * FIXME: implement continuous event-tracking.
933      */
934     if (sp->_drv_mouse_new_buttons != sp->_drv_mouse_old_buttons) {
935
936         memset(&work, 0, sizeof(work));
937
938         if (sp->_drv_mouse_new_buttons) {
939
940             if (sp->_drv_mouse_new_buttons & FROM_LEFT_1ST_BUTTON_PRESSED)
941                 work.bstate |= BUTTON1_PRESSED;
942             if (sp->_drv_mouse_new_buttons & FROM_LEFT_2ND_BUTTON_PRESSED)
943                 work.bstate |= BUTTON2_PRESSED;
944             if (sp->_drv_mouse_new_buttons & FROM_LEFT_3RD_BUTTON_PRESSED)
945                 work.bstate |= BUTTON3_PRESSED;
946             if (sp->_drv_mouse_new_buttons & FROM_LEFT_4TH_BUTTON_PRESSED)
947                 work.bstate |= BUTTON4_PRESSED;
948
949         } else {
950
951             if (sp->_drv_mouse_old_buttons & FROM_LEFT_1ST_BUTTON_PRESSED)
952                 work.bstate |= BUTTON1_RELEASED;
953             if (sp->_drv_mouse_old_buttons & FROM_LEFT_2ND_BUTTON_PRESSED)
954                 work.bstate |= BUTTON2_RELEASED;
955             if (sp->_drv_mouse_old_buttons & FROM_LEFT_3RD_BUTTON_PRESSED)
956                 work.bstate |= BUTTON3_RELEASED;
957             if (sp->_drv_mouse_old_buttons & FROM_LEFT_4TH_BUTTON_PRESSED)
958                 work.bstate |= BUTTON4_RELEASED;
959
960             result = TRUE;
961         }
962
963         work.x = mer.dwMousePosition.X;
964         work.y = mer.dwMousePosition.Y;
965
966         sp->_drv_mouse_fifo[sp->_drv_mouse_tail] = work;
967         sp->_drv_mouse_tail += 1;
968     }
969
970     return result;
971 }
972
973 static int
974 drv_read(TERMINAL_CONTROL_BLOCK * TCB, int *buf)
975 {
976     SCREEN *sp;
977     int n = 1;
978     INPUT_RECORD inp;
979     BOOL b;
980     DWORD nRead;
981     WORD vk;
982     WORD sc;
983
984     AssertTCB();
985     assert(buf);
986     SetSP();
987
988     memset(&inp, 0, sizeof(inp));
989
990     T((T_CALLED("drv_read(%p)"), TCB));
991     while ((b = ReadConsoleInput(TCB->inp, &inp, 1, &nRead))) {
992         if (b && nRead > 0) {
993             if (inp.EventType == KEY_EVENT) {
994                 if (!inp.Event.KeyEvent.bKeyDown)
995                     continue;
996                 *buf = (int) inp.Event.KeyEvent.uChar.AsciiChar;
997                 vk = inp.Event.KeyEvent.wVirtualKeyCode;
998                 sc = inp.Event.KeyEvent.wVirtualScanCode;
999                 if (*buf == 0) {
1000                     if (sp->_keypad_on) {
1001                         *buf = MapKey(TCB, vk);
1002                         if (0 > (*buf))
1003                             continue;
1004                         else
1005                             break;
1006                     } else
1007                         continue;
1008                 } else {        /* *buf != 0 */
1009                     break;
1010                 }
1011             } else if (inp.EventType == MOUSE_EVENT) {
1012                 if (handle_mouse(sp, inp.Event.MouseEvent)) {
1013                     *buf = KEY_MOUSE;
1014                     break;
1015                 }
1016             }
1017             continue;
1018         }
1019     }
1020     returnCode(n);
1021 }
1022
1023 static int
1024 drv_nap(TERMINAL_CONTROL_BLOCK * TCB GCC_UNUSED, int ms)
1025 {
1026     Sleep(ms);
1027     return OK;
1028 }
1029
1030 static bool
1031 drv_kyExist(TERMINAL_CONTROL_BLOCK * TCB, int keycode)
1032 {
1033     SCREEN *sp;
1034     WORD nKey;
1035     void *res;
1036     bool found = FALSE;
1037     LONG key = GenMap(0, (WORD) keycode);
1038
1039     AssertTCB();
1040     SetSP();
1041
1042     AssertTCB();
1043
1044     res = bsearch(&key,
1045                   PropOf(TCB)->rmap,
1046                   (size_t) (N_INI + FKEYS),
1047                   sizeof(keylist[0]),
1048                   rkeycompare);
1049     if (res) {
1050         key = *((LONG *) res);
1051         nKey = LOWORD(key);
1052         if (!(nKey & 0x8000))
1053             found = TRUE;
1054     }
1055     return found;
1056 }
1057
1058 static int
1059 drv_kpad(TERMINAL_CONTROL_BLOCK * TCB, bool flag GCC_UNUSED)
1060 {
1061     SCREEN *sp;
1062     int code = ERR;
1063
1064     AssertTCB();
1065     sp = TCB->csp;
1066
1067     if (sp) {
1068         code = OK;
1069     }
1070     return code;
1071 }
1072
1073 static int
1074 drv_keyok(TERMINAL_CONTROL_BLOCK * TCB, int keycode, bool flag)
1075 {
1076     int code = ERR;
1077     SCREEN *sp;
1078     WORD nKey;
1079     WORD vKey;
1080     void *res;
1081     LONG key = GenMap(0, (WORD) keycode);
1082
1083     AssertTCB();
1084     SetSP();
1085
1086     if (sp) {
1087         res = bsearch(&key,
1088                       PropOf(TCB)->rmap,
1089                       (size_t) (N_INI + FKEYS),
1090                       sizeof(keylist[0]),
1091                       rkeycompare);
1092         if (res) {
1093             key = *((LONG *) res);
1094             vKey = HIWORD(key);
1095             nKey = (LOWORD(key)) & 0x7fff;
1096             if (!flag)
1097                 nKey |= 0x8000;
1098             *(LONG *) res = GenMap(vKey, nKey);
1099         }
1100     }
1101     return code;
1102 }
1103
1104 NCURSES_EXPORT_VAR (TERM_DRIVER) _nc_WIN_DRIVER = {
1105     FALSE,
1106         drv_CanHandle,          /* CanHandle */
1107         drv_init,               /* init */
1108         drv_release,            /* release */
1109         drv_size,               /* size */
1110         drv_sgmode,             /* sgmode */
1111         drv_conattr,            /* conattr */
1112         drv_mvcur,              /* hwcur */
1113         drv_mode,               /* mode */
1114         drv_rescol,             /* rescol */
1115         drv_rescolors,          /* rescolors */
1116         drv_setcolor,           /* color */
1117         drv_dobeepflash,        /* DoBeepFlash */
1118         drv_initpair,           /* initpair */
1119         drv_initcolor,          /* initcolor */
1120         drv_do_color,           /* docolor */
1121         drv_initmouse,          /* initmouse */
1122         drv_setfilter,          /* setfilter */
1123         drv_hwlabel,            /* hwlabel */
1124         drv_hwlabelOnOff,       /* hwlabelOnOff */
1125         drv_doupdate,           /* update */
1126         drv_defaultcolors,      /* defaultcolors */
1127         drv_print,              /* print */
1128         drv_size,               /* getsize */
1129         drv_setsize,            /* setsize */
1130         drv_initacs,            /* initacs */
1131         drv_screen_init,        /* scinit */
1132         drv_wrap,               /* scexit */
1133         drv_twait,              /* twait */
1134         drv_read,               /* read */
1135         drv_nap,                /* nap */
1136         drv_kpad,               /* kpad */
1137         drv_keyok,              /* kyOk */
1138         drv_kyExist             /* kyExist */
1139 };