]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/base/lib_mouse.c
ncurses 6.3 - patch 20220430
[ncurses.git] / ncurses / base / lib_mouse.c
1 /****************************************************************************
2  * Copyright 2018-2021,2022 Thomas E. Dickey                                *
3  * Copyright 1998-2016,2017 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: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
32  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
33  *     and: Thomas E. Dickey                        1996-on                 *
34  *     and: Juergen Pfeifer                         2008                    *
35  ****************************************************************************/
36
37 /*
38  * This module is intended to encapsulate ncurses's interface to pointing
39  * devices.
40  *
41  * The primary method used is xterm's internal mouse-tracking facility.
42  * Additional methods depend on the platform:
43  *      Alessandro Rubini's GPM server (Linux)
44  *      sysmouse (FreeBSD)
45  *      special-purpose mouse interface for OS/2 EMX.
46  *
47  * Notes for implementors of new mouse-interface methods:
48  *
49  * The code is logically split into a lower level that accepts event reports
50  * in a device-dependent format and an upper level that parses mouse gestures
51  * and filters events.  The mediating data structure is a circular queue of
52  * MEVENT structures.
53  *
54  * Functionally, the lower level's job is to pick up primitive events and
55  * put them on the circular queue.  This can happen in one of two ways:
56  * either (a) _nc_mouse_event() detects a series of incoming mouse reports
57  * and queues them, or (b) code in lib_getch.c detects the kmous prefix in
58  * the keyboard input stream and calls _nc_mouse_inline to queue up a series
59  * of adjacent mouse reports.
60  *
61  * In either case, _nc_mouse_parse() should be called after the series is
62  * accepted to parse the digested mouse reports (low-level MEVENTs) into
63  * a gesture (a high-level or composite MEVENT).
64  *
65  * Don't be too shy about adding new event types or modifiers, if you can find
66  * room for them in the 32-bit mask.  The API is written so that users get
67  * feedback on which theoretical event types they won't see when they call
68  * mousemask. There's one bit per button (the RESERVED_EVENT bit) not being
69  * used yet, and a couple of bits open at the high end.
70  */
71
72 #ifdef __EMX__
73 #  include <io.h>
74 #  define  INCL_DOS
75 #  define  INCL_VIO
76 #  define  INCL_KBD
77 #  define  INCL_MOU
78 #  define  INCL_DOSPROCESS
79 #  include <os2.h>              /* Need to include before the others */
80 #endif
81
82 #include <curses.priv.h>
83
84 #ifndef CUR
85 #define CUR SP_TERMTYPE
86 #endif
87
88 MODULE_ID("$Id: lib_mouse.c,v 1.196 2022/04/30 23:21:34 tom Exp $")
89
90 #include <tic.h>
91
92 #if USE_GPM_SUPPORT
93 #include <linux/keyboard.h>     /* defines KG_* macros */
94
95 #ifdef HAVE_LIBDL
96 /* use dynamic loader to avoid linkage dependency */
97 #include <dlfcn.h>
98
99 #ifdef RTLD_NOW
100 #define my_RTLD RTLD_NOW
101 #else
102 #ifdef RTLD_LAZY
103 #define my_RTLD RTLD_LAZY
104 #else
105 make an error
106 #endif
107 #endif                          /* RTLD_NOW */
108 #endif                          /* HAVE_LIBDL */
109
110 #endif                          /* USE_GPM_SUPPORT */
111
112 #if USE_SYSMOUSE
113 #undef buttons                  /* symbol conflict in consio.h */
114 #undef mouse_info               /* symbol conflict in consio.h */
115 #include <osreldate.h>
116 #if defined(__DragonFly_version) || (defined(__FreeBSD__) && (__FreeBSD_version >= 400017))
117 #include <sys/consio.h>
118 #include <sys/fbio.h>
119 #else
120 #include <machine/console.h>
121 #endif
122 #endif                          /* use_SYSMOUSE */
123
124 #if USE_KLIBC_MOUSE
125 #include <sys/socket.h>
126 #define pipe(handles) socketpair(AF_LOCAL, SOCK_STREAM, 0, handles)
127 #define DosWrite(hfile, pbuffer, cbwrite, pcbactual) \
128                 write(hfile, pbuffer, cbwrite)
129 #define DosExit(action, result )        /* do nothing */
130 #define DosCreateThread(ptid, pfn, param, flag, cbStack) \
131                 (*(ptid) = _beginthread(pfn, NULL, cbStack, \
132                                         (void *)param), (*(ptid) == -1))
133 #endif
134
135 #define MY_TRACE TRACE_ICALLS|TRACE_IEVENT
136
137 #define MASK_RELEASE(x)         (mmask_t) NCURSES_MOUSE_MASK(x, 001)
138 #define MASK_PRESS(x)           (mmask_t) NCURSES_MOUSE_MASK(x, 002)
139 #define MASK_CLICK(x)           (mmask_t) NCURSES_MOUSE_MASK(x, 004)
140 #define MASK_DOUBLE_CLICK(x)    (mmask_t) NCURSES_MOUSE_MASK(x, 010)
141 #define MASK_TRIPLE_CLICK(x)    (mmask_t) NCURSES_MOUSE_MASK(x, 020)
142 #define MASK_RESERVED_EVENT(x)  (mmask_t) NCURSES_MOUSE_MASK(x, 040)
143
144 #if NCURSES_MOUSE_VERSION == 1
145
146 #define BUTTON_CLICKED        (BUTTON1_CLICKED        | BUTTON2_CLICKED        | BUTTON3_CLICKED        | BUTTON4_CLICKED)
147 #define BUTTON_PRESSED        (BUTTON1_PRESSED        | BUTTON2_PRESSED        | BUTTON3_PRESSED        | BUTTON4_PRESSED)
148 #define BUTTON_RELEASED       (BUTTON1_RELEASED       | BUTTON2_RELEASED       | BUTTON3_RELEASED       | BUTTON4_RELEASED)
149 #define BUTTON_DOUBLE_CLICKED (BUTTON1_DOUBLE_CLICKED | BUTTON2_DOUBLE_CLICKED | BUTTON3_DOUBLE_CLICKED | BUTTON4_DOUBLE_CLICKED)
150 #define BUTTON_TRIPLE_CLICKED (BUTTON1_TRIPLE_CLICKED | BUTTON2_TRIPLE_CLICKED | BUTTON3_TRIPLE_CLICKED | BUTTON4_TRIPLE_CLICKED)
151
152 #define MAX_BUTTONS  4
153
154 #else
155
156 #define BUTTON_CLICKED        (BUTTON1_CLICKED        | BUTTON2_CLICKED        | BUTTON3_CLICKED        | BUTTON4_CLICKED        | BUTTON5_CLICKED)
157 #define BUTTON_PRESSED        (BUTTON1_PRESSED        | BUTTON2_PRESSED        | BUTTON3_PRESSED        | BUTTON4_PRESSED        | BUTTON5_PRESSED)
158 #define BUTTON_RELEASED       (BUTTON1_RELEASED       | BUTTON2_RELEASED       | BUTTON3_RELEASED       | BUTTON4_RELEASED       | BUTTON5_RELEASED)
159 #define BUTTON_DOUBLE_CLICKED (BUTTON1_DOUBLE_CLICKED | BUTTON2_DOUBLE_CLICKED | BUTTON3_DOUBLE_CLICKED | BUTTON4_DOUBLE_CLICKED | BUTTON5_DOUBLE_CLICKED)
160 #define BUTTON_TRIPLE_CLICKED (BUTTON1_TRIPLE_CLICKED | BUTTON2_TRIPLE_CLICKED | BUTTON3_TRIPLE_CLICKED | BUTTON4_TRIPLE_CLICKED | BUTTON5_TRIPLE_CLICKED)
161
162 #if NCURSES_MOUSE_VERSION == 2
163 #define MAX_BUTTONS  5
164 #else
165 #define MAX_BUTTONS  11
166 #endif
167
168 #endif
169
170 #define INVALID_EVENT   -1
171 #define NORMAL_EVENT    0
172
173 #define ValidEvent(ep) ((ep)->id != INVALID_EVENT)
174 #define Invalidate(ep) (ep)->id = INVALID_EVENT
175
176 #if USE_GPM_SUPPORT
177
178 #ifndef LIBGPM_SONAME
179 #define LIBGPM_SONAME "libgpm.so"
180 #endif
181
182 #define GET_DLSYM(name) (my_##name = (TYPE_##name) dlsym(sp->_dlopen_gpm, #name))
183
184 #endif                          /* USE_GPM_SUPPORT */
185
186 static bool _nc_mouse_parse(SCREEN *, int);
187 static void _nc_mouse_resume(SCREEN *);
188 static void _nc_mouse_wrap(SCREEN *);
189
190 /* maintain a circular list of mouse events */
191
192 #define FirstEV(sp)     ((sp)->_mouse_events)
193 #define LastEV(sp)      ((sp)->_mouse_events + EV_MAX - 1)
194
195 #undef  NEXT
196 #define NEXT(ep)        ((ep >= LastEV(SP_PARM)) \
197                          ? FirstEV(SP_PARM) \
198                          : ep + 1)
199
200 #undef  PREV
201 #define PREV(ep)        ((ep <= FirstEV(SP_PARM)) \
202                          ? LastEV(SP_PARM) \
203                          : ep - 1)
204
205 #define IndexEV(sp, ep) (ep - FirstEV(sp))
206
207 #define RunParams(sp, eventp, runp) \
208                 (long) IndexEV(sp, runp), \
209                 (long) (IndexEV(sp, eventp) + (EV_MAX - 1)) % EV_MAX
210
211 #ifdef TRACE
212 static void
213 _trace_slot(SCREEN *sp, const char *tag)
214 {
215     MEVENT *ep;
216
217     _tracef("%s", tag);
218
219     for (ep = FirstEV(sp); ep <= LastEV(sp); ep++)
220         _tracef("mouse event queue slot %ld = %s",
221                 (long) IndexEV(sp, ep),
222                 _nc_tracemouse(sp, ep));
223 }
224 #endif
225
226 #if USE_EMX_MOUSE
227
228 #  define TOP_ROW          0
229 #  define LEFT_COL         0
230
231 #  define M_FD(sp) sp->_mouse_fd
232
233 static void
234 write_event(SCREEN *sp, int down, int button, int x, int y)
235 {
236     char buf[6];
237     unsigned long ignore;
238
239     _nc_STRCPY(buf, "\033[M", sizeof(buf));     /* should be the same as key_mouse */
240     buf[3] = ' ' + (button - 1) + (down ? 0 : 0x40);
241     buf[4] = ' ' + x - LEFT_COL + 1;
242     buf[5] = ' ' + y - TOP_ROW + 1;
243     DosWrite(sp->_emxmouse_wfd, buf, 6, &ignore);
244 }
245
246 static void
247 #if USE_KLIBC_MOUSE
248 mouse_server(void *param)
249 #else
250 mouse_server(unsigned long param)
251 #endif
252 {
253     SCREEN *sp = (SCREEN *) param;
254     unsigned short fWait = MOU_WAIT;
255     /* NOPTRRECT mourt = { 0,0,24,79 }; */
256     MOUEVENTINFO mouev;
257     HMOU hmou;
258     unsigned short mask = MOUSE_BN1_DOWN | MOUSE_BN2_DOWN | MOUSE_BN3_DOWN;
259     int nbuttons = 3;
260     int oldstate = 0;
261     char err[80];
262     unsigned long rc;
263
264     /* open the handle for the mouse */
265     if (MouOpen(NULL, &hmou) == 0) {
266         rc = MouSetEventMask(&mask, hmou);
267         if (rc) {               /* retry with 2 buttons */
268             mask = MOUSE_BN1_DOWN | MOUSE_BN2_DOWN;
269             rc = MouSetEventMask(&mask, hmou);
270             nbuttons = 2;
271         }
272         if (rc == 0 && MouDrawPtr(hmou) == 0) {
273             for (;;) {
274                 /* sit and wait on the event queue */
275                 rc = MouReadEventQue(&mouev, &fWait, hmou);
276                 if (rc) {
277                     _nc_SPRINTF(err, _nc_SLIMIT(sizeof(err))
278                                 "Error reading mouse queue, rc=%lu.\r\n", rc);
279                     break;
280                 }
281                 if (!sp->_emxmouse_activated)
282                     goto finish;
283
284                 /*
285                  * OS/2 numbers a 3-button mouse inconsistently from other
286                  * platforms:
287                  *      1 = left
288                  *      2 = right
289                  *      3 = middle.
290                  */
291                 if ((mouev.fs ^ oldstate) & MOUSE_BN1_DOWN)
292                     write_event(sp, mouev.fs & MOUSE_BN1_DOWN,
293                                 sp->_emxmouse_buttons[1], mouev.col, mouev.row);
294                 if ((mouev.fs ^ oldstate) & MOUSE_BN2_DOWN)
295                     write_event(sp, mouev.fs & MOUSE_BN2_DOWN,
296                                 sp->_emxmouse_buttons[3], mouev.col, mouev.row);
297                 if ((mouev.fs ^ oldstate) & MOUSE_BN3_DOWN)
298                     write_event(sp, mouev.fs & MOUSE_BN3_DOWN,
299                                 sp->_emxmouse_buttons[2], mouev.col, mouev.row);
300
301               finish:
302                 oldstate = mouev.fs;
303             }
304         } else {
305             _nc_SPRINTF(err, _nc_SLIMIT(sizeof(err))
306                         "Error setting event mask, buttons=%d, rc=%lu.\r\n",
307                         nbuttons, rc);
308         }
309
310         DosWrite(2, err, strlen(err), &rc);
311         MouClose(hmou);
312     }
313     DosExit(EXIT_THREAD, 0L);
314 }
315
316 #endif /* USE_EMX_MOUSE */
317
318 #if USE_SYSMOUSE
319 static void
320 sysmouse_server(SCREEN *sp)
321 {
322     struct mouse_info the_mouse;
323     MEVENT *work;
324
325     the_mouse.operation = MOUSE_GETINFO;
326     if (sp != 0
327         && sp->_mouse_fd >= 0
328         && sp->_sysmouse_tail < FIFO_SIZE
329         && ioctl(sp->_mouse_fd, CONS_MOUSECTL, &the_mouse) != -1) {
330
331         if (sp->_sysmouse_head > sp->_sysmouse_tail) {
332             sp->_sysmouse_tail = 0;
333             sp->_sysmouse_head = 0;
334         }
335         work = &(sp->_sysmouse_fifo[sp->_sysmouse_tail]);
336         memset(work, 0, sizeof(*work));
337         work->id = NORMAL_EVENT;        /* there's only one mouse... */
338
339         sp->_sysmouse_old_buttons = sp->_sysmouse_new_buttons;
340         sp->_sysmouse_new_buttons = the_mouse.u.data.buttons & 0x7;
341
342         if (sp->_sysmouse_new_buttons) {
343             if (sp->_sysmouse_new_buttons & 1)
344                 work->bstate |= BUTTON1_PRESSED;
345             if (sp->_sysmouse_new_buttons & 2)
346                 work->bstate |= BUTTON2_PRESSED;
347             if (sp->_sysmouse_new_buttons & 4)
348                 work->bstate |= BUTTON3_PRESSED;
349         } else {
350             if (sp->_sysmouse_old_buttons & 1)
351                 work->bstate |= BUTTON1_RELEASED;
352             if (sp->_sysmouse_old_buttons & 2)
353                 work->bstate |= BUTTON2_RELEASED;
354             if (sp->_sysmouse_old_buttons & 4)
355                 work->bstate |= BUTTON3_RELEASED;
356         }
357
358         /* for cosmetic bug in syscons.c on FreeBSD 3.[34] */
359         the_mouse.operation = MOUSE_HIDE;
360         ioctl(sp->_mouse_fd, CONS_MOUSECTL, &the_mouse);
361         the_mouse.operation = MOUSE_SHOW;
362         ioctl(sp->_mouse_fd, CONS_MOUSECTL, &the_mouse);
363
364         /*
365          * We're only interested if the button is pressed or released.
366          * FIXME: implement continuous event-tracking.
367          */
368         if (sp->_sysmouse_new_buttons != sp->_sysmouse_old_buttons) {
369             sp->_sysmouse_tail += 1;
370         }
371         work->x = the_mouse.u.data.x / sp->_sysmouse_char_width;
372         work->y = the_mouse.u.data.y / sp->_sysmouse_char_height;
373     }
374 }
375
376 static void
377 handle_sysmouse(int sig GCC_UNUSED)
378 {
379     sysmouse_server(CURRENT_SCREEN);
380 }
381 #endif /* USE_SYSMOUSE */
382
383 #ifndef USE_TERM_DRIVER
384 #define xterm_kmous "\033[M"
385
386 static void
387 init_xterm_mouse(SCREEN *sp)
388 {
389     sp->_mouse_type = M_XTERM;
390     sp->_mouse_format = MF_X10;
391     sp->_mouse_xtermcap = tigetstr("XM");
392     if (VALID_STRING(sp->_mouse_xtermcap)) {
393         char *code = strstr(sp->_mouse_xtermcap, "[?");
394         if (code != 0) {
395             code += 2;
396             while ((*code >= '0') && (*code <= '9')) {
397                 char *next = code;
398                 while ((*next >= '0') && (*next <= '9')) {
399                     ++next;
400                 }
401                 if (!strncmp(code, "1006", (size_t) (next - code))) {
402                     sp->_mouse_format = MF_SGR1006;
403                 }
404 #ifdef EXP_XTERM_1005
405                 if (!strncmp(code, "1005", (size_t) (next - code))) {
406                     sp->_mouse_format = MF_XTERM_1005;
407                 }
408 #endif
409                 if (*next == ';') {
410                     while (*next == ';') {
411                         ++next;
412                     }
413                     code = next;
414                 } else {
415                     break;
416                 }
417             }
418         }
419     } else {
420         int code = tigetnum("XM");
421         switch (code) {
422 #ifdef EXP_XTERM_1005
423         case 1005:
424             /* see "xterm+sm+1005" */
425             sp->_mouse_xtermcap = "\033[?1005;1000%?%p1%{1}%=%th%el%;";
426             sp->_mouse_format = MF_XTERM_1005;
427             break;
428 #endif
429         case 1006:
430             /* see "xterm+sm+1006" */
431             sp->_mouse_xtermcap = "\033[?1006;1000%?%p1%{1}%=%th%el%;";
432             sp->_mouse_format = MF_SGR1006;
433             break;
434         default:
435             sp->_mouse_xtermcap = "\033[?1000%?%p1%{1}%=%th%el%;";
436             break;
437         }
438     }
439 }
440 #endif
441
442 static void
443 enable_xterm_mouse(SCREEN *sp, int enable)
444 {
445 #if USE_EMX_MOUSE
446     sp->_emxmouse_activated = enable;
447 #else
448     NCURSES_PUTP2("xterm-mouse", TIPARM_1(sp->_mouse_xtermcap, enable));
449 #endif
450     sp->_mouse_active = enable;
451 }
452
453 #if USE_GPM_SUPPORT
454 static bool
455 allow_gpm_mouse(SCREEN *sp GCC_UNUSED)
456 {
457     bool result = FALSE;
458
459 #if USE_WEAK_SYMBOLS
460     /* Danger Robinson: do not use dlopen for libgpm if already loaded */
461     if ((Gpm_Wgetch) != 0) {
462         if (!sp->_mouse_gpm_loaded) {
463             T(("GPM library was already dlopen'd, not by us"));
464         }
465     } else
466 #endif
467         /* GPM does printf's without checking if stdout is a terminal */
468     if (NC_ISATTY(fileno(stdout))) {
469         const char *list = getenv("NCURSES_GPM_TERMS");
470         const char *env = getenv("TERM");
471         if (list != 0) {
472             if (env != 0) {
473                 result = _nc_name_match(list, env, "|:");
474             }
475         } else {
476             /* GPM checks the beginning of the $TERM variable to decide if it
477              * should pass xterm events through.  There is no real advantage in
478              * allowing GPM to do this.  Recent versions relax that check, and
479              * pretend that GPM can work with any terminal having the kmous
480              * capability.  Perhaps that works for someone.  If so, they can
481              * set the environment variable (above).
482              */
483             if (env != 0 && strstr(env, "linux") != 0) {
484                 result = TRUE;
485             }
486         }
487     }
488     return result;
489 }
490
491 #ifdef HAVE_LIBDL
492 static void
493 unload_gpm_library(SCREEN *sp)
494 {
495     if (sp->_dlopen_gpm != 0) {
496         T(("unload GPM library"));
497         sp->_mouse_gpm_loaded = FALSE;
498         sp->_mouse_fd = -1;
499     }
500 }
501
502 static void
503 load_gpm_library(SCREEN *sp)
504 {
505     sp->_mouse_gpm_found = FALSE;
506
507     /*
508      * If we already had a successful dlopen, reuse it.
509      */
510     if (sp->_dlopen_gpm != 0) {
511         sp->_mouse_gpm_found = TRUE;
512         sp->_mouse_gpm_loaded = TRUE;
513     } else if ((sp->_dlopen_gpm = dlopen(LIBGPM_SONAME, my_RTLD)) != 0) {
514 #if (defined(__GNUC__) && (__GNUC__ >= 5)) || defined(__clang__)
515 #pragma GCC diagnostic push
516 #pragma GCC diagnostic ignored "-Wpedantic"
517 #endif
518         if (GET_DLSYM(gpm_fd) == 0 ||
519             GET_DLSYM(Gpm_Open) == 0 ||
520             GET_DLSYM(Gpm_Close) == 0 ||
521             GET_DLSYM(Gpm_GetEvent) == 0) {
522 #if (defined(__GNUC__) && (__GNUC__ >= 5)) || defined(__clang__)
523 #pragma GCC diagnostic pop
524 #endif
525             T(("GPM initialization failed: %s", dlerror()));
526             unload_gpm_library(sp);
527             dlclose(sp->_dlopen_gpm);
528             sp->_dlopen_gpm = 0;
529         } else {
530             sp->_mouse_gpm_found = TRUE;
531             sp->_mouse_gpm_loaded = TRUE;
532         }
533     }
534 }
535 #endif /* HAVE_LIBDL */
536
537 static bool
538 enable_gpm_mouse(SCREEN *sp, bool enable)
539 {
540     bool result;
541
542     T((T_CALLED("enable_gpm_mouse(%d)"), enable));
543
544     if (enable && !sp->_mouse_active) {
545 #ifdef HAVE_LIBDL
546         if (sp->_mouse_gpm_found && !sp->_mouse_gpm_loaded) {
547             load_gpm_library(sp);
548         }
549 #endif
550         if (sp->_mouse_gpm_loaded) {
551             int code;
552
553             /* GPM: initialize connection to gpm server */
554             sp->_mouse_gpm_connect.eventMask = GPM_DOWN | GPM_UP;
555             sp->_mouse_gpm_connect.defaultMask =
556                 (unsigned short) (~(sp->_mouse_gpm_connect.eventMask | GPM_HARD));
557             sp->_mouse_gpm_connect.minMod = 0;
558             sp->_mouse_gpm_connect.maxMod =
559                 (unsigned short) (~((1 << KG_SHIFT) |
560                                     (1 << KG_SHIFTL) |
561                                     (1 << KG_SHIFTR)));
562             /*
563              * Note: GPM hardcodes \E[?1001s and \E[?1000h during its open.
564              * The former is recognized by wscons (SunOS), and the latter by
565              * xterm.  Those will not show up in ncurses' traces.
566              */
567             code = my_Gpm_Open(&sp->_mouse_gpm_connect, 0);
568             result = (code >= 0);
569
570             /*
571              * GPM can return a -2 if it is trying to do something with xterm.
572              * Ignore that, since it conflicts with our use of stdin.
573              */
574             if (code == -2) {
575                 my_Gpm_Close();
576             }
577         } else {
578             result = FALSE;
579         }
580         sp->_mouse_active = result;
581         T(("GPM open %s", result ? "succeeded" : "failed"));
582     } else {
583         if (!enable && sp->_mouse_active) {
584             /* GPM: close connection to gpm server */
585             my_Gpm_Close();
586             sp->_mouse_active = FALSE;
587             T(("GPM closed"));
588         }
589         result = enable;
590     }
591 #ifdef HAVE_LIBDL
592     if (!result) {
593         unload_gpm_library(sp);
594     }
595 #endif
596     returnBool(result);
597 }
598 #endif /* USE_GPM_SUPPORT */
599
600 static void
601 initialize_mousetype(SCREEN *sp)
602 {
603     T((T_CALLED("initialize_mousetype()")));
604
605     /* Try gpm first, because gpm may be configured to run in xterm */
606 #if USE_GPM_SUPPORT
607     if (allow_gpm_mouse(sp)) {
608         if (!sp->_mouse_gpm_loaded) {
609 #ifdef HAVE_LIBDL
610             load_gpm_library(sp);
611 #else /* !HAVE_LIBDL */
612             sp->_mouse_gpm_found = TRUE;
613             sp->_mouse_gpm_loaded = TRUE;
614 #endif
615         }
616
617         /*
618          * The gpm_fd file-descriptor may be negative (xterm).  So we have to
619          * maintain our notion of whether the mouse connection is active
620          * without testing the file-descriptor.
621          */
622         if (sp->_mouse_gpm_found && enable_gpm_mouse(sp, TRUE)) {
623             sp->_mouse_type = M_GPM;
624             sp->_mouse_fd = *(my_gpm_fd);
625             T(("GPM mouse_fd %d", sp->_mouse_fd));
626             returnVoid;
627         }
628     }
629 #endif /* USE_GPM_SUPPORT */
630
631     /* OS/2 VIO */
632 #if USE_EMX_MOUSE
633     if (!sp->_emxmouse_thread
634         && strstr(SP_TERMTYPE term_names, "xterm") == 0
635         && NonEmpty(key_mouse)) {
636         int handles[2];
637
638         if (pipe(handles) < 0) {
639             perror("mouse pipe error");
640             returnVoid;
641         } else {
642             int rc;
643
644             if (!sp->_emxmouse_buttons[0]) {
645                 const char *s = getenv("MOUSE_BUTTONS_123");
646
647                 sp->_emxmouse_buttons[0] = 1;
648                 if (s && strlen(s) >= 3) {
649                     sp->_emxmouse_buttons[1] = s[0] - '0';
650                     sp->_emxmouse_buttons[2] = s[1] - '0';
651                     sp->_emxmouse_buttons[3] = s[2] - '0';
652                 } else {
653                     sp->_emxmouse_buttons[1] = 1;
654                     sp->_emxmouse_buttons[2] = 3;
655                     sp->_emxmouse_buttons[3] = 2;
656                 }
657             }
658             sp->_emxmouse_wfd = handles[1];
659             M_FD(sp) = handles[0];
660             /* Needed? */
661             setmode(handles[0], O_BINARY);
662             setmode(handles[1], O_BINARY);
663             /* Do not use CRT functions, we may single-threaded. */
664             rc = DosCreateThread((unsigned long *) &sp->_emxmouse_thread,
665                                  mouse_server, (long) sp, 0, 8192);
666             if (rc) {
667                 printf("mouse thread error %d=%#x", rc, rc);
668             } else {
669                 sp->_mouse_type = M_XTERM;
670             }
671             returnVoid;
672         }
673     }
674 #endif /* USE_EMX_MOUSE */
675
676 #if USE_SYSMOUSE
677     {
678         static char dev_tty[] = "/dev/tty";
679         struct mouse_info the_mouse;
680         char *the_device = 0;
681
682         if (NC_ISATTY(sp->_ifd))
683             the_device = ttyname(sp->_ifd);
684         if (the_device == 0)
685             the_device = dev_tty;
686
687         sp->_mouse_fd = open(the_device, O_RDWR);
688
689         if (sp->_mouse_fd >= 0) {
690             /*
691              * sysmouse does not have a usable user interface for obtaining
692              * mouse events.  The logical way to proceed (reading data on a
693              * stream) only works if one opens the device as root.  Even in
694              * that mode, careful examination shows we lose events
695              * occasionally.  The interface provided for user programs is to
696              * establish a signal handler.  really.
697              *
698              * Take over SIGUSR2 for this purpose since SIGUSR1 is more
699              * likely to be used by an application.  getch() will have to
700              * handle the misleading EINTR's.
701              */
702             signal(SIGUSR2, SIG_IGN);
703             the_mouse.operation = MOUSE_MODE;
704             the_mouse.u.mode.mode = 0;
705             the_mouse.u.mode.signal = SIGUSR2;
706             if (ioctl(sp->_mouse_fd, CONS_MOUSECTL, &the_mouse) != -1) {
707                 signal(SIGUSR2, handle_sysmouse);
708                 the_mouse.operation = MOUSE_SHOW;
709                 ioctl(sp->_mouse_fd, CONS_MOUSECTL, &the_mouse);
710
711 #if defined(FBIO_MODEINFO) || defined(CONS_MODEINFO)    /* FreeBSD > 2.x */
712                 {
713 #ifndef FBIO_GETMODE            /* FreeBSD 3.x */
714 #define FBIO_GETMODE    CONS_GET
715 #define FBIO_MODEINFO   CONS_MODEINFO
716 #endif /* FBIO_GETMODE */
717                     video_info_t the_video;
718
719                     if (ioctl(sp->_mouse_fd,
720                               FBIO_GETMODE,
721                               &the_video.vi_mode) != -1
722                         && ioctl(sp->_mouse_fd,
723                                  FBIO_MODEINFO,
724                                  &the_video) != -1) {
725                         sp->_sysmouse_char_width = the_video.vi_cwidth;
726                         sp->_sysmouse_char_height = the_video.vi_cheight;
727                     }
728                 }
729 #endif /* defined(FBIO_MODEINFO) || defined(CONS_MODEINFO) */
730
731                 if (sp->_sysmouse_char_width <= 0)
732                     sp->_sysmouse_char_width = 8;
733                 if (sp->_sysmouse_char_height <= 0)
734                     sp->_sysmouse_char_height = 16;
735                 sp->_mouse_type = M_SYSMOUSE;
736                 returnVoid;
737             }
738         }
739     }
740 #endif /* USE_SYSMOUSE */
741
742 #ifdef USE_TERM_DRIVER
743     CallDriver(sp, td_initmouse);
744 #else
745     /* we know how to recognize mouse events under "xterm" */
746     if (NonEmpty(key_mouse)) {
747         init_xterm_mouse(sp);
748     } else if (strstr(SP_TERMTYPE term_names, "xterm") != 0) {
749         if (_nc_add_to_try(&(sp->_keytry), xterm_kmous, KEY_MOUSE) == OK)
750             init_xterm_mouse(sp);
751     }
752 #endif
753
754     returnVoid;
755 }
756
757 static bool
758 _nc_mouse_init(SCREEN *sp)
759 /* initialize the mouse */
760 {
761     bool result = FALSE;
762
763     if (sp != 0) {
764         if (!sp->_mouse_initialized) {
765             int i;
766
767             sp->_mouse_initialized = TRUE;
768
769             TR(MY_TRACE, ("_nc_mouse_init() called"));
770
771             sp->_mouse_eventp = FirstEV(sp);
772             for (i = 0; i < EV_MAX; i++)
773                 Invalidate(sp->_mouse_events + i);
774
775             initialize_mousetype(sp);
776
777             T(("_nc_mouse_init() set mousetype to %d", sp->_mouse_type));
778         }
779         result = sp->_mouse_initialized;
780     }
781     return result;
782 }
783
784 /*
785  * Query to see if there is a pending mouse event.  This is called from
786  * fifo_push() in lib_getch.c
787  */
788 static bool
789 _nc_mouse_event(SCREEN *sp)
790 {
791     MEVENT *eventp = sp->_mouse_eventp;
792     bool result = FALSE;
793
794     (void) eventp;
795
796     switch (sp->_mouse_type) {
797     case M_XTERM:
798         /* xterm: never have to query, mouse events are in the keyboard stream */
799 #if USE_EMX_MOUSE
800         {
801             char kbuf[3];
802
803             int i, res = read(M_FD(sp), &kbuf, 3);      /* Eat the prefix */
804             if (res != 3)
805                 printf("Got %d chars instead of 3 for prefix.\n", res);
806             for (i = 0; i < res; i++) {
807                 if (kbuf[i] != key_mouse[i])
808                     printf("Got char %d instead of %d for prefix.\n",
809                            (int) kbuf[i], (int) key_mouse[i]);
810             }
811             result = TRUE;
812         }
813 #endif /* USE_EMX_MOUSE */
814         break;
815
816 #if USE_GPM_SUPPORT
817     case M_GPM:
818         if (sp->_mouse_fd >= 0) {
819             /* query server for event, return TRUE if we find one */
820             Gpm_Event ev;
821
822             switch (my_Gpm_GetEvent(&ev)) {
823             case 0:
824                 /* Connection closed, drop the mouse. */
825                 sp->_mouse_fd = -1;
826                 break;
827             case 1:
828                 /* there's only one mouse... */
829                 eventp->id = NORMAL_EVENT;
830
831                 eventp->bstate = 0;
832                 switch (ev.type & 0x0f) {
833                 case (GPM_DOWN):
834                     if (ev.buttons & GPM_B_LEFT)
835                         eventp->bstate |= BUTTON1_PRESSED;
836                     if (ev.buttons & GPM_B_MIDDLE)
837                         eventp->bstate |= BUTTON2_PRESSED;
838                     if (ev.buttons & GPM_B_RIGHT)
839                         eventp->bstate |= BUTTON3_PRESSED;
840                     break;
841                 case (GPM_UP):
842                     if (ev.buttons & GPM_B_LEFT)
843                         eventp->bstate |= BUTTON1_RELEASED;
844                     if (ev.buttons & GPM_B_MIDDLE)
845                         eventp->bstate |= BUTTON2_RELEASED;
846                     if (ev.buttons & GPM_B_RIGHT)
847                         eventp->bstate |= BUTTON3_RELEASED;
848                     break;
849                 default:
850                     eventp->bstate |= REPORT_MOUSE_POSITION;
851                     break;
852                 }
853
854                 eventp->x = ev.x - 1;
855                 eventp->y = ev.y - 1;
856                 eventp->z = 0;
857
858                 /* bump the next-free pointer into the circular list */
859                 sp->_mouse_eventp = NEXT(eventp);
860                 result = TRUE;
861                 break;
862             }
863         }
864         break;
865 #endif
866
867 #if USE_SYSMOUSE
868     case M_SYSMOUSE:
869         if (sp->_sysmouse_head < sp->_sysmouse_tail) {
870             *eventp = sp->_sysmouse_fifo[sp->_sysmouse_head];
871
872             /*
873              * Point the fifo-head to the next possible location.  If there
874              * are none, reset the indices.  This may be interrupted by the
875              * signal handler, doing essentially the same reset.
876              */
877             sp->_sysmouse_head += 1;
878             if (sp->_sysmouse_head == sp->_sysmouse_tail) {
879                 sp->_sysmouse_tail = 0;
880                 sp->_sysmouse_head = 0;
881             }
882
883             /* bump the next-free pointer into the circular list */
884             sp->_mouse_eventp = eventp = NEXT(eventp);
885             result = TRUE;
886         }
887         break;
888 #endif /* USE_SYSMOUSE */
889
890 #ifdef USE_TERM_DRIVER
891     case M_TERM_DRIVER:
892         while (sp->_drv_mouse_head < sp->_drv_mouse_tail) {
893             *eventp = sp->_drv_mouse_fifo[sp->_drv_mouse_head];
894
895             /*
896              * Point the fifo-head to the next possible location.  If there
897              * are none, reset the indices.
898              */
899             sp->_drv_mouse_head += 1;
900             if (sp->_drv_mouse_head == sp->_drv_mouse_tail) {
901                 sp->_drv_mouse_tail = 0;
902                 sp->_drv_mouse_head = 0;
903             }
904
905             /* bump the next-free pointer into the circular list */
906             sp->_mouse_eventp = eventp = NEXT(eventp);
907             result = TRUE;
908         }
909         break;
910 #endif
911
912     case M_NONE:
913         break;
914     }
915
916     return result;              /* true if we found an event */
917 }
918
919 #if USE_EMX_MOUSE
920 #define PRESS_POSITION(n) \
921     do { \
922             eventp->bstate = MASK_PRESS(n); \
923             sp->_mouse_bstate |= MASK_PRESS(n); \
924             if (button & 0x40) { \
925                     eventp->bstate = MASK_RELEASE(n); \
926                     sp->_mouse_bstate &= ~MASK_PRESS(n); \
927             } \
928     } while (0)
929 #else
930 #define PRESS_POSITION(n) \
931     do { \
932             eventp->bstate = (mmask_t) ((sp->_mouse_bstate & MASK_PRESS(n)) \
933                                     ? REPORT_MOUSE_POSITION \
934                                     : MASK_PRESS(n)); \
935             sp->_mouse_bstate |= MASK_PRESS(n); \
936     } while (0)
937 #endif
938
939 static bool
940 handle_wheel(SCREEN *sp, MEVENT * eventp, int button, int wheel)
941 {
942     bool result = TRUE;
943
944     switch (button & 3) {
945     case 0:
946         if (wheel) {
947             eventp->bstate = MASK_PRESS(4);
948             /* Do not record in sp->_mouse_bstate; there will be no
949              * corresponding release event.
950              */
951         } else {
952             PRESS_POSITION(1);
953         }
954         break;
955     case 1:
956         if (wheel) {
957 #if NCURSES_MOUSE_VERSION >= 2
958             eventp->bstate = MASK_PRESS(5);
959             /* See comment above for button 4 */
960 #else
961             /* Ignore this event as it is not a true press of the button */
962             eventp->bstate = REPORT_MOUSE_POSITION;
963 #endif
964         } else {
965             PRESS_POSITION(2);
966         }
967         break;
968     case 2:
969         PRESS_POSITION(3);
970         break;
971     default:
972         /*
973          * case 3 is sent when the mouse buttons are released.
974          *
975          * If the terminal uses xterm mode 1003, a continuous series of
976          * button-release events is sent as the mouse moves around the screen,
977          * or as the wheel mouse is rotated.
978          *
979          * Return false in this case, so that when running in X10 mode, we will
980          * recalculate bstate.
981          */
982         eventp->bstate = REPORT_MOUSE_POSITION;
983         result = FALSE;
984         break;
985     }
986     return result;
987 }
988
989 static bool
990 decode_X10_bstate(SCREEN *sp, MEVENT * eventp, unsigned intro)
991 {
992     bool result;
993     int button = 0;
994     int wheel = (intro & 96) == 96;
995
996     eventp->bstate = 0;
997
998     if (intro >= 96) {
999         if (intro >= 160) {
1000             button = (int) (intro - 152);       /* buttons 8-11 */
1001         } else {
1002             button = (int) (intro - 92);        /* buttons 4-7 */
1003         }
1004     } else {
1005         button = (intro & 3);
1006     }
1007
1008     if (button > MAX_BUTTONS) {
1009         eventp->bstate = REPORT_MOUSE_POSITION;
1010     } else if (!handle_wheel(sp, eventp, (int) intro, wheel)) {
1011
1012         /*
1013          * Release events aren't reported for individual buttons, just for
1014          * the button set as a whole.  However, because there are normally
1015          * no mouse events under xterm that intervene between press and
1016          * release, we can infer the button actually released by looking at
1017          * the previous event.
1018          */
1019         if (sp->_mouse_bstate & BUTTON_PRESSED) {
1020             int b;
1021
1022             eventp->bstate = BUTTON_RELEASED;
1023             for (b = 1; b <= MAX_BUTTONS; ++b) {
1024                 if (!(sp->_mouse_bstate & MASK_PRESS(b)))
1025                     eventp->bstate &= ~MASK_RELEASE(b);
1026             }
1027             sp->_mouse_bstate = 0;
1028         } else {
1029             /*
1030              * xterm will return a stream of release-events to let the
1031              * application know where the mouse is going, if private mode
1032              * 1002 or 1003 is enabled.
1033              */
1034             eventp->bstate = REPORT_MOUSE_POSITION;
1035         }
1036     }
1037
1038     if (intro & 4) {
1039         eventp->bstate |= BUTTON_SHIFT;
1040     }
1041     if (intro & 8) {
1042         eventp->bstate |= BUTTON_ALT;
1043     }
1044     if (intro & 16) {
1045         eventp->bstate |= BUTTON_CTRL;
1046     }
1047     result = (eventp->bstate & REPORT_MOUSE_POSITION) ? TRUE : FALSE;
1048     return result;
1049 }
1050
1051 /* This code requires that your xterm entry contain the kmous capability and
1052  * that it be set to the \E[M documented in the Xterm Control Sequences
1053  * reference.  This is how we arrange for mouse events to be reported via a
1054  * KEY_MOUSE return value from wgetch().  After this value is received,
1055  * _nc_mouse_inline() gets called and is immediately responsible for parsing
1056  * the mouse status information following the prefix.
1057  *
1058  * The following quotes from the ctlseqs.ms document in the XTerm distribution,
1059  * describing the mouse tracking feature:
1060  *
1061  * Parameters for all mouse tracking escape sequences generated by xterm encode
1062  * numeric parameters in a single character as value+040.  For example, ! is
1063  * 1.
1064  *
1065  * On button press or release, xterm sends ESC [ M CbCxCy.  The low two bits of
1066  * Cb encode button information:  0=MB1 pressed, 1=MB2 pressed, 2=MB3 pressed,
1067  * 3=release.  The upper bits encode what modifiers were down when the button
1068  * was pressed and are added together.  4=Shift, 8=Meta, 16=Control.  Cx and Cy
1069  * are the x and y coordinates of the mouse event.  The upper left corner is
1070  * (1,1).
1071  *
1072  * (End quote) By the time we get here, we've eaten the key prefix.  FYI, the
1073  * loop below is necessary because mouse click info isn't guaranteed to present
1074  * as a single clist item.
1075  *
1076  * Wheel mice may return buttons 4 and 5 when the wheel is turned.  We encode
1077  * those as button presses.
1078  */
1079 static bool
1080 decode_xterm_X10(SCREEN *sp, MEVENT * eventp)
1081 {
1082 #define MAX_KBUF 3
1083     unsigned char kbuf[MAX_KBUF + 1];
1084     size_t grabbed;
1085     int res;
1086     bool result;
1087
1088 # if USE_PTHREADS_EINTR
1089 #  if USE_WEAK_SYMBOLS
1090     if ((pthread_self) && (pthread_kill) && (pthread_equal))
1091 #  endif
1092         _nc_globals.read_thread = pthread_self();
1093 # endif
1094     for (grabbed = 0; grabbed < MAX_KBUF; grabbed += (size_t) res) {
1095
1096         /* For VIO mouse we add extra bit 64 to disambiguate button-up. */
1097         res = (int) read(
1098 #if USE_EMX_MOUSE
1099                             (M_FD(sp) >= 0) ? M_FD(sp) : sp->_ifd,
1100 #else
1101                             sp->_ifd,
1102 #endif
1103                             kbuf + grabbed, (size_t) (MAX_KBUF - (int) grabbed));
1104         if (res == -1)
1105             break;
1106     }
1107 #if USE_PTHREADS_EINTR
1108     _nc_globals.read_thread = 0;
1109 #endif
1110     kbuf[MAX_KBUF] = '\0';
1111
1112     TR(TRACE_IEVENT,
1113        ("_nc_mouse_inline sees the following xterm data: '%s'", kbuf));
1114
1115     /* there's only one mouse... */
1116     eventp->id = NORMAL_EVENT;
1117
1118     result = decode_X10_bstate(sp, eventp, kbuf[0]);
1119
1120     eventp->x = (kbuf[1] - ' ') - 1;
1121     eventp->y = (kbuf[2] - ' ') - 1;
1122
1123     return result;
1124 }
1125
1126 #ifdef EXP_XTERM_1005
1127 /*
1128  * This is identical to X10/X11 responses except that there are two UTF-8
1129  * characters storing the ordinates instead of two bytes.
1130  */
1131 static bool
1132 decode_xterm_1005(SCREEN *sp, MEVENT * eventp)
1133 {
1134     char kbuf[80];
1135     size_t grabbed;
1136     size_t limit = (sizeof(kbuf) - 1);
1137     unsigned coords[2];
1138     bool result;
1139
1140     coords[0] = 0;
1141     coords[1] = 0;
1142
1143 # if USE_PTHREADS_EINTR
1144 #  if USE_WEAK_SYMBOLS
1145     if ((pthread_self) && (pthread_kill) && (pthread_equal))
1146 #  endif
1147         _nc_globals.read_thread = pthread_self();
1148 # endif
1149     for (grabbed = 0; grabbed < limit;) {
1150         int res;
1151
1152         res = (int) read(
1153 #if USE_EMX_MOUSE
1154                             (M_FD(sp) >= 0) ? M_FD(sp) : sp->_ifd,
1155 #else
1156                             sp->_ifd,
1157 #endif
1158                             (kbuf + grabbed), (size_t) 1);
1159         if (res == -1)
1160             break;
1161         grabbed += (size_t) res;
1162         if (grabbed > 1) {
1163             size_t check = 1;
1164             int n;
1165
1166             for (n = 0; n < 2; ++n) {
1167                 int rc;
1168
1169                 if (check >= grabbed)
1170                     break;
1171                 rc = _nc_conv_to_utf32(&coords[n], kbuf + check, (unsigned)
1172                                        (grabbed - check));
1173                 if (!rc)
1174                     break;
1175                 check += (size_t) rc;
1176             }
1177             if (n >= 2)
1178                 break;
1179         }
1180     }
1181 #if USE_PTHREADS_EINTR
1182     _nc_globals.read_thread = 0;
1183 #endif
1184
1185     TR(TRACE_IEVENT,
1186        ("_nc_mouse_inline sees the following xterm data: %s",
1187         _nc_visbufn(kbuf, (int) grabbed)));
1188
1189     /* there's only one mouse... */
1190     eventp->id = NORMAL_EVENT;
1191
1192     result = decode_X10_bstate(sp, eventp, UChar(kbuf[0]));
1193
1194     eventp->x = (int) (coords[0] - ' ') - 1;
1195     eventp->y = (int) (coords[1] - ' ') - 1;
1196
1197     return result;
1198 }
1199 #endif /* EXP_XTERM_1005 */
1200
1201 /*
1202  * ECMA-48 section 5.4
1203  */
1204 #define isInter(c) ((c) >= 0x20 && (c) <= 0x2f)
1205 #define isParam(c) ((c) >= 0x30 && (c) <= 0x3f)
1206 #define isFinal(c) ((c) >= 0x40 && (c) <= 0x7e)
1207
1208 #define MAX_PARAMS 9
1209
1210 typedef struct {
1211     int nerror;                 /* nonzero if there are unexpected chars */
1212     int nparam;                 /* number of numeric parameters */
1213     int params[MAX_PARAMS];
1214     int final;                  /* the final-character */
1215 } SGR_DATA;
1216
1217 static bool
1218 read_SGR(SCREEN *sp, SGR_DATA * result)
1219 {
1220     char kbuf[80];              /* bigger than any possible mouse response */
1221     int grabbed = 0;
1222     int ch = 0;
1223     int now = -1;
1224     int marker = 1;
1225
1226     memset(result, 0, sizeof(*result));
1227 # if USE_PTHREADS_EINTR
1228 #  if USE_WEAK_SYMBOLS
1229     if ((pthread_self) && (pthread_kill) && (pthread_equal))
1230 #  endif
1231         _nc_globals.read_thread = pthread_self();
1232 # endif
1233
1234     do {
1235         int res;
1236
1237         res = (int) read(
1238 #if USE_EMX_MOUSE
1239                             (M_FD(sp) >= 0) ? M_FD(sp) : sp->_ifd,
1240 #else
1241                             sp->_ifd,
1242 #endif
1243                             (kbuf + grabbed), (size_t) 1);
1244         if (res == -1)
1245             break;
1246         if ((grabbed + MAX_KBUF) >= (int) sizeof(kbuf)) {
1247             result->nerror++;
1248             break;
1249         }
1250         ch = UChar(kbuf[grabbed]);
1251         kbuf[grabbed + 1] = 0;
1252         switch (ch) {
1253         case '0':
1254         case '1':
1255         case '2':
1256         case '3':
1257         case '4':
1258         case '5':
1259         case '6':
1260         case '7':
1261         case '8':
1262         case '9':
1263             if (marker) {
1264                 ++now;
1265                 result->nparam = (now + 1);
1266             }
1267             marker = 0;
1268             result->params[now] = (result->params[now] * 10) + (ch - '0');
1269             break;
1270         case ';':
1271             if (marker) {
1272                 ++now;
1273                 result->nparam = (now + 1);
1274             }
1275             marker = 1;
1276             break;
1277         default:
1278             if (ch < 32 || ch > 126) {
1279                 /*
1280                  * Technically other characters could be interspersed in the
1281                  * response.  Ignore those for now.
1282                  */
1283                 result->nerror++;
1284                 continue;
1285             } else if (isFinal(ch)) {
1286                 if (marker) {
1287                     result->nparam++;
1288                 }
1289                 result->final = ch;
1290             } else {
1291                 result->nerror++;
1292             }
1293             break;
1294         }
1295         ++grabbed;
1296     } while (!isFinal(ch));
1297 #if USE_PTHREADS_EINTR
1298     _nc_globals.read_thread = 0;
1299 #endif
1300
1301     kbuf[++grabbed] = 0;
1302     TR(TRACE_IEVENT,
1303        ("_nc_mouse_inline sees the following xterm data: '%s'", kbuf));
1304     return (grabbed > 0) && (result->nerror == 0);
1305 }
1306
1307 static bool
1308 decode_xterm_SGR1006(SCREEN *sp, MEVENT * eventp)
1309 {
1310     SGR_DATA data;
1311     bool result = FALSE;
1312     if (read_SGR(sp, &data)) {
1313         int b = data.params[0];
1314         int b3 = 1 + (b & 3);
1315         int wheel = ((b & 64) == 64);
1316
1317         if (b >= 132) {
1318             b3 = MAX_BUTTONS + 1;
1319         } else if (b >= 128) {
1320             b3 = (b - 120);     /* buttons 8-11 */
1321         } else if (b >= 64) {
1322             b3 = (b - 60);      /* buttons 6-7 */
1323         }
1324
1325         eventp->id = NORMAL_EVENT;
1326         if (data.final == 'M') {
1327             (void) handle_wheel(sp, eventp, b, wheel);
1328         } else if (b3 > MAX_BUTTONS) {
1329             eventp->bstate = REPORT_MOUSE_POSITION;
1330         } else {
1331             mmask_t pressed = (mmask_t) NCURSES_MOUSE_MASK(b3, NCURSES_BUTTON_PRESSED);
1332             mmask_t release = (mmask_t) NCURSES_MOUSE_MASK(b3, NCURSES_BUTTON_RELEASED);
1333             if (sp->_mouse_bstate & pressed) {
1334                 eventp->bstate = release;
1335                 sp->_mouse_bstate &= ~pressed;
1336             } else {
1337                 eventp->bstate = REPORT_MOUSE_POSITION;
1338             }
1339         }
1340         if (b & 4) {
1341             eventp->bstate |= BUTTON_SHIFT;
1342         }
1343         if (b & 8) {
1344             eventp->bstate |= BUTTON_ALT;
1345         }
1346         if (b & 16) {
1347             eventp->bstate |= BUTTON_CTRL;
1348         }
1349         result = (eventp->bstate & REPORT_MOUSE_POSITION) ? TRUE : FALSE;
1350         eventp->x = (data.params[1] ? (data.params[1] - 1) : 0);
1351         eventp->y = (data.params[2] ? (data.params[2] - 1) : 0);
1352     }
1353     return result;
1354 }
1355
1356 static bool
1357 _nc_mouse_inline(SCREEN *sp)
1358 /* mouse report received in the keyboard stream -- parse its info */
1359 {
1360     bool result = FALSE;
1361     MEVENT *eventp = sp->_mouse_eventp;
1362
1363     TR(MY_TRACE, ("_nc_mouse_inline() called"));
1364
1365     if (sp->_mouse_type == M_XTERM) {
1366         switch (sp->_mouse_format) {
1367         case MF_X10:
1368             result = decode_xterm_X10(sp, eventp);
1369             break;
1370         case MF_SGR1006:
1371             result = decode_xterm_SGR1006(sp, eventp);
1372             break;
1373 #ifdef EXP_XTERM_1005
1374         case MF_XTERM_1005:
1375             result = decode_xterm_1005(sp, eventp);
1376             break;
1377 #endif
1378         }
1379
1380         TR(MY_TRACE,
1381            ("_nc_mouse_inline: primitive mouse-event %s has slot %ld",
1382             _nc_tracemouse(sp, eventp),
1383             (long) IndexEV(sp, eventp)));
1384
1385         /* bump the next-free pointer into the circular list */
1386         sp->_mouse_eventp = NEXT(eventp);
1387
1388         if (!result) {
1389             /* If this event is from a wheel-mouse, treat it like position
1390              * reports and avoid waiting for the release-events which will
1391              * never come.
1392              */
1393             if (eventp->bstate & BUTTON_PRESSED) {
1394                 int b;
1395
1396                 for (b = 4; b <= MAX_BUTTONS; ++b) {
1397                     if ((eventp->bstate & MASK_PRESS(b))) {
1398                         result = TRUE;
1399                         break;
1400                     }
1401                 }
1402             }
1403         }
1404     }
1405
1406     return (result);
1407 }
1408
1409 static void
1410 mouse_activate(SCREEN *sp, int on)
1411 {
1412     if (!on && !sp->_mouse_initialized)
1413         return;
1414
1415     if (!_nc_mouse_init(sp))
1416         return;
1417
1418     if (on) {
1419         sp->_mouse_bstate = 0;
1420         switch (sp->_mouse_type) {
1421         case M_XTERM:
1422 #if NCURSES_EXT_FUNCS
1423             NCURSES_SP_NAME(keyok) (NCURSES_SP_ARGx KEY_MOUSE, on);
1424 #endif
1425             TPUTS_TRACE("xterm mouse initialization");
1426             enable_xterm_mouse(sp, 1);
1427             break;
1428 #if USE_GPM_SUPPORT
1429         case M_GPM:
1430             if (enable_gpm_mouse(sp, TRUE)) {
1431                 sp->_mouse_fd = *(my_gpm_fd);
1432                 T(("GPM mouse_fd %d", sp->_mouse_fd));
1433             }
1434             break;
1435 #endif
1436 #if USE_SYSMOUSE
1437         case M_SYSMOUSE:
1438             signal(SIGUSR2, handle_sysmouse);
1439             sp->_mouse_active = TRUE;
1440             break;
1441 #endif
1442 #ifdef USE_TERM_DRIVER
1443         case M_TERM_DRIVER:
1444             sp->_mouse_active = TRUE;
1445             break;
1446 #endif
1447         case M_NONE:
1448             return;
1449         }
1450         /* Make runtime binding to cut down on object size of applications that
1451          * do not use the mouse (e.g., 'clear').
1452          */
1453         sp->_mouse_event = _nc_mouse_event;
1454         sp->_mouse_inline = _nc_mouse_inline;
1455         sp->_mouse_parse = _nc_mouse_parse;
1456         sp->_mouse_resume = _nc_mouse_resume;
1457         sp->_mouse_wrap = _nc_mouse_wrap;
1458     } else {
1459
1460         switch (sp->_mouse_type) {
1461         case M_XTERM:
1462             TPUTS_TRACE("xterm mouse deinitialization");
1463             enable_xterm_mouse(sp, 0);
1464             break;
1465 #if USE_GPM_SUPPORT
1466         case M_GPM:
1467             enable_gpm_mouse(sp, FALSE);
1468             break;
1469 #endif
1470 #if USE_SYSMOUSE
1471         case M_SYSMOUSE:
1472             signal(SIGUSR2, SIG_IGN);
1473             sp->_mouse_active = FALSE;
1474             break;
1475 #endif
1476 #ifdef USE_TERM_DRIVER
1477         case M_TERM_DRIVER:
1478             sp->_mouse_active = FALSE;
1479             break;
1480 #endif
1481         case M_NONE:
1482             return;
1483         }
1484     }
1485     NCURSES_SP_NAME(_nc_flush) (NCURSES_SP_ARG);
1486 }
1487
1488 /**************************************************************************
1489  *
1490  * Device-independent code
1491  *
1492  **************************************************************************/
1493
1494 static bool
1495 _nc_mouse_parse(SCREEN *sp, int runcount)
1496 /* parse a run of atomic mouse events into a gesture */
1497 {
1498     MEVENT *eventp = sp->_mouse_eventp;
1499     MEVENT *next, *ep;
1500     MEVENT *first_valid = NULL;
1501     MEVENT *first_invalid = NULL;
1502     int n;
1503     int b;
1504     bool merge;
1505     bool endLoop;
1506
1507     TR(MY_TRACE, ("_nc_mouse_parse(%d) called", runcount));
1508
1509     /*
1510      * When we enter this routine, the event list next-free pointer
1511      * points just past a run of mouse events that we know were separated
1512      * in time by less than the critical click interval. The job of this
1513      * routine is to collapse this run into a single higher-level event
1514      * or gesture.
1515      *
1516      * We accomplish this in two passes.  The first pass merges press/release
1517      * pairs into click events.  The second merges runs of click events into
1518      * double or triple-click events.
1519      *
1520      * It's possible that the run may not resolve to a single event (for
1521      * example, if the user quadruple-clicks).  If so, leading events
1522      * in the run are ignored if user does not call getmouse in a loop (getting
1523      * them from newest to older).
1524      *
1525      * Note that this routine is independent of the format of the specific
1526      * format of the pointing-device's reports.  We can use it to parse
1527      * gestures on anything that reports press/release events on a per-
1528      * button basis, as long as the device-dependent mouse code puts stuff
1529      * on the queue in MEVENT format.
1530      */
1531
1532     /*
1533      * Reset all events that were not set, in case the user sometimes calls
1534      * getmouse only once and other times until there are no more events in
1535      * queue.
1536      *
1537      * This also allows reaching the beginning of the run.
1538      */
1539     ep = eventp;
1540     for (n = runcount; n < EV_MAX; n++) {
1541         Invalidate(ep);
1542         ep = NEXT(ep);
1543     }
1544
1545 #ifdef TRACE
1546     if (USE_TRACEF(TRACE_IEVENT)) {
1547         _trace_slot(sp, "before mouse press/release merge:");
1548         _tracef("_nc_mouse_parse: run starts at %ld, ends at %ld, count %d",
1549                 RunParams(sp, eventp, ep),
1550                 runcount);
1551         _nc_unlock_global(tracef);
1552     }
1553 #endif /* TRACE */
1554
1555     /* first pass; merge press/release pairs */
1556     endLoop = FALSE;
1557     while (!endLoop) {
1558         next = NEXT(ep);
1559         if (next == eventp) {
1560             /* Will end the loop, but compact before */
1561             endLoop = TRUE;
1562         } else {
1563
1564 #define MASK_CHANGED(x) (!(ep->bstate & MASK_PRESS(x)) \
1565                       == !(next->bstate & MASK_RELEASE(x)))
1566
1567             if (ValidEvent(ep) && ValidEvent(next)
1568                 && ep->x == next->x && ep->y == next->y
1569                 && (ep->bstate & BUTTON_PRESSED)
1570                 && (!(next->bstate & BUTTON_PRESSED))) {
1571                 bool changed = TRUE;
1572
1573                 for (b = 1; b <= MAX_BUTTONS; ++b) {
1574                     if (!MASK_CHANGED(b)) {
1575                         changed = FALSE;
1576                         break;
1577                     }
1578                 }
1579
1580                 if (changed) {
1581                     merge = FALSE;
1582                     for (b = 1; b <= MAX_BUTTONS; ++b) {
1583                         if ((sp->_mouse_mask2 & MASK_CLICK(b))
1584                             && (ep->bstate & MASK_PRESS(b))) {
1585                             next->bstate &= ~MASK_RELEASE(b);
1586                             next->bstate |= MASK_CLICK(b);
1587                             merge = TRUE;
1588                         }
1589                     }
1590                     if (merge) {
1591                         Invalidate(ep);
1592                     }
1593                 }
1594             }
1595         }
1596
1597         /* Compact valid events */
1598         if (!ValidEvent(ep)) {
1599             if ((first_valid != NULL) && (first_invalid == NULL)) {
1600                 first_invalid = ep;
1601             }
1602         } else {
1603             if (first_valid == NULL) {
1604                 first_valid = ep;
1605             } else if (first_invalid != NULL) {
1606                 *first_invalid = *ep;
1607                 Invalidate(ep);
1608                 first_invalid = NEXT(first_invalid);
1609             }
1610         }
1611
1612         ep = next;
1613     }
1614
1615     if (first_invalid != NULL) {
1616         eventp = first_invalid;
1617     }
1618 #ifdef TRACE
1619     if (USE_TRACEF(TRACE_IEVENT)) {
1620         _trace_slot(sp, "before mouse click merge:");
1621         if (first_valid == NULL) {
1622             _tracef("_nc_mouse_parse: no valid event");
1623         } else {
1624             _tracef("_nc_mouse_parse: run starts at %ld, ends at %ld, count %d",
1625                     RunParams(sp, eventp, first_valid),
1626                     runcount);
1627             _nc_unlock_global(tracef);
1628         }
1629     }
1630 #endif /* TRACE */
1631
1632     /*
1633      * Second pass; merge click runs.  We merge click events forward in the
1634      * queue.  For example, double click can be changed to triple click.
1635      *
1636      * NOTE: There is a problem with this design!  If the application
1637      * allows enough click events to pile up in the circular queue so
1638      * they wrap around, it will cheerfully merge the newest forward
1639      * into the oldest, creating a bogus doubleclick and confusing
1640      * the queue-traversal logic rather badly.  Generally this won't
1641      * happen, because calling getmouse() marks old events invalid and
1642      * ineligible for merges.  The true solution to this problem would
1643      * be to timestamp each MEVENT and perform the obvious sanity check,
1644      * but the timer element would have to have sub-second resolution,
1645      * which would get us into portability trouble.
1646      */
1647     first_invalid = NULL;
1648     endLoop = (first_valid == NULL);
1649     ep = first_valid;
1650     while (!endLoop) {
1651         next = NEXT(ep);
1652
1653         if (next == eventp) {
1654             /* Will end the loop, but check event type and compact before */
1655             endLoop = TRUE;
1656         } else if (!ValidEvent(next)) {
1657             continue;
1658         } else {
1659             /* merge click events forward */
1660             if ((ep->bstate & BUTTON_CLICKED)
1661                 && (next->bstate & BUTTON_CLICKED)) {
1662                 merge = FALSE;
1663                 for (b = 1; b <= MAX_BUTTONS; ++b) {
1664                     if ((sp->_mouse_mask2 & MASK_DOUBLE_CLICK(b))
1665                         && (ep->bstate & MASK_CLICK(b))
1666                         && (next->bstate & MASK_CLICK(b))) {
1667                         next->bstate &= ~MASK_CLICK(b);
1668                         next->bstate |= MASK_DOUBLE_CLICK(b);
1669                         merge = TRUE;
1670                     }
1671                 }
1672                 if (merge) {
1673                     Invalidate(ep);
1674                 }
1675             }
1676
1677             /* merge double-click events forward */
1678             if ((ep->bstate & BUTTON_DOUBLE_CLICKED)
1679                 && (next->bstate & BUTTON_CLICKED)) {
1680                 merge = FALSE;
1681                 for (b = 1; b <= MAX_BUTTONS; ++b) {
1682                     if ((sp->_mouse_mask2 & MASK_TRIPLE_CLICK(b))
1683                         && (ep->bstate & MASK_DOUBLE_CLICK(b))
1684                         && (next->bstate & MASK_CLICK(b))) {
1685                         next->bstate &= ~MASK_CLICK(b);
1686                         next->bstate |= MASK_TRIPLE_CLICK(b);
1687                         merge = TRUE;
1688                     }
1689                 }
1690                 if (merge) {
1691                     Invalidate(ep);
1692                 }
1693             }
1694         }
1695
1696         /* Discard event if it does not match event mask */
1697         if (!(ep->bstate & sp->_mouse_mask2)) {
1698             Invalidate(ep);
1699         }
1700
1701         /* Compact valid events */
1702         if (!ValidEvent(ep)) {
1703             if (ep == first_valid) {
1704                 first_valid = next;
1705             } else if (first_invalid == NULL) {
1706                 first_invalid = ep;
1707             }
1708         } else if (first_invalid != NULL) {
1709             *first_invalid = *ep;
1710             Invalidate(ep);
1711             first_invalid = NEXT(first_invalid);
1712         }
1713
1714         ep = next;
1715     }
1716
1717     if (first_invalid == NULL) {
1718         first_invalid = eventp;
1719     }
1720     sp->_mouse_eventp = first_invalid;
1721
1722 #ifdef TRACE
1723     if (first_valid != NULL) {
1724         if (USE_TRACEF(TRACE_IEVENT)) {
1725             _trace_slot(sp, "after mouse event queue compaction:");
1726             _tracef("_nc_mouse_parse: run starts at %ld, ends at %ld, count %d",
1727                     RunParams(sp, first_invalid, first_valid),
1728                     runcount);
1729             _nc_unlock_global(tracef);
1730         }
1731         for (ep = first_valid; ep != first_invalid; ep = NEXT(ep)) {
1732             if (ValidEvent(ep))
1733                 TR(MY_TRACE,
1734                    ("_nc_mouse_parse: returning composite mouse event %s at slot %ld",
1735                     _nc_tracemouse(sp, ep),
1736                     (long) IndexEV(sp, ep)));
1737         }
1738     }
1739 #endif /* TRACE */
1740
1741     /* after all this, do we have a valid event? */
1742     ep = PREV(first_invalid);
1743     return ValidEvent(ep) && ((ep->bstate & sp->_mouse_mask) != 0);
1744 }
1745
1746 static void
1747 _nc_mouse_wrap(SCREEN *sp)
1748 /* release mouse -- called by endwin() before shellout/exit */
1749 {
1750     TR(MY_TRACE, ("_nc_mouse_wrap() called"));
1751
1752     switch (sp->_mouse_type) {
1753     case M_XTERM:
1754         if (sp->_mouse_mask)
1755             mouse_activate(sp, FALSE);
1756         break;
1757 #if USE_GPM_SUPPORT
1758         /* GPM: pass all mouse events to next client */
1759     case M_GPM:
1760         if (sp->_mouse_mask)
1761             mouse_activate(sp, FALSE);
1762         break;
1763 #endif
1764 #if USE_SYSMOUSE
1765     case M_SYSMOUSE:
1766         mouse_activate(sp, FALSE);
1767         break;
1768 #endif
1769 #ifdef USE_TERM_DRIVER
1770     case M_TERM_DRIVER:
1771         mouse_activate(sp, FALSE);
1772         break;
1773 #endif
1774     case M_NONE:
1775         break;
1776     }
1777 }
1778
1779 static void
1780 _nc_mouse_resume(SCREEN *sp)
1781 /* re-connect to mouse -- called by doupdate() after shellout */
1782 {
1783     TR(MY_TRACE, ("_nc_mouse_resume() called"));
1784
1785     switch (sp->_mouse_type) {
1786     case M_XTERM:
1787         /* xterm: re-enable reporting */
1788         if (sp->_mouse_mask)
1789             mouse_activate(sp, TRUE);
1790         break;
1791
1792 #if USE_GPM_SUPPORT
1793     case M_GPM:
1794         /* GPM: reclaim our event set */
1795         if (sp->_mouse_mask)
1796             mouse_activate(sp, TRUE);
1797         break;
1798 #endif
1799
1800 #if USE_SYSMOUSE
1801     case M_SYSMOUSE:
1802         mouse_activate(sp, TRUE);
1803         break;
1804 #endif
1805
1806 #ifdef USE_TERM_DRIVER
1807     case M_TERM_DRIVER:
1808         mouse_activate(sp, TRUE);
1809         break;
1810 #endif
1811
1812     case M_NONE:
1813         break;
1814     }
1815 }
1816
1817 /**************************************************************************
1818  *
1819  * Mouse interface entry points for the API
1820  *
1821  **************************************************************************/
1822
1823 NCURSES_EXPORT(int)
1824 NCURSES_SP_NAME(getmouse) (NCURSES_SP_DCLx MEVENT * aevent)
1825 {
1826     int result = ERR;
1827     MEVENT *eventp;
1828
1829     T((T_CALLED("getmouse(%p,%p)"), (void *) SP_PARM, (void *) aevent));
1830
1831     if ((aevent != 0) &&
1832         (SP_PARM != 0) &&
1833         (SP_PARM->_mouse_type != M_NONE) &&
1834         (eventp = SP_PARM->_mouse_eventp) != 0) {
1835         /* compute the current-event pointer */
1836         MEVENT *prev = PREV(eventp);
1837
1838         /*
1839          * Discard events not matching mask (there could be still some if
1840          * _nc_mouse_parse was not called, e.g., when _nc_mouse_inline returns
1841          * false).
1842          */
1843         while (ValidEvent(prev) && (!(prev->bstate & SP_PARM->_mouse_mask2))) {
1844             Invalidate(prev);
1845             prev = PREV(prev);
1846         }
1847         if (ValidEvent(prev)) {
1848             /* copy the event we find there */
1849             *aevent = *prev;
1850
1851             TR(TRACE_IEVENT, ("getmouse: returning event %s from slot %ld",
1852                               _nc_tracemouse(SP_PARM, prev),
1853                               (long) IndexEV(SP_PARM, prev)));
1854
1855             Invalidate(prev);   /* so the queue slot becomes free */
1856             SP_PARM->_mouse_eventp = prev;
1857             result = OK;
1858         } else {
1859             /* Reset the provided event */
1860             aevent->bstate = 0;
1861             Invalidate(aevent);
1862             aevent->x = 0;
1863             aevent->y = 0;
1864             aevent->z = 0;
1865         }
1866     }
1867     returnCode(result);
1868 }
1869
1870 #if NCURSES_SP_FUNCS
1871 /* grab a copy of the current mouse event */
1872 NCURSES_EXPORT(int)
1873 getmouse(MEVENT * aevent)
1874 {
1875     return NCURSES_SP_NAME(getmouse) (CURRENT_SCREEN, aevent);
1876 }
1877 #endif
1878
1879 NCURSES_EXPORT(int)
1880 NCURSES_SP_NAME(ungetmouse) (NCURSES_SP_DCLx MEVENT * aevent)
1881 {
1882     int result = ERR;
1883     MEVENT *eventp;
1884
1885     T((T_CALLED("ungetmouse(%p,%p)"), (void *) SP_PARM, (void *) aevent));
1886
1887     if (aevent != 0 &&
1888         SP_PARM != 0 &&
1889         (eventp = SP_PARM->_mouse_eventp) != 0) {
1890
1891         /* stick the given event in the next-free slot */
1892         *eventp = *aevent;
1893
1894         /* bump the next-free pointer into the circular list */
1895         SP_PARM->_mouse_eventp = NEXT(eventp);
1896
1897         /* push back the notification event on the keyboard queue */
1898         result = NCURSES_SP_NAME(ungetch) (NCURSES_SP_ARGx KEY_MOUSE);
1899     }
1900     returnCode(result);
1901 }
1902
1903 #if NCURSES_SP_FUNCS
1904 /* enqueue a synthesized mouse event to be seen by the next wgetch() */
1905 NCURSES_EXPORT(int)
1906 ungetmouse(MEVENT * aevent)
1907 {
1908     return NCURSES_SP_NAME(ungetmouse) (CURRENT_SCREEN, aevent);
1909 }
1910 #endif
1911
1912 NCURSES_EXPORT(mmask_t)
1913 NCURSES_SP_NAME(mousemask) (NCURSES_SP_DCLx mmask_t newmask, mmask_t * oldmask)
1914 /* set the mouse event mask */
1915 {
1916     mmask_t result = 0;
1917
1918     T((T_CALLED("mousemask(%p,%#lx,%p)"),
1919        (void *) SP_PARM,
1920        (unsigned long) newmask,
1921        (void *) oldmask));
1922
1923     if (SP_PARM != 0) {
1924         if (oldmask)
1925             *oldmask = SP_PARM->_mouse_mask;
1926
1927         if (newmask || SP_PARM->_mouse_initialized) {
1928             _nc_mouse_init(SP_PARM);
1929
1930             if (SP_PARM->_mouse_type != M_NONE) {
1931                 int b;
1932
1933                 result = newmask &
1934                     (REPORT_MOUSE_POSITION
1935                      | BUTTON_ALT
1936                      | BUTTON_CTRL
1937                      | BUTTON_SHIFT
1938                      | BUTTON_PRESSED
1939                      | BUTTON_RELEASED
1940                      | BUTTON_CLICKED
1941                      | BUTTON_DOUBLE_CLICKED
1942                      | BUTTON_TRIPLE_CLICKED);
1943
1944                 mouse_activate(SP_PARM, (bool) (result != 0));
1945
1946                 SP_PARM->_mouse_mask = result;
1947                 SP_PARM->_mouse_mask2 = result;
1948
1949                 /*
1950                  * Make a mask corresponding to the states we will need to
1951                  * retain (temporarily) while building up the state that the
1952                  * user asked for.
1953                  */
1954                 for (b = 1; b <= MAX_BUTTONS; ++b) {
1955                     if (SP_PARM->_mouse_mask2 & MASK_TRIPLE_CLICK(b))
1956                         SP_PARM->_mouse_mask2 |= MASK_DOUBLE_CLICK(b);
1957                     if (SP_PARM->_mouse_mask2 & MASK_DOUBLE_CLICK(b))
1958                         SP_PARM->_mouse_mask2 |= MASK_CLICK(b);
1959                     if (SP_PARM->_mouse_mask2 & MASK_CLICK(b))
1960                         SP_PARM->_mouse_mask2 |= (MASK_PRESS(b) |
1961                                                   MASK_RELEASE(b));
1962                 }
1963             }
1964         }
1965     }
1966     returnMMask(result);
1967 }
1968
1969 #if NCURSES_SP_FUNCS
1970 NCURSES_EXPORT(mmask_t)
1971 mousemask(mmask_t newmask, mmask_t * oldmask)
1972 {
1973     return NCURSES_SP_NAME(mousemask) (CURRENT_SCREEN, newmask, oldmask);
1974 }
1975 #endif
1976
1977 NCURSES_EXPORT(bool)
1978 wenclose(const WINDOW *win, int y, int x)
1979 /* check to see if given window encloses given screen location */
1980 {
1981     bool result = FALSE;
1982
1983     T((T_CALLED("wenclose(%p,%d,%d)"), (const void *) win, y, x));
1984
1985     if (win != 0) {
1986         y -= win->_yoffset;
1987         result = ((win->_begy <= y &&
1988                    win->_begx <= x &&
1989                    (win->_begx + win->_maxx) >= x &&
1990                    (win->_begy + win->_maxy) >= y) ? TRUE : FALSE);
1991     }
1992     returnBool(result);
1993 }
1994
1995 NCURSES_EXPORT(int)
1996 NCURSES_SP_NAME(mouseinterval) (NCURSES_SP_DCLx int maxclick)
1997 /* set the maximum mouse interval within which to recognize a click */
1998 {
1999     int oldval;
2000
2001     T((T_CALLED("mouseinterval(%p,%d)"), (void *) SP_PARM, maxclick));
2002
2003     if (SP_PARM != 0) {
2004         oldval = SP_PARM->_maxclick;
2005         if (maxclick >= 0)
2006             SP_PARM->_maxclick = maxclick;
2007     } else {
2008         oldval = DEFAULT_MAXCLICK;
2009     }
2010
2011     returnCode(oldval);
2012 }
2013
2014 #if NCURSES_SP_FUNCS
2015 NCURSES_EXPORT(int)
2016 mouseinterval(int maxclick)
2017 {
2018     return NCURSES_SP_NAME(mouseinterval) (CURRENT_SCREEN, maxclick);
2019 }
2020 #endif
2021
2022 /* This may be used by other routines to ask for the existence of mouse
2023    support */
2024 NCURSES_EXPORT(bool)
2025 _nc_has_mouse(SCREEN *sp)
2026 {
2027     return (((0 == sp) || (sp->_mouse_type == M_NONE)) ? FALSE : TRUE);
2028 }
2029
2030 NCURSES_EXPORT(bool)
2031 NCURSES_SP_NAME(has_mouse) (NCURSES_SP_DCL0)
2032 {
2033     return _nc_has_mouse(SP_PARM);
2034 }
2035
2036 #if NCURSES_SP_FUNCS
2037 NCURSES_EXPORT(bool)
2038 has_mouse(void)
2039 {
2040     return _nc_has_mouse(CURRENT_SCREEN);
2041 }
2042 #endif
2043
2044 NCURSES_EXPORT(bool)
2045 wmouse_trafo(const WINDOW *win, int *pY, int *pX, bool to_screen)
2046 {
2047     bool result = FALSE;
2048
2049     T((T_CALLED("wmouse_trafo(%p,%p,%p,%d)"),
2050        (const void *) win,
2051        (void *) pY,
2052        (void *) pX,
2053        to_screen));
2054
2055     if (win && pY && pX) {
2056         int y = *pY;
2057         int x = *pX;
2058
2059         if (to_screen) {
2060             y += win->_begy + win->_yoffset;
2061             x += win->_begx;
2062             if (wenclose(win, y, x))
2063                 result = TRUE;
2064         } else {
2065             if (wenclose(win, y, x)) {
2066                 y -= (win->_begy + win->_yoffset);
2067                 x -= win->_begx;
2068                 result = TRUE;
2069             }
2070         }
2071         if (result) {
2072             *pX = x;
2073             *pY = y;
2074         }
2075     }
2076     returnBool(result);
2077 }