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