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