]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/base/lib_mouse.c
ncurses 6.2 - patch 20200523
[ncurses.git] / ncurses / base / lib_mouse.c
1 /****************************************************************************
2  * Copyright 2018-2019,2020 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.188 2020/05/23 23:35:35 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         case 1006:
423             break;
424         default:
425             code = 1000;
426             break;
427         }
428         sp->_mouse_xtermcap = "\033[?1000%?%p1%{1}%=%th%el%;";
429     }
430 }
431 #endif
432
433 static void
434 enable_xterm_mouse(SCREEN *sp, int enable)
435 {
436 #if USE_EMX_MOUSE
437     sp->_emxmouse_activated = enable;
438 #else
439     NCURSES_PUTP2("xterm-mouse", TPARM_1(sp->_mouse_xtermcap, enable));
440 #endif
441     sp->_mouse_active = enable;
442 }
443
444 #if USE_GPM_SUPPORT
445 static bool
446 allow_gpm_mouse(SCREEN *sp GCC_UNUSED)
447 {
448     bool result = FALSE;
449
450 #if USE_WEAK_SYMBOLS
451     /* Danger Robinson: do not use dlopen for libgpm if already loaded */
452     if ((Gpm_Wgetch) != 0) {
453         if (!sp->_mouse_gpm_loaded) {
454             T(("GPM library was already dlopen'd, not by us"));
455         }
456     } else
457 #endif
458         /* GPM does printf's without checking if stdout is a terminal */
459     if (NC_ISATTY(fileno(stdout))) {
460         const char *list = getenv("NCURSES_GPM_TERMS");
461         const char *env = getenv("TERM");
462         if (list != 0) {
463             if (env != 0) {
464                 result = _nc_name_match(list, env, "|:");
465             }
466         } else {
467             /* GPM checks the beginning of the $TERM variable to decide if it
468              * should pass xterm events through.  There is no real advantage in
469              * allowing GPM to do this.  Recent versions relax that check, and
470              * pretend that GPM can work with any terminal having the kmous
471              * capability.  Perhaps that works for someone.  If so, they can
472              * set the environment variable (above).
473              */
474             if (env != 0 && strstr(env, "linux") != 0) {
475                 result = TRUE;
476             }
477         }
478     }
479     return result;
480 }
481
482 #ifdef HAVE_LIBDL
483 static void
484 unload_gpm_library(SCREEN *sp)
485 {
486     if (sp->_dlopen_gpm != 0) {
487         T(("unload GPM library"));
488         sp->_mouse_gpm_loaded = FALSE;
489         sp->_mouse_fd = -1;
490         dlclose(sp->_dlopen_gpm);
491         sp->_dlopen_gpm = 0;
492     }
493 }
494
495 static void
496 load_gpm_library(SCREEN *sp)
497 {
498     sp->_mouse_gpm_found = FALSE;
499     if ((sp->_dlopen_gpm = dlopen(LIBGPM_SONAME, my_RTLD)) != 0) {
500 #if (defined(__GNUC__) && (__GNUC__ >= 5)) || defined(__clang__)
501 #pragma GCC diagnostic push
502 #pragma GCC diagnostic ignored "-Wpedantic"
503 #endif
504         if (GET_DLSYM(gpm_fd) == 0 ||
505             GET_DLSYM(Gpm_Open) == 0 ||
506             GET_DLSYM(Gpm_Close) == 0 ||
507             GET_DLSYM(Gpm_GetEvent) == 0) {
508 #if (defined(__GNUC__) && (__GNUC__ >= 5)) || defined(__clang__)
509 #pragma GCC diagnostic pop
510 #endif
511             T(("GPM initialization failed: %s", dlerror()));
512             unload_gpm_library(sp);
513         } else {
514             sp->_mouse_gpm_found = TRUE;
515             sp->_mouse_gpm_loaded = TRUE;
516         }
517     }
518 }
519 #endif
520
521 static bool
522 enable_gpm_mouse(SCREEN *sp, bool enable)
523 {
524     bool result;
525
526     T((T_CALLED("enable_gpm_mouse(%d)"), enable));
527
528     if (enable && !sp->_mouse_active) {
529 #ifdef HAVE_LIBDL
530         if (sp->_mouse_gpm_found && !sp->_mouse_gpm_loaded) {
531             load_gpm_library(sp);
532         }
533 #endif
534         if (sp->_mouse_gpm_loaded) {
535             int code;
536
537             /* GPM: initialize connection to gpm server */
538             sp->_mouse_gpm_connect.eventMask = GPM_DOWN | GPM_UP;
539             sp->_mouse_gpm_connect.defaultMask =
540                 (unsigned short) (~(sp->_mouse_gpm_connect.eventMask | GPM_HARD));
541             sp->_mouse_gpm_connect.minMod = 0;
542             sp->_mouse_gpm_connect.maxMod =
543                 (unsigned short) (~((1 << KG_SHIFT) |
544                                     (1 << KG_SHIFTL) |
545                                     (1 << KG_SHIFTR)));
546             /*
547              * Note: GPM hardcodes \E[?1001s and \E[?1000h during its open.
548              * The former is recognized by wscons (SunOS), and the latter by
549              * xterm.  Those will not show up in ncurses' traces.
550              */
551             code = my_Gpm_Open(&sp->_mouse_gpm_connect, 0);
552             result = (code >= 0);
553
554             /*
555              * GPM can return a -2 if it is trying to do something with xterm.
556              * Ignore that, since it conflicts with our use of stdin.
557              */
558             if (code == -2) {
559                 my_Gpm_Close();
560             }
561         } else {
562             result = FALSE;
563         }
564         sp->_mouse_active = result;
565         T(("GPM open %s", result ? "succeeded" : "failed"));
566     } else {
567         if (!enable && sp->_mouse_active) {
568             /* GPM: close connection to gpm server */
569             my_Gpm_Close();
570             sp->_mouse_active = FALSE;
571             T(("GPM closed"));
572         }
573         result = enable;
574     }
575 #ifdef HAVE_LIBDL
576     if (!result) {
577         unload_gpm_library(sp);
578     }
579 #endif
580     returnBool(result);
581 }
582 #endif /* USE_GPM_SUPPORT */
583
584 static void
585 initialize_mousetype(SCREEN *sp)
586 {
587     T((T_CALLED("initialize_mousetype()")));
588
589     /* Try gpm first, because gpm may be configured to run in xterm */
590 #if USE_GPM_SUPPORT
591     if (allow_gpm_mouse(sp)) {
592         if (!sp->_mouse_gpm_loaded) {
593 #ifdef HAVE_LIBDL
594             load_gpm_library(sp);
595 #else /* !HAVE_LIBDL */
596             sp->_mouse_gpm_found = TRUE;
597             sp->_mouse_gpm_loaded = TRUE;
598 #endif
599         }
600
601         /*
602          * The gpm_fd file-descriptor may be negative (xterm).  So we have to
603          * maintain our notion of whether the mouse connection is active
604          * without testing the file-descriptor.
605          */
606         if (sp->_mouse_gpm_found && enable_gpm_mouse(sp, TRUE)) {
607             sp->_mouse_type = M_GPM;
608             sp->_mouse_fd = *(my_gpm_fd);
609             T(("GPM mouse_fd %d", sp->_mouse_fd));
610             returnVoid;
611         }
612     }
613 #endif /* USE_GPM_SUPPORT */
614
615     /* OS/2 VIO */
616 #if USE_EMX_MOUSE
617     if (!sp->_emxmouse_thread
618         && strstr(SP_TERMTYPE term_names, "xterm") == 0
619         && NonEmpty(key_mouse)) {
620         int handles[2];
621
622         if (pipe(handles) < 0) {
623             perror("mouse pipe error");
624             returnVoid;
625         } else {
626             int rc;
627
628             if (!sp->_emxmouse_buttons[0]) {
629                 const char *s = getenv("MOUSE_BUTTONS_123");
630
631                 sp->_emxmouse_buttons[0] = 1;
632                 if (s && strlen(s) >= 3) {
633                     sp->_emxmouse_buttons[1] = s[0] - '0';
634                     sp->_emxmouse_buttons[2] = s[1] - '0';
635                     sp->_emxmouse_buttons[3] = s[2] - '0';
636                 } else {
637                     sp->_emxmouse_buttons[1] = 1;
638                     sp->_emxmouse_buttons[2] = 3;
639                     sp->_emxmouse_buttons[3] = 2;
640                 }
641             }
642             sp->_emxmouse_wfd = handles[1];
643             M_FD(sp) = handles[0];
644             /* Needed? */
645             setmode(handles[0], O_BINARY);
646             setmode(handles[1], O_BINARY);
647             /* Do not use CRT functions, we may single-threaded. */
648             rc = DosCreateThread((unsigned long *) &sp->_emxmouse_thread,
649                                  mouse_server, (long) sp, 0, 8192);
650             if (rc) {
651                 printf("mouse thread error %d=%#x", rc, rc);
652             } else {
653                 sp->_mouse_type = M_XTERM;
654             }
655             returnVoid;
656         }
657     }
658 #endif /* USE_EMX_MOUSE */
659
660 #if USE_SYSMOUSE
661     {
662         static char dev_tty[] = "/dev/tty";
663         struct mouse_info the_mouse;
664         char *the_device = 0;
665
666         if (NC_ISATTY(sp->_ifd))
667             the_device = ttyname(sp->_ifd);
668         if (the_device == 0)
669             the_device = dev_tty;
670
671         sp->_mouse_fd = open(the_device, O_RDWR);
672
673         if (sp->_mouse_fd >= 0) {
674             /*
675              * sysmouse does not have a usable user interface for obtaining
676              * mouse events.  The logical way to proceed (reading data on a
677              * stream) only works if one opens the device as root.  Even in
678              * that mode, careful examination shows we lose events
679              * occasionally.  The interface provided for user programs is to
680              * establish a signal handler.  really.
681              *
682              * Take over SIGUSR2 for this purpose since SIGUSR1 is more
683              * likely to be used by an application.  getch() will have to
684              * handle the misleading EINTR's.
685              */
686             signal(SIGUSR2, SIG_IGN);
687             the_mouse.operation = MOUSE_MODE;
688             the_mouse.u.mode.mode = 0;
689             the_mouse.u.mode.signal = SIGUSR2;
690             if (ioctl(sp->_mouse_fd, CONS_MOUSECTL, &the_mouse) != -1) {
691                 signal(SIGUSR2, handle_sysmouse);
692                 the_mouse.operation = MOUSE_SHOW;
693                 ioctl(sp->_mouse_fd, CONS_MOUSECTL, &the_mouse);
694
695 #if defined(FBIO_MODEINFO) || defined(CONS_MODEINFO)    /* FreeBSD > 2.x */
696                 {
697 #ifndef FBIO_GETMODE            /* FreeBSD 3.x */
698 #define FBIO_GETMODE    CONS_GET
699 #define FBIO_MODEINFO   CONS_MODEINFO
700 #endif /* FBIO_GETMODE */
701                     video_info_t the_video;
702
703                     if (ioctl(sp->_mouse_fd,
704                               FBIO_GETMODE,
705                               &the_video.vi_mode) != -1
706                         && ioctl(sp->_mouse_fd,
707                                  FBIO_MODEINFO,
708                                  &the_video) != -1) {
709                         sp->_sysmouse_char_width = the_video.vi_cwidth;
710                         sp->_sysmouse_char_height = the_video.vi_cheight;
711                     }
712                 }
713 #endif /* defined(FBIO_MODEINFO) || defined(CONS_MODEINFO) */
714
715                 if (sp->_sysmouse_char_width <= 0)
716                     sp->_sysmouse_char_width = 8;
717                 if (sp->_sysmouse_char_height <= 0)
718                     sp->_sysmouse_char_height = 16;
719                 sp->_mouse_type = M_SYSMOUSE;
720                 returnVoid;
721             }
722         }
723     }
724 #endif /* USE_SYSMOUSE */
725
726 #ifdef USE_TERM_DRIVER
727     CallDriver(sp, td_initmouse);
728 #else
729     /* we know how to recognize mouse events under "xterm" */
730     if (NonEmpty(key_mouse)) {
731         init_xterm_mouse(sp);
732     } else if (strstr(SP_TERMTYPE term_names, "xterm") != 0) {
733         if (_nc_add_to_try(&(sp->_keytry), xterm_kmous, KEY_MOUSE) == OK)
734             init_xterm_mouse(sp);
735     }
736 #endif
737
738     returnVoid;
739 }
740
741 static bool
742 _nc_mouse_init(SCREEN *sp)
743 /* initialize the mouse */
744 {
745     bool result = FALSE;
746
747     if (sp != 0) {
748         if (!sp->_mouse_initialized) {
749             int i;
750
751             sp->_mouse_initialized = TRUE;
752
753             TR(MY_TRACE, ("_nc_mouse_init() called"));
754
755             sp->_mouse_eventp = FirstEV(sp);
756             for (i = 0; i < EV_MAX; i++)
757                 Invalidate(sp->_mouse_events + i);
758
759             initialize_mousetype(sp);
760
761             T(("_nc_mouse_init() set mousetype to %d", sp->_mouse_type));
762         }
763         result = sp->_mouse_initialized;
764     }
765     return result;
766 }
767
768 /*
769  * Query to see if there is a pending mouse event.  This is called from
770  * fifo_push() in lib_getch.c
771  */
772 static bool
773 _nc_mouse_event(SCREEN *sp)
774 {
775     MEVENT *eventp = sp->_mouse_eventp;
776     bool result = FALSE;
777
778     (void) eventp;
779
780     switch (sp->_mouse_type) {
781     case M_XTERM:
782         /* xterm: never have to query, mouse events are in the keyboard stream */
783 #if USE_EMX_MOUSE
784         {
785             char kbuf[3];
786
787             int i, res = read(M_FD(sp), &kbuf, 3);      /* Eat the prefix */
788             if (res != 3)
789                 printf("Got %d chars instead of 3 for prefix.\n", res);
790             for (i = 0; i < res; i++) {
791                 if (kbuf[i] != key_mouse[i])
792                     printf("Got char %d instead of %d for prefix.\n",
793                            (int) kbuf[i], (int) key_mouse[i]);
794             }
795             result = TRUE;
796         }
797 #endif /* USE_EMX_MOUSE */
798         break;
799
800 #if USE_GPM_SUPPORT
801     case M_GPM:
802         if (sp->_mouse_fd >= 0) {
803             /* query server for event, return TRUE if we find one */
804             Gpm_Event ev;
805
806             switch (my_Gpm_GetEvent(&ev)) {
807             case 0:
808                 /* Connection closed, drop the mouse. */
809                 sp->_mouse_fd = -1;
810                 break;
811             case 1:
812                 /* there's only one mouse... */
813                 eventp->id = NORMAL_EVENT;
814
815                 eventp->bstate = 0;
816                 switch (ev.type & 0x0f) {
817                 case (GPM_DOWN):
818                     if (ev.buttons & GPM_B_LEFT)
819                         eventp->bstate |= BUTTON1_PRESSED;
820                     if (ev.buttons & GPM_B_MIDDLE)
821                         eventp->bstate |= BUTTON2_PRESSED;
822                     if (ev.buttons & GPM_B_RIGHT)
823                         eventp->bstate |= BUTTON3_PRESSED;
824                     break;
825                 case (GPM_UP):
826                     if (ev.buttons & GPM_B_LEFT)
827                         eventp->bstate |= BUTTON1_RELEASED;
828                     if (ev.buttons & GPM_B_MIDDLE)
829                         eventp->bstate |= BUTTON2_RELEASED;
830                     if (ev.buttons & GPM_B_RIGHT)
831                         eventp->bstate |= BUTTON3_RELEASED;
832                     break;
833                 default:
834                     eventp->bstate |= REPORT_MOUSE_POSITION;
835                     break;
836                 }
837
838                 eventp->x = ev.x - 1;
839                 eventp->y = ev.y - 1;
840                 eventp->z = 0;
841
842                 /* bump the next-free pointer into the circular list */
843                 sp->_mouse_eventp = NEXT(eventp);
844                 result = TRUE;
845                 break;
846             }
847         }
848         break;
849 #endif
850
851 #if USE_SYSMOUSE
852     case M_SYSMOUSE:
853         if (sp->_sysmouse_head < sp->_sysmouse_tail) {
854             *eventp = sp->_sysmouse_fifo[sp->_sysmouse_head];
855
856             /*
857              * Point the fifo-head to the next possible location.  If there
858              * are none, reset the indices.  This may be interrupted by the
859              * signal handler, doing essentially the same reset.
860              */
861             sp->_sysmouse_head += 1;
862             if (sp->_sysmouse_head == sp->_sysmouse_tail) {
863                 sp->_sysmouse_tail = 0;
864                 sp->_sysmouse_head = 0;
865             }
866
867             /* bump the next-free pointer into the circular list */
868             sp->_mouse_eventp = eventp = NEXT(eventp);
869             result = TRUE;
870         }
871         break;
872 #endif /* USE_SYSMOUSE */
873
874 #ifdef USE_TERM_DRIVER
875     case M_TERM_DRIVER:
876         while (sp->_drv_mouse_head < sp->_drv_mouse_tail) {
877             *eventp = sp->_drv_mouse_fifo[sp->_drv_mouse_head];
878
879             /*
880              * Point the fifo-head to the next possible location.  If there
881              * are none, reset the indices.
882              */
883             sp->_drv_mouse_head += 1;
884             if (sp->_drv_mouse_head == sp->_drv_mouse_tail) {
885                 sp->_drv_mouse_tail = 0;
886                 sp->_drv_mouse_head = 0;
887             }
888
889             /* bump the next-free pointer into the circular list */
890             sp->_mouse_eventp = eventp = NEXT(eventp);
891             result = TRUE;
892         }
893         break;
894 #endif
895
896     case M_NONE:
897         break;
898     }
899
900     return result;              /* true if we found an event */
901 }
902
903 #if USE_EMX_MOUSE
904 #define PRESS_POSITION(n) \
905     do { \
906             eventp->bstate = MASK_PRESS(n); \
907             sp->_mouse_bstate |= MASK_PRESS(n); \
908             if (button & 0x40) { \
909                     eventp->bstate = MASK_RELEASE(n); \
910                     sp->_mouse_bstate &= ~MASK_PRESS(n); \
911             } \
912     } while (0)
913 #else
914 #define PRESS_POSITION(n) \
915     do { \
916             eventp->bstate = (mmask_t) ((sp->_mouse_bstate & MASK_PRESS(n)) \
917                                     ? REPORT_MOUSE_POSITION \
918                                     : MASK_PRESS(n)); \
919             sp->_mouse_bstate |= MASK_PRESS(n); \
920     } while (0)
921 #endif
922
923 static bool
924 handle_wheel(SCREEN *sp, MEVENT * eventp, int button, int wheel)
925 {
926     bool result = TRUE;
927
928     switch (button & 3) {
929     case 0:
930         if (wheel) {
931             eventp->bstate = MASK_PRESS(4);
932             /* Do not record in sp->_mouse_bstate; there will be no
933              * corresponding release event.
934              */
935         } else {
936             PRESS_POSITION(1);
937         }
938         break;
939     case 1:
940         if (wheel) {
941 #if NCURSES_MOUSE_VERSION >= 2
942             eventp->bstate = MASK_PRESS(5);
943             /* See comment above for button 4 */
944 #else
945             /* Ignore this event as it is not a true press of the button */
946             eventp->bstate = REPORT_MOUSE_POSITION;
947 #endif
948         } else {
949             PRESS_POSITION(2);
950         }
951         break;
952     case 2:
953         PRESS_POSITION(3);
954         break;
955     default:
956         result = FALSE;
957         break;
958     }
959     return result;
960 }
961
962 static bool
963 decode_X10_bstate(SCREEN *sp, MEVENT * eventp, unsigned intro)
964 {
965     bool result;
966     int button = 0;
967     int wheel = (intro & 96) == 96;
968
969     eventp->bstate = 0;
970
971     if (intro >= 96) {
972         if (intro >= 160) {
973             button = (int) (intro - 152);       /* buttons 8-11 */
974         } else if (intro >= 96) {
975             button = (int) (intro - 92);        /* buttons 4-7 */
976         }
977     } else {
978         button = (intro & 3);
979     }
980
981     if (button > MAX_BUTTONS) {
982         eventp->bstate = REPORT_MOUSE_POSITION;
983     } else if (!handle_wheel(sp, eventp, (int) intro, wheel)) {
984
985         /*
986          * Release events aren't reported for individual buttons, just for
987          * the button set as a whole.  However, because there are normally
988          * no mouse events under xterm that intervene between press and
989          * release, we can infer the button actually released by looking at
990          * the previous event.
991          */
992         if (sp->_mouse_bstate & BUTTON_PRESSED) {
993             int b;
994
995             eventp->bstate = BUTTON_RELEASED;
996             for (b = 1; b <= MAX_BUTTONS; ++b) {
997                 if (!(sp->_mouse_bstate & MASK_PRESS(b)))
998                     eventp->bstate &= ~MASK_RELEASE(b);
999             }
1000             sp->_mouse_bstate = 0;
1001         } else {
1002             /*
1003              * xterm will return a stream of release-events to let the
1004              * application know where the mouse is going, if private mode
1005              * 1002 or 1003 is enabled.
1006              */
1007             eventp->bstate = REPORT_MOUSE_POSITION;
1008         }
1009     }
1010
1011     if (intro & 4) {
1012         eventp->bstate |= BUTTON_SHIFT;
1013     }
1014     if (intro & 8) {
1015         eventp->bstate |= BUTTON_ALT;
1016     }
1017     if (intro & 16) {
1018         eventp->bstate |= BUTTON_CTRL;
1019     }
1020     result = (eventp->bstate & REPORT_MOUSE_POSITION) ? TRUE : FALSE;
1021     return result;
1022 }
1023
1024 /* This code requires that your xterm entry contain the kmous capability and
1025  * that it be set to the \E[M documented in the Xterm Control Sequences
1026  * reference.  This is how we arrange for mouse events to be reported via a
1027  * KEY_MOUSE return value from wgetch().  After this value is received,
1028  * _nc_mouse_inline() gets called and is immediately responsible for parsing
1029  * the mouse status information following the prefix.
1030  *
1031  * The following quotes from the ctlseqs.ms document in the XTerm distribution,
1032  * describing the mouse tracking feature:
1033  *
1034  * Parameters for all mouse tracking escape sequences generated by xterm encode
1035  * numeric parameters in a single character as value+040.  For example, ! is
1036  * 1.
1037  *
1038  * On button press or release, xterm sends ESC [ M CbCxCy.  The low two bits of
1039  * Cb encode button information:  0=MB1 pressed, 1=MB2 pressed, 2=MB3 pressed,
1040  * 3=release.  The upper bits encode what modifiers were down when the button
1041  * was pressed and are added together.  4=Shift, 8=Meta, 16=Control.  Cx and Cy
1042  * are the x and y coordinates of the mouse event.  The upper left corner is
1043  * (1,1).
1044  *
1045  * (End quote) By the time we get here, we've eaten the key prefix.  FYI, the
1046  * loop below is necessary because mouse click info isn't guaranteed to present
1047  * as a single clist item.
1048  *
1049  * Wheel mice may return buttons 4 and 5 when the wheel is turned.  We encode
1050  * those as button presses.
1051  */
1052 static bool
1053 decode_xterm_X10(SCREEN *sp, MEVENT * eventp)
1054 {
1055 #define MAX_KBUF 3
1056     unsigned char kbuf[MAX_KBUF + 1];
1057     size_t grabbed;
1058     int res;
1059     bool result;
1060
1061 # if USE_PTHREADS_EINTR
1062 #  if USE_WEAK_SYMBOLS
1063     if ((pthread_self) && (pthread_kill) && (pthread_equal))
1064 #  endif
1065         _nc_globals.read_thread = pthread_self();
1066 # endif
1067     for (grabbed = 0; grabbed < MAX_KBUF; grabbed += (size_t) res) {
1068
1069         /* For VIO mouse we add extra bit 64 to disambiguate button-up. */
1070         res = (int) read(
1071 #if USE_EMX_MOUSE
1072                             (M_FD(sp) >= 0) ? M_FD(sp) : sp->_ifd,
1073 #else
1074                             sp->_ifd,
1075 #endif
1076                             kbuf + grabbed, (size_t) (MAX_KBUF - (int) grabbed));
1077         if (res == -1)
1078             break;
1079     }
1080 #if USE_PTHREADS_EINTR
1081     _nc_globals.read_thread = 0;
1082 #endif
1083     kbuf[MAX_KBUF] = '\0';
1084
1085     TR(TRACE_IEVENT,
1086        ("_nc_mouse_inline sees the following xterm data: '%s'", kbuf));
1087
1088     /* there's only one mouse... */
1089     eventp->id = NORMAL_EVENT;
1090
1091     result = decode_X10_bstate(sp, eventp, kbuf[0]);
1092
1093     eventp->x = (kbuf[1] - ' ') - 1;
1094     eventp->y = (kbuf[2] - ' ') - 1;
1095
1096     return result;
1097 }
1098
1099 #ifdef EXP_XTERM_1005
1100 /*
1101  * This is identical to X10/X11 responses except that there are two UTF-8
1102  * characters storing the ordinates instead of two bytes.
1103  */
1104 static bool
1105 decode_xterm_1005(SCREEN *sp, MEVENT * eventp)
1106 {
1107     char kbuf[80];
1108     size_t grabbed;
1109     size_t limit = (sizeof(kbuf) - 1);
1110     unsigned coords[2];
1111     bool result;
1112
1113     coords[0] = 0;
1114     coords[1] = 0;
1115
1116 # if USE_PTHREADS_EINTR
1117 #  if USE_WEAK_SYMBOLS
1118     if ((pthread_self) && (pthread_kill) && (pthread_equal))
1119 #  endif
1120         _nc_globals.read_thread = pthread_self();
1121 # endif
1122     for (grabbed = 0; grabbed < limit;) {
1123         int res;
1124
1125         res = (int) read(
1126 #if USE_EMX_MOUSE
1127                             (M_FD(sp) >= 0) ? M_FD(sp) : sp->_ifd,
1128 #else
1129                             sp->_ifd,
1130 #endif
1131                             (kbuf + grabbed), (size_t) 1);
1132         if (res == -1)
1133             break;
1134         grabbed += (size_t) res;
1135         if (grabbed > 1) {
1136             size_t check = 1;
1137             int n;
1138
1139             for (n = 0; n < 2; ++n) {
1140                 int rc;
1141
1142                 if (check >= grabbed)
1143                     break;
1144                 rc = _nc_conv_to_utf32(&coords[n], kbuf + check, (unsigned)
1145                                        (grabbed - check));
1146                 if (!rc)
1147                     break;
1148                 check += (size_t) rc;
1149             }
1150             if (n >= 2)
1151                 break;
1152         }
1153     }
1154 #if USE_PTHREADS_EINTR
1155     _nc_globals.read_thread = 0;
1156 #endif
1157
1158     TR(TRACE_IEVENT,
1159        ("_nc_mouse_inline sees the following xterm data: %s",
1160         _nc_visbufn(kbuf, (int) grabbed)));
1161
1162     /* there's only one mouse... */
1163     eventp->id = NORMAL_EVENT;
1164
1165     result = decode_X10_bstate(sp, eventp, UChar(kbuf[0]));
1166
1167     eventp->x = (int) (coords[0] - ' ') - 1;
1168     eventp->y = (int) (coords[1] - ' ') - 1;
1169
1170     return result;
1171 }
1172 #endif /* EXP_XTERM_1005 */
1173
1174 /*
1175  * ECMA-48 section 5.4
1176  */
1177 #define isInter(c) ((c) >= 0x20 && (c) <= 0x2f)
1178 #define isParam(c) ((c) >= 0x30 && (c) <= 0x3f)
1179 #define isFinal(c) ((c) >= 0x40 && (c) <= 0x7e)
1180
1181 #define MAX_PARAMS 9
1182
1183 typedef struct {
1184     int nerror;                 /* nonzero if there are unexpected chars */
1185     int nparam;                 /* number of numeric parameters */
1186     int params[MAX_PARAMS];
1187     int final;                  /* the final-character */
1188 } SGR_DATA;
1189
1190 static bool
1191 read_SGR(SCREEN *sp, SGR_DATA * result)
1192 {
1193     char kbuf[80];              /* bigger than any possible mouse response */
1194     int grabbed = 0;
1195     int ch = 0;
1196     int now = -1;
1197     int marker = 1;
1198
1199     memset(result, 0, sizeof(*result));
1200 # if USE_PTHREADS_EINTR
1201 #  if USE_WEAK_SYMBOLS
1202     if ((pthread_self) && (pthread_kill) && (pthread_equal))
1203 #  endif
1204         _nc_globals.read_thread = pthread_self();
1205 # endif
1206
1207     do {
1208         int res;
1209
1210         res = (int) read(
1211 #if USE_EMX_MOUSE
1212                             (M_FD(sp) >= 0) ? M_FD(sp) : sp->_ifd,
1213 #else
1214                             sp->_ifd,
1215 #endif
1216                             (kbuf + grabbed), (size_t) 1);
1217         if (res == -1)
1218             break;
1219         if ((grabbed + MAX_KBUF) >= (int) sizeof(kbuf)) {
1220             result->nerror++;
1221             break;
1222         }
1223         ch = UChar(kbuf[grabbed]);
1224         kbuf[grabbed + 1] = 0;
1225         switch (ch) {
1226         case '0':
1227         case '1':
1228         case '2':
1229         case '3':
1230         case '4':
1231         case '5':
1232         case '6':
1233         case '7':
1234         case '8':
1235         case '9':
1236             if (marker) {
1237                 ++now;
1238                 result->nparam = (now + 1);
1239             }
1240             marker = 0;
1241             result->params[now] = (result->params[now] * 10) + (ch - '0');
1242             break;
1243         case ';':
1244             if (marker) {
1245                 ++now;
1246                 result->nparam = (now + 1);
1247             }
1248             marker = 1;
1249             break;
1250         default:
1251             if (ch < 32 || ch > 126) {
1252                 /*
1253                  * Technically other characters could be interspersed in the
1254                  * response.  Ignore those for now.
1255                  */
1256                 result->nerror++;
1257                 continue;
1258             } else if (isFinal(ch)) {
1259                 if (marker) {
1260                     result->nparam++;
1261                 }
1262                 result->final = ch;
1263             } else {
1264                 result->nerror++;
1265             }
1266             break;
1267         }
1268         ++grabbed;
1269     } while (!isFinal(ch));
1270 #if USE_PTHREADS_EINTR
1271     _nc_globals.read_thread = 0;
1272 #endif
1273
1274     kbuf[++grabbed] = 0;
1275     TR(TRACE_IEVENT,
1276        ("_nc_mouse_inline sees the following xterm data: '%s'", kbuf));
1277     return (grabbed > 0) && (result->nerror == 0);
1278 }
1279
1280 static bool
1281 decode_xterm_SGR1006(SCREEN *sp, MEVENT * eventp)
1282 {
1283     SGR_DATA data;
1284     bool result = FALSE;
1285     if (read_SGR(sp, &data)) {
1286         int b = data.params[0];
1287         int b3 = 1 + (b & 3);
1288         int wheel = ((b & 64) == 64);
1289
1290         if (b >= 132) {
1291             b3 = MAX_BUTTONS + 1;
1292         } else if (b >= 128) {
1293             b3 = (b - 120);     /* buttons 8-11 */
1294         } else if (b >= 64) {
1295             b3 = (b - 60);      /* buttons 6-7 */
1296         }
1297
1298         eventp->id = NORMAL_EVENT;
1299         if (data.final == 'M') {
1300             (void) handle_wheel(sp, eventp, b, wheel);
1301         } else if (b3 > MAX_BUTTONS) {
1302             eventp->bstate = REPORT_MOUSE_POSITION;
1303         } else {
1304             mmask_t pressed = (mmask_t) NCURSES_MOUSE_MASK(b3, NCURSES_BUTTON_PRESSED);
1305             mmask_t release = (mmask_t) NCURSES_MOUSE_MASK(b3, NCURSES_BUTTON_RELEASED);
1306             if (sp->_mouse_bstate & pressed) {
1307                 eventp->bstate = release;
1308                 sp->_mouse_bstate &= ~pressed;
1309             } else {
1310                 eventp->bstate = REPORT_MOUSE_POSITION;
1311             }
1312         }
1313         if (b & 4) {
1314             eventp->bstate |= BUTTON_SHIFT;
1315         }
1316         if (b & 8) {
1317             eventp->bstate |= BUTTON_ALT;
1318         }
1319         if (b & 16) {
1320             eventp->bstate |= BUTTON_CTRL;
1321         }
1322         result = (eventp->bstate & REPORT_MOUSE_POSITION) ? TRUE : FALSE;
1323         eventp->x = (data.params[1] ? (data.params[1] - 1) : 0);
1324         eventp->y = (data.params[2] ? (data.params[2] - 1) : 0);
1325     }
1326     return result;
1327 }
1328
1329 static bool
1330 _nc_mouse_inline(SCREEN *sp)
1331 /* mouse report received in the keyboard stream -- parse its info */
1332 {
1333     bool result = FALSE;
1334     MEVENT *eventp = sp->_mouse_eventp;
1335
1336     TR(MY_TRACE, ("_nc_mouse_inline() called"));
1337
1338     if (sp->_mouse_type == M_XTERM) {
1339         switch (sp->_mouse_format) {
1340         case MF_X10:
1341             result = decode_xterm_X10(sp, eventp);
1342             break;
1343         case MF_SGR1006:
1344             result = decode_xterm_SGR1006(sp, eventp);
1345             break;
1346 #ifdef EXP_XTERM_1005
1347         case MF_XTERM_1005:
1348             result = decode_xterm_1005(sp, eventp);
1349             break;
1350 #endif
1351         }
1352
1353         TR(MY_TRACE,
1354            ("_nc_mouse_inline: primitive mouse-event %s has slot %ld",
1355             _nc_tracemouse(sp, eventp),
1356             (long) IndexEV(sp, eventp)));
1357
1358         /* bump the next-free pointer into the circular list */
1359         sp->_mouse_eventp = NEXT(eventp);
1360
1361         if (!result) {
1362             /* If this event is from a wheel-mouse, treat it like position
1363              * reports and avoid waiting for the release-events which will
1364              * never come.
1365              */
1366             if (eventp->bstate & BUTTON_PRESSED) {
1367                 int b;
1368
1369                 for (b = 4; b <= MAX_BUTTONS; ++b) {
1370                     if ((eventp->bstate & MASK_PRESS(b))) {
1371                         result = TRUE;
1372                         break;
1373                     }
1374                 }
1375             }
1376         }
1377     }
1378
1379     return (result);
1380 }
1381
1382 static void
1383 mouse_activate(SCREEN *sp, int on)
1384 {
1385     if (!on && !sp->_mouse_initialized)
1386         return;
1387
1388     if (!_nc_mouse_init(sp))
1389         return;
1390
1391     if (on) {
1392         sp->_mouse_bstate = 0;
1393         switch (sp->_mouse_type) {
1394         case M_XTERM:
1395 #if NCURSES_EXT_FUNCS
1396             NCURSES_SP_NAME(keyok) (NCURSES_SP_ARGx KEY_MOUSE, on);
1397 #endif
1398             TPUTS_TRACE("xterm mouse initialization");
1399             enable_xterm_mouse(sp, 1);
1400             break;
1401 #if USE_GPM_SUPPORT
1402         case M_GPM:
1403             if (enable_gpm_mouse(sp, TRUE)) {
1404                 sp->_mouse_fd = *(my_gpm_fd);
1405                 T(("GPM mouse_fd %d", sp->_mouse_fd));
1406             }
1407             break;
1408 #endif
1409 #if USE_SYSMOUSE
1410         case M_SYSMOUSE:
1411             signal(SIGUSR2, handle_sysmouse);
1412             sp->_mouse_active = TRUE;
1413             break;
1414 #endif
1415 #ifdef USE_TERM_DRIVER
1416         case M_TERM_DRIVER:
1417             sp->_mouse_active = TRUE;
1418             break;
1419 #endif
1420         case M_NONE:
1421             return;
1422         }
1423         /* Make runtime binding to cut down on object size of applications that
1424          * do not use the mouse (e.g., 'clear').
1425          */
1426         sp->_mouse_event = _nc_mouse_event;
1427         sp->_mouse_inline = _nc_mouse_inline;
1428         sp->_mouse_parse = _nc_mouse_parse;
1429         sp->_mouse_resume = _nc_mouse_resume;
1430         sp->_mouse_wrap = _nc_mouse_wrap;
1431     } else {
1432
1433         switch (sp->_mouse_type) {
1434         case M_XTERM:
1435             TPUTS_TRACE("xterm mouse deinitialization");
1436             enable_xterm_mouse(sp, 0);
1437             break;
1438 #if USE_GPM_SUPPORT
1439         case M_GPM:
1440             enable_gpm_mouse(sp, FALSE);
1441             break;
1442 #endif
1443 #if USE_SYSMOUSE
1444         case M_SYSMOUSE:
1445             signal(SIGUSR2, SIG_IGN);
1446             sp->_mouse_active = FALSE;
1447             break;
1448 #endif
1449 #ifdef USE_TERM_DRIVER
1450         case M_TERM_DRIVER:
1451             sp->_mouse_active = FALSE;
1452             break;
1453 #endif
1454         case M_NONE:
1455             return;
1456         }
1457     }
1458     NCURSES_SP_NAME(_nc_flush) (NCURSES_SP_ARG);
1459 }
1460
1461 /**************************************************************************
1462  *
1463  * Device-independent code
1464  *
1465  **************************************************************************/
1466
1467 static bool
1468 _nc_mouse_parse(SCREEN *sp, int runcount)
1469 /* parse a run of atomic mouse events into a gesture */
1470 {
1471     MEVENT *eventp = sp->_mouse_eventp;
1472     MEVENT *next, *ep;
1473     MEVENT *first_valid = NULL;
1474     MEVENT *first_invalid = NULL;
1475     int n;
1476     int b;
1477     bool merge;
1478     bool endLoop;
1479
1480     TR(MY_TRACE, ("_nc_mouse_parse(%d) called", runcount));
1481
1482     /*
1483      * When we enter this routine, the event list next-free pointer
1484      * points just past a run of mouse events that we know were separated
1485      * in time by less than the critical click interval. The job of this
1486      * routine is to collapse this run into a single higher-level event
1487      * or gesture.
1488      *
1489      * We accomplish this in two passes.  The first pass merges press/release
1490      * pairs into click events.  The second merges runs of click events into
1491      * double or triple-click events.
1492      *
1493      * It's possible that the run may not resolve to a single event (for
1494      * example, if the user quadruple-clicks).  If so, leading events
1495      * in the run are ignored if user does not call getmouse in a loop (getting
1496      * them from newest to older).
1497      *
1498      * Note that this routine is independent of the format of the specific
1499      * format of the pointing-device's reports.  We can use it to parse
1500      * gestures on anything that reports press/release events on a per-
1501      * button basis, as long as the device-dependent mouse code puts stuff
1502      * on the queue in MEVENT format.
1503      */
1504
1505     /*
1506      * Reset all events that were not set, in case the user sometimes calls
1507      * getmouse only once and other times until there are no more events in
1508      * queue.
1509      *
1510      * This also allows reaching the beginning of the run.
1511      */
1512     ep = eventp;
1513     for (n = runcount; n < EV_MAX; n++) {
1514         Invalidate(ep);
1515         ep = NEXT(ep);
1516     }
1517
1518 #ifdef TRACE
1519     if (USE_TRACEF(TRACE_IEVENT)) {
1520         _trace_slot(sp, "before mouse press/release merge:");
1521         _tracef("_nc_mouse_parse: run starts at %ld, ends at %ld, count %d",
1522                 RunParams(sp, eventp, ep),
1523                 runcount);
1524         _nc_unlock_global(tracef);
1525     }
1526 #endif /* TRACE */
1527
1528     /* first pass; merge press/release pairs */
1529     endLoop = FALSE;
1530     while (!endLoop) {
1531         next = NEXT(ep);
1532         if (next == eventp) {
1533             /* Will end the loop, but compact before */
1534             endLoop = TRUE;
1535         } else {
1536
1537 #define MASK_CHANGED(x) (!(ep->bstate & MASK_PRESS(x)) \
1538                       == !(next->bstate & MASK_RELEASE(x)))
1539
1540             if (ValidEvent(ep) && ValidEvent(next)
1541                 && ep->x == next->x && ep->y == next->y
1542                 && (ep->bstate & BUTTON_PRESSED)
1543                 && (!(next->bstate & BUTTON_PRESSED))) {
1544                 bool changed = TRUE;
1545
1546                 for (b = 1; b <= MAX_BUTTONS; ++b) {
1547                     if (!MASK_CHANGED(b)) {
1548                         changed = FALSE;
1549                         break;
1550                     }
1551                 }
1552
1553                 if (changed) {
1554                     merge = FALSE;
1555                     for (b = 1; b <= MAX_BUTTONS; ++b) {
1556                         if ((sp->_mouse_mask & MASK_CLICK(b))
1557                             && (ep->bstate & MASK_PRESS(b))) {
1558                             next->bstate &= ~MASK_RELEASE(b);
1559                             next->bstate |= MASK_CLICK(b);
1560                             merge = TRUE;
1561                         }
1562                     }
1563                     if (merge) {
1564                         Invalidate(ep);
1565                     }
1566                 }
1567             }
1568         }
1569
1570         /* Compact valid events */
1571         if (!ValidEvent(ep)) {
1572             if ((first_valid != NULL) && (first_invalid == NULL)) {
1573                 first_invalid = ep;
1574             }
1575         } else {
1576             if (first_valid == NULL) {
1577                 first_valid = ep;
1578             } else if (first_invalid != NULL) {
1579                 *first_invalid = *ep;
1580                 Invalidate(ep);
1581                 first_invalid = NEXT(first_invalid);
1582             }
1583         }
1584
1585         ep = next;
1586     }
1587
1588     if (first_invalid != NULL) {
1589         eventp = first_invalid;
1590     }
1591 #ifdef TRACE
1592     if (USE_TRACEF(TRACE_IEVENT)) {
1593         _trace_slot(sp, "before mouse click merge:");
1594         if (first_valid == NULL) {
1595             _tracef("_nc_mouse_parse: no valid event");
1596         } else {
1597             _tracef("_nc_mouse_parse: run starts at %ld, ends at %ld, count %d",
1598                     RunParams(sp, eventp, first_valid),
1599                     runcount);
1600             _nc_unlock_global(tracef);
1601         }
1602     }
1603 #endif /* TRACE */
1604
1605     /*
1606      * Second pass; merge click runs.  We merge click events forward in the
1607      * queue.  For example, double click can be changed to triple click.
1608      *
1609      * NOTE: There is a problem with this design!  If the application
1610      * allows enough click events to pile up in the circular queue so
1611      * they wrap around, it will cheerfully merge the newest forward
1612      * into the oldest, creating a bogus doubleclick and confusing
1613      * the queue-traversal logic rather badly.  Generally this won't
1614      * happen, because calling getmouse() marks old events invalid and
1615      * ineligible for merges.  The true solution to this problem would
1616      * be to timestamp each MEVENT and perform the obvious sanity check,
1617      * but the timer element would have to have sub-second resolution,
1618      * which would get us into portability trouble.
1619      */
1620     first_invalid = NULL;
1621     endLoop = (first_valid == NULL);
1622     ep = first_valid;
1623     while (!endLoop) {
1624         next = NEXT(ep);
1625
1626         if (next == eventp) {
1627             /* Will end the loop, but check event type and compact before */
1628             endLoop = TRUE;
1629         } else if (!ValidEvent(next)) {
1630             continue;
1631         } else {
1632             /* merge click events forward */
1633             if ((ep->bstate & BUTTON_CLICKED)
1634                 && (next->bstate & BUTTON_CLICKED)) {
1635                 merge = FALSE;
1636                 for (b = 1; b <= MAX_BUTTONS; ++b) {
1637                     if ((sp->_mouse_mask & MASK_DOUBLE_CLICK(b))
1638                         && (ep->bstate & MASK_CLICK(b))
1639                         && (next->bstate & MASK_CLICK(b))) {
1640                         next->bstate &= ~MASK_CLICK(b);
1641                         next->bstate |= MASK_DOUBLE_CLICK(b);
1642                         merge = TRUE;
1643                     }
1644                 }
1645                 if (merge) {
1646                     Invalidate(ep);
1647                 }
1648             }
1649
1650             /* merge double-click events forward */
1651             if ((ep->bstate & BUTTON_DOUBLE_CLICKED)
1652                 && (next->bstate & BUTTON_CLICKED)) {
1653                 merge = FALSE;
1654                 for (b = 1; b <= MAX_BUTTONS; ++b) {
1655                     if ((sp->_mouse_mask & MASK_TRIPLE_CLICK(b))
1656                         && (ep->bstate & MASK_DOUBLE_CLICK(b))
1657                         && (next->bstate & MASK_CLICK(b))) {
1658                         next->bstate &= ~MASK_CLICK(b);
1659                         next->bstate |= MASK_TRIPLE_CLICK(b);
1660                         merge = TRUE;
1661                     }
1662                 }
1663                 if (merge) {
1664                     Invalidate(ep);
1665                 }
1666             }
1667         }
1668
1669         /* Discard event if it does not match event mask */
1670         if (!(ep->bstate & sp->_mouse_mask2)) {
1671             Invalidate(ep);
1672         }
1673
1674         /* Compact valid events */
1675         if (!ValidEvent(ep)) {
1676             if (ep == first_valid) {
1677                 first_valid = next;
1678             } else if (first_invalid == NULL) {
1679                 first_invalid = ep;
1680             }
1681         } else if (first_invalid != NULL) {
1682             *first_invalid = *ep;
1683             Invalidate(ep);
1684             first_invalid = NEXT(first_invalid);
1685         }
1686
1687         ep = next;
1688     }
1689
1690     if (first_invalid == NULL) {
1691         first_invalid = eventp;
1692     }
1693     sp->_mouse_eventp = first_invalid;
1694
1695 #ifdef TRACE
1696     if (first_valid != NULL) {
1697         if (USE_TRACEF(TRACE_IEVENT)) {
1698             _trace_slot(sp, "after mouse event queue compaction:");
1699             _tracef("_nc_mouse_parse: run starts at %ld, ends at %ld, count %d",
1700                     RunParams(sp, first_invalid, first_valid),
1701                     runcount);
1702             _nc_unlock_global(tracef);
1703         }
1704         for (ep = first_valid; ep != first_invalid; ep = NEXT(ep)) {
1705             if (ValidEvent(ep))
1706                 TR(MY_TRACE,
1707                    ("_nc_mouse_parse: returning composite mouse event %s at slot %ld",
1708                     _nc_tracemouse(sp, ep),
1709                     (long) IndexEV(sp, ep)));
1710         }
1711     }
1712 #endif /* TRACE */
1713
1714     /* after all this, do we have a valid event? */
1715     return ValidEvent(PREV(first_invalid));
1716 }
1717
1718 static void
1719 _nc_mouse_wrap(SCREEN *sp)
1720 /* release mouse -- called by endwin() before shellout/exit */
1721 {
1722     TR(MY_TRACE, ("_nc_mouse_wrap() called"));
1723
1724     switch (sp->_mouse_type) {
1725     case M_XTERM:
1726         if (sp->_mouse_mask)
1727             mouse_activate(sp, FALSE);
1728         break;
1729 #if USE_GPM_SUPPORT
1730         /* GPM: pass all mouse events to next client */
1731     case M_GPM:
1732         if (sp->_mouse_mask)
1733             mouse_activate(sp, FALSE);
1734         break;
1735 #endif
1736 #if USE_SYSMOUSE
1737     case M_SYSMOUSE:
1738         mouse_activate(sp, FALSE);
1739         break;
1740 #endif
1741 #ifdef USE_TERM_DRIVER
1742     case M_TERM_DRIVER:
1743         mouse_activate(sp, FALSE);
1744         break;
1745 #endif
1746     case M_NONE:
1747         break;
1748     }
1749 }
1750
1751 static void
1752 _nc_mouse_resume(SCREEN *sp)
1753 /* re-connect to mouse -- called by doupdate() after shellout */
1754 {
1755     TR(MY_TRACE, ("_nc_mouse_resume() called"));
1756
1757     switch (sp->_mouse_type) {
1758     case M_XTERM:
1759         /* xterm: re-enable reporting */
1760         if (sp->_mouse_mask)
1761             mouse_activate(sp, TRUE);
1762         break;
1763
1764 #if USE_GPM_SUPPORT
1765     case M_GPM:
1766         /* GPM: reclaim our event set */
1767         if (sp->_mouse_mask)
1768             mouse_activate(sp, TRUE);
1769         break;
1770 #endif
1771
1772 #if USE_SYSMOUSE
1773     case M_SYSMOUSE:
1774         mouse_activate(sp, TRUE);
1775         break;
1776 #endif
1777
1778 #ifdef USE_TERM_DRIVER
1779     case M_TERM_DRIVER:
1780         mouse_activate(sp, TRUE);
1781         break;
1782 #endif
1783
1784     case M_NONE:
1785         break;
1786     }
1787 }
1788
1789 /**************************************************************************
1790  *
1791  * Mouse interface entry points for the API
1792  *
1793  **************************************************************************/
1794
1795 NCURSES_EXPORT(int)
1796 NCURSES_SP_NAME(getmouse) (NCURSES_SP_DCLx MEVENT * aevent)
1797 {
1798     int result = ERR;
1799     MEVENT *eventp;
1800
1801     T((T_CALLED("getmouse(%p,%p)"), (void *) SP_PARM, (void *) aevent));
1802
1803     if ((aevent != 0) &&
1804         (SP_PARM != 0) &&
1805         (SP_PARM->_mouse_type != M_NONE) &&
1806         (eventp = SP_PARM->_mouse_eventp) != 0) {
1807         /* compute the current-event pointer */
1808         MEVENT *prev = PREV(eventp);
1809
1810         /*
1811          * Discard events not matching mask (there could be still some if
1812          * _nc_mouse_parse was not called, e.g., when _nc_mouse_inline returns
1813          * false).
1814          */
1815         while (ValidEvent(prev) && (!(prev->bstate & SP_PARM->_mouse_mask2))) {
1816             Invalidate(prev);
1817             prev = PREV(prev);
1818         }
1819         if (ValidEvent(prev)) {
1820             /* copy the event we find there */
1821             *aevent = *prev;
1822
1823             TR(TRACE_IEVENT, ("getmouse: returning event %s from slot %ld",
1824                               _nc_tracemouse(SP_PARM, prev),
1825                               (long) IndexEV(SP_PARM, prev)));
1826
1827             Invalidate(prev);   /* so the queue slot becomes free */
1828             SP_PARM->_mouse_eventp = prev;
1829             result = OK;
1830         } else {
1831             /* Reset the provided event */
1832             aevent->bstate = 0;
1833             Invalidate(aevent);
1834             aevent->x = 0;
1835             aevent->y = 0;
1836             aevent->z = 0;
1837         }
1838     }
1839     returnCode(result);
1840 }
1841
1842 #if NCURSES_SP_FUNCS
1843 /* grab a copy of the current mouse event */
1844 NCURSES_EXPORT(int)
1845 getmouse(MEVENT * aevent)
1846 {
1847     return NCURSES_SP_NAME(getmouse) (CURRENT_SCREEN, aevent);
1848 }
1849 #endif
1850
1851 NCURSES_EXPORT(int)
1852 NCURSES_SP_NAME(ungetmouse) (NCURSES_SP_DCLx MEVENT * aevent)
1853 {
1854     int result = ERR;
1855     MEVENT *eventp;
1856
1857     T((T_CALLED("ungetmouse(%p,%p)"), (void *) SP_PARM, (void *) aevent));
1858
1859     if (aevent != 0 &&
1860         SP_PARM != 0 &&
1861         (eventp = SP_PARM->_mouse_eventp) != 0) {
1862
1863         /* stick the given event in the next-free slot */
1864         *eventp = *aevent;
1865
1866         /* bump the next-free pointer into the circular list */
1867         SP_PARM->_mouse_eventp = NEXT(eventp);
1868
1869         /* push back the notification event on the keyboard queue */
1870         result = NCURSES_SP_NAME(ungetch) (NCURSES_SP_ARGx KEY_MOUSE);
1871     }
1872     returnCode(result);
1873 }
1874
1875 #if NCURSES_SP_FUNCS
1876 /* enqueue a synthesized mouse event to be seen by the next wgetch() */
1877 NCURSES_EXPORT(int)
1878 ungetmouse(MEVENT * aevent)
1879 {
1880     return NCURSES_SP_NAME(ungetmouse) (CURRENT_SCREEN, aevent);
1881 }
1882 #endif
1883
1884 NCURSES_EXPORT(mmask_t)
1885 NCURSES_SP_NAME(mousemask) (NCURSES_SP_DCLx mmask_t newmask, mmask_t * oldmask)
1886 /* set the mouse event mask */
1887 {
1888     mmask_t result = 0;
1889
1890     T((T_CALLED("mousemask(%p,%#lx,%p)"),
1891        (void *) SP_PARM,
1892        (unsigned long) newmask,
1893        (void *) oldmask));
1894
1895     if (SP_PARM != 0) {
1896         if (oldmask)
1897             *oldmask = SP_PARM->_mouse_mask;
1898
1899         if (newmask || SP_PARM->_mouse_initialized) {
1900             _nc_mouse_init(SP_PARM);
1901
1902             if (SP_PARM->_mouse_type != M_NONE) {
1903                 int b;
1904
1905                 result = newmask &
1906                     (REPORT_MOUSE_POSITION
1907                      | BUTTON_ALT
1908                      | BUTTON_CTRL
1909                      | BUTTON_SHIFT
1910                      | BUTTON_PRESSED
1911                      | BUTTON_RELEASED
1912                      | BUTTON_CLICKED
1913                      | BUTTON_DOUBLE_CLICKED
1914                      | BUTTON_TRIPLE_CLICKED);
1915
1916                 mouse_activate(SP_PARM, (bool) (result != 0));
1917
1918                 SP_PARM->_mouse_mask = result;
1919                 SP_PARM->_mouse_mask2 = result;
1920
1921                 /*
1922                  * Make a mask corresponding to the states we will need to
1923                  * retain (temporarily) while building up the state that the
1924                  * user asked for.
1925                  */
1926                 for (b = 1; b <= MAX_BUTTONS; ++b) {
1927                     if (SP_PARM->_mouse_mask2 & MASK_TRIPLE_CLICK(b))
1928                         SP_PARM->_mouse_mask2 |= MASK_DOUBLE_CLICK(b);
1929                     if (SP_PARM->_mouse_mask2 & MASK_DOUBLE_CLICK(b))
1930                         SP_PARM->_mouse_mask2 |= MASK_CLICK(b);
1931                     if (SP_PARM->_mouse_mask2 & MASK_CLICK(b))
1932                         SP_PARM->_mouse_mask2 |= (MASK_PRESS(b) |
1933                                                   MASK_RELEASE(b));
1934                 }
1935             }
1936         }
1937     }
1938     returnMMask(result);
1939 }
1940
1941 #if NCURSES_SP_FUNCS
1942 NCURSES_EXPORT(mmask_t)
1943 mousemask(mmask_t newmask, mmask_t * oldmask)
1944 {
1945     return NCURSES_SP_NAME(mousemask) (CURRENT_SCREEN, newmask, oldmask);
1946 }
1947 #endif
1948
1949 NCURSES_EXPORT(bool)
1950 wenclose(const WINDOW *win, int y, int x)
1951 /* check to see if given window encloses given screen location */
1952 {
1953     bool result = FALSE;
1954
1955     T((T_CALLED("wenclose(%p,%d,%d)"), (const void *) win, y, x));
1956
1957     if (win != 0) {
1958         y -= win->_yoffset;
1959         result = ((win->_begy <= y &&
1960                    win->_begx <= x &&
1961                    (win->_begx + win->_maxx) >= x &&
1962                    (win->_begy + win->_maxy) >= y) ? TRUE : FALSE);
1963     }
1964     returnBool(result);
1965 }
1966
1967 NCURSES_EXPORT(int)
1968 NCURSES_SP_NAME(mouseinterval) (NCURSES_SP_DCLx int maxclick)
1969 /* set the maximum mouse interval within which to recognize a click */
1970 {
1971     int oldval;
1972
1973     T((T_CALLED("mouseinterval(%p,%d)"), (void *) SP_PARM, maxclick));
1974
1975     if (SP_PARM != 0) {
1976         oldval = SP_PARM->_maxclick;
1977         if (maxclick >= 0)
1978             SP_PARM->_maxclick = maxclick;
1979     } else {
1980         oldval = DEFAULT_MAXCLICK;
1981     }
1982
1983     returnCode(oldval);
1984 }
1985
1986 #if NCURSES_SP_FUNCS
1987 NCURSES_EXPORT(int)
1988 mouseinterval(int maxclick)
1989 {
1990     return NCURSES_SP_NAME(mouseinterval) (CURRENT_SCREEN, maxclick);
1991 }
1992 #endif
1993
1994 /* This may be used by other routines to ask for the existence of mouse
1995    support */
1996 NCURSES_EXPORT(bool)
1997 _nc_has_mouse(SCREEN *sp)
1998 {
1999     return (((0 == sp) || (sp->_mouse_type == M_NONE)) ? FALSE : TRUE);
2000 }
2001
2002 NCURSES_EXPORT(bool)
2003 NCURSES_SP_NAME(has_mouse) (NCURSES_SP_DCL0)
2004 {
2005     return _nc_has_mouse(SP_PARM);
2006 }
2007
2008 #if NCURSES_SP_FUNCS
2009 NCURSES_EXPORT(bool)
2010 has_mouse(void)
2011 {
2012     return _nc_has_mouse(CURRENT_SCREEN);
2013 }
2014 #endif
2015
2016 NCURSES_EXPORT(bool)
2017 wmouse_trafo(const WINDOW *win, int *pY, int *pX, bool to_screen)
2018 {
2019     bool result = FALSE;
2020
2021     T((T_CALLED("wmouse_trafo(%p,%p,%p,%d)"),
2022        (const void *) win,
2023        (void *) pY,
2024        (void *) pX,
2025        to_screen));
2026
2027     if (win && pY && pX) {
2028         int y = *pY;
2029         int x = *pX;
2030
2031         if (to_screen) {
2032             y += win->_begy + win->_yoffset;
2033             x += win->_begx;
2034             if (wenclose(win, y, x))
2035                 result = TRUE;
2036         } else {
2037             if (wenclose(win, y, x)) {
2038                 y -= (win->_begy + win->_yoffset);
2039                 x -= win->_begx;
2040                 result = TRUE;
2041             }
2042         }
2043         if (result) {
2044             *pX = x;
2045             *pY = y;
2046         }
2047     }
2048     returnBool(result);
2049 }