]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/base/lib_mouse.c
ncurses 5.6 - patch 20070929
[ncurses.git] / ncurses / base / lib_mouse.c
1 /****************************************************************************
2  * Copyright (c) 1998-2006,2007 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  ****************************************************************************/
34
35 /*
36  * This module is intended to encapsulate ncurses's interface to pointing
37  * devices.
38  *
39  * The primary method used is xterm's internal mouse-tracking facility.
40  * Additional methods depend on the platform:
41  *      Alessandro Rubini's GPM server (Linux)
42  *      sysmouse (FreeBSD)
43  *      special-purpose mouse interface for OS/2 EMX.
44  *
45  * Notes for implementors of new mouse-interface methods:
46  *
47  * The code is logically split into a lower level that accepts event reports
48  * in a device-dependent format and an upper level that parses mouse gestures
49  * and filters events.  The mediating data structure is a circular queue of
50  * MEVENT structures.
51  *
52  * Functionally, the lower level's job is to pick up primitive events and
53  * put them on the circular queue.  This can happen in one of two ways:
54  * either (a) _nc_mouse_event() detects a series of incoming mouse reports
55  * and queues them, or (b) code in lib_getch.c detects the kmous prefix in
56  * the keyboard input stream and calls _nc_mouse_inline to queue up a series
57  * of adjacent mouse reports.
58  *
59  * In either case, _nc_mouse_parse() should be called after the series is
60  * accepted to parse the digested mouse reports (low-level MEVENTs) into
61  * a gesture (a high-level or composite MEVENT).
62  *
63  * Don't be too shy about adding new event types or modifiers, if you can find
64  * room for them in the 32-bit mask.  The API is written so that users get
65  * feedback on which theoretical event types they won't see when they call
66  * mousemask. There's one bit per button (the RESERVED_EVENT bit) not being
67  * used yet, and a couple of bits open at the high end.
68  */
69
70 #ifdef __EMX__
71 #  include <io.h>
72 #  define  INCL_DOS
73 #  define  INCL_VIO
74 #  define  INCL_KBD
75 #  define  INCL_MOU
76 #  define  INCL_DOSPROCESS
77 #  include <os2.h>              /* Need to include before the others */
78 #endif
79
80 #include <curses.priv.h>
81
82 MODULE_ID("$Id: lib_mouse.c,v 1.88 2007/09/29 21:50:04 tom Exp $")
83
84 #include <term.h>
85 #include <tic.h>
86
87 #if USE_GPM_SUPPORT
88 #include <linux/keyboard.h>     /* defines KG_* macros */
89
90 #ifdef HAVE_LIBDL
91 /* use dynamic loader to avoid linkage dependency */
92 #include <dlfcn.h>
93
94 #ifdef RTLD_NOW
95 #define my_RTLD RTLD_NOW
96 #else
97 #ifdef RTLD_LAZY
98 #define my_RTLD RTLD_LAZY
99 #else
100 make an error
101 #endif
102 #endif                          /* RTLD_NOW */
103 #endif                          /* HAVE_LIBDL */
104
105 #endif                          /* USE_GPM_SUPPORT */
106
107 #if USE_SYSMOUSE
108 #undef buttons                  /* symbol conflict in consio.h */
109 #undef mouse_info               /* symbol conflict in consio.h */
110 #include <osreldate.h>
111 #if (__FreeBSD_version >= 400017)
112 #include <sys/consio.h>
113 #include <sys/fbio.h>
114 #else
115 #include <machine/console.h>
116 #endif
117 #endif                          /* use_SYSMOUSE */
118
119 #define MY_TRACE TRACE_ICALLS|TRACE_IEVENT
120
121 #define MASK_RELEASE(x)         NCURSES_MOUSE_MASK(x, 001)
122 #define MASK_PRESS(x)           NCURSES_MOUSE_MASK(x, 002)
123 #define MASK_CLICK(x)           NCURSES_MOUSE_MASK(x, 004)
124 #define MASK_DOUBLE_CLICK(x)    NCURSES_MOUSE_MASK(x, 010)
125 #define MASK_TRIPLE_CLICK(x)    NCURSES_MOUSE_MASK(x, 020)
126 #define MASK_RESERVED_EVENT(x)  NCURSES_MOUSE_MASK(x, 040)
127
128 #if NCURSES_MOUSE_VERSION == 1
129 #define BUTTON_CLICKED        (BUTTON1_CLICKED        | BUTTON2_CLICKED        | BUTTON3_CLICKED        | BUTTON4_CLICKED)
130 #define BUTTON_PRESSED        (BUTTON1_PRESSED        | BUTTON2_PRESSED        | BUTTON3_PRESSED        | BUTTON4_PRESSED)
131 #define BUTTON_RELEASED       (BUTTON1_RELEASED       | BUTTON2_RELEASED       | BUTTON3_RELEASED       | BUTTON4_RELEASED)
132 #define BUTTON_DOUBLE_CLICKED (BUTTON1_DOUBLE_CLICKED | BUTTON2_DOUBLE_CLICKED | BUTTON3_DOUBLE_CLICKED | BUTTON4_DOUBLE_CLICKED)
133 #define BUTTON_TRIPLE_CLICKED (BUTTON1_TRIPLE_CLICKED | BUTTON2_TRIPLE_CLICKED | BUTTON3_TRIPLE_CLICKED | BUTTON4_TRIPLE_CLICKED)
134 #define MAX_BUTTONS  4
135 #else
136 #define BUTTON_CLICKED        (BUTTON1_CLICKED        | BUTTON2_CLICKED        | BUTTON3_CLICKED        | BUTTON4_CLICKED        | BUTTON5_CLICKED)
137 #define BUTTON_PRESSED        (BUTTON1_PRESSED        | BUTTON2_PRESSED        | BUTTON3_PRESSED        | BUTTON4_PRESSED        | BUTTON5_PRESSED)
138 #define BUTTON_RELEASED       (BUTTON1_RELEASED       | BUTTON2_RELEASED       | BUTTON3_RELEASED       | BUTTON4_RELEASED       | BUTTON5_RELEASED)
139 #define BUTTON_DOUBLE_CLICKED (BUTTON1_DOUBLE_CLICKED | BUTTON2_DOUBLE_CLICKED | BUTTON3_DOUBLE_CLICKED | BUTTON4_DOUBLE_CLICKED | BUTTON5_DOUBLE_CLICKED)
140 #define BUTTON_TRIPLE_CLICKED (BUTTON1_TRIPLE_CLICKED | BUTTON2_TRIPLE_CLICKED | BUTTON3_TRIPLE_CLICKED | BUTTON4_TRIPLE_CLICKED | BUTTON5_TRIPLE_CLICKED)
141 #define MAX_BUTTONS  5
142 #endif
143
144 #define INVALID_EVENT   -1
145 #define NORMAL_EVENT    0
146
147 #if USE_GPM_SUPPORT
148
149 #ifndef LIBGPM_SONAME
150 #define LIBGPM_SONAME "libgpm.so"
151 #endif
152
153 #define GET_DLSYM(name) (my_##name = (TYPE_##name) dlsym(obj, #name))
154
155 #endif                          /* USE_GPM_SUPPORT */
156
157 static bool _nc_mouse_parse(int);
158 static void _nc_mouse_resume(SCREEN *);
159 static void _nc_mouse_wrap(SCREEN *);
160
161 /* maintain a circular list of mouse events */
162
163 #undef  NEXT
164 #define NEXT(ep)        ((ep == SP->_mouse_events + EV_MAX - 1) \
165                          ? SP->_mouse_events \
166                          : ep + 1)
167
168 #undef  PREV
169 #define PREV(ep)        ((ep == SP->_mouse_events) \
170                          ? SP->_mouse_events + EV_MAX - 1 \
171                          : ep - 1)
172
173 #ifdef TRACE
174 static void
175 _trace_slot(const char *tag)
176 {
177     MEVENT *ep;
178
179     _tracef(tag);
180
181     for (ep = SP->_mouse_events; ep < SP->_mouse_events + EV_MAX; ep++)
182         _tracef("mouse event queue slot %ld = %s",
183                 (long) (ep - SP->_mouse_events),
184                 _tracemouse(ep));
185 }
186 #endif
187
188 #if USE_EMX_MOUSE
189
190 #  define TOP_ROW          0
191 #  define LEFT_COL         0
192
193 #  define M_FD(sp) sp->_mouse_fd
194
195 static void
196 write_event(int down, int button, int x, int y)
197 {
198     char buf[6];
199     unsigned long ignore;
200
201     strncpy(buf, key_mouse, 3); /* should be "\033[M" */
202     buf[3] = ' ' + (button - 1) + (down ? 0 : 0x40);
203     buf[4] = ' ' + x - LEFT_COL + 1;
204     buf[5] = ' ' + y - TOP_ROW + 1;
205     DosWrite(SP->_emxmouse_wfd, buf, 6, &ignore);
206 }
207
208 static void
209 mouse_server(unsigned long ignored GCC_UNUSED)
210 {
211     unsigned short fWait = MOU_WAIT;
212     /* NOPTRRECT mourt = { 0,0,24,79 }; */
213     MOUEVENTINFO mouev;
214     HMOU hmou;
215     unsigned short mask = MOUSE_BN1_DOWN | MOUSE_BN2_DOWN | MOUSE_BN3_DOWN;
216     int nbuttons = 3;
217     int oldstate = 0;
218     char err[80];
219     unsigned long rc;
220
221     /* open the handle for the mouse */
222     if (MouOpen(NULL, &hmou) == 0) {
223         rc = MouSetEventMask(&mask, hmou);
224         if (rc) {               /* retry with 2 buttons */
225             mask = MOUSE_BN1_DOWN | MOUSE_BN2_DOWN;
226             rc = MouSetEventMask(&mask, hmou);
227             nbuttons = 2;
228         }
229         if (rc == 0 && MouDrawPtr(hmou) == 0) {
230             for (;;) {
231                 /* sit and wait on the event queue */
232                 rc = MouReadEventQue(&mouev, &fWait, hmou);
233                 if (rc) {
234                     sprintf(err, "Error reading mouse queue, rc=%lu.\r\n", rc);
235                     break;
236                 }
237                 if (!SP->_emxmouse_activated)
238                     goto finish;
239
240                 /*
241                  * OS/2 numbers a 3-button mouse inconsistently from other
242                  * platforms:
243                  *      1 = left
244                  *      2 = right
245                  *      3 = middle.
246                  */
247                 if ((mouev.fs ^ oldstate) & MOUSE_BN1_DOWN)
248                     write_event(mouev.fs & MOUSE_BN1_DOWN,
249                                 SP->_emxmouse_buttons[1], mouev.col, mouev.row);
250                 if ((mouev.fs ^ oldstate) & MOUSE_BN2_DOWN)
251                     write_event(mouev.fs & MOUSE_BN2_DOWN,
252                                 SP->_emxmouse_buttons[3], mouev.col, mouev.row);
253                 if ((mouev.fs ^ oldstate) & MOUSE_BN3_DOWN)
254                     write_event(mouev.fs & MOUSE_BN3_DOWN,
255                                 SP->_emxmouse_buttons[2], mouev.col, mouev.row);
256
257               finish:
258                 oldstate = mouev.fs;
259             }
260         } else
261             sprintf(err, "Error setting event mask, buttons=%d, rc=%lu.\r\n",
262                     nbuttons, rc);
263
264         DosWrite(2, err, strlen(err), &rc);
265         MouClose(hmou);
266     }
267     DosExit(EXIT_THREAD, 0L);
268 }
269
270 #endif /* USE_EMX_MOUSE */
271
272 #if USE_SYSMOUSE
273 static void
274 handle_sysmouse(int sig GCC_UNUSED)
275 {
276     struct mouse_info the_mouse;
277     MEVENT *work;
278
279     the_mouse.operation = MOUSE_GETINFO;
280     if (SP != 0
281         && SP->_mouse_fd >= 0
282         && SP->_sysmouse_tail < FIFO_SIZE
283         && ioctl(SP->_mouse_fd, CONS_MOUSECTL, &the_mouse) != -1) {
284
285         if (SP->_sysmouse_head > SP->_sysmouse_tail) {
286             SP->_sysmouse_tail = 0;
287             SP->_sysmouse_head = 0;
288         }
289         work = &(SP->_sysmouse_fifo[SP->_sysmouse_tail]);
290         memset(work, 0, sizeof(*work));
291         work->id = NORMAL_EVENT;        /* there's only one mouse... */
292
293         SP->_sysmouse_old_buttons = SP->_sysmouse_new_buttons;
294         SP->_sysmouse_new_buttons = the_mouse.u.data.buttons & 0x7;
295
296         if (SP->_sysmouse_new_buttons) {
297             if (SP->_sysmouse_new_buttons & 1)
298                 work->bstate |= BUTTON1_PRESSED;
299             if (SP->_sysmouse_new_buttons & 2)
300                 work->bstate |= BUTTON2_PRESSED;
301             if (SP->_sysmouse_new_buttons & 4)
302                 work->bstate |= BUTTON3_PRESSED;
303         } else {
304             if (SP->_sysmouse_old_buttons & 1)
305                 work->bstate |= BUTTON1_RELEASED;
306             if (SP->_sysmouse_old_buttons & 2)
307                 work->bstate |= BUTTON2_RELEASED;
308             if (SP->_sysmouse_old_buttons & 4)
309                 work->bstate |= BUTTON3_RELEASED;
310         }
311
312         /* for cosmetic bug in syscons.c on FreeBSD 3.[34] */
313         the_mouse.operation = MOUSE_HIDE;
314         ioctl(SP->_mouse_fd, CONS_MOUSECTL, &the_mouse);
315         the_mouse.operation = MOUSE_SHOW;
316         ioctl(SP->_mouse_fd, CONS_MOUSECTL, &the_mouse);
317
318         /*
319          * We're only interested if the button is pressed or released.
320          * FIXME: implement continuous event-tracking.
321          */
322         if (SP->_sysmouse_new_buttons != SP->_sysmouse_old_buttons) {
323             SP->_sysmouse_tail += 1;
324         }
325         work->x = the_mouse.u.data.x / SP->_sysmouse_char_width;
326         work->y = the_mouse.u.data.y / SP->_sysmouse_char_height;
327     }
328 }
329 #endif /* USE_SYSMOUSE */
330
331 static void
332 init_xterm_mouse(void)
333 {
334     SP->_mouse_type = M_XTERM;
335     SP->_mouse_xtermcap = tigetstr("XM");
336     if (!VALID_STRING(SP->_mouse_xtermcap))
337         SP->_mouse_xtermcap = "\033[?1000%?%p1%{1}%=%th%el%;";
338 }
339
340 static void
341 enable_xterm_mouse(int enable)
342 {
343 #if USE_EMX_MOUSE
344     SP->_emxmouse_activated = enable;
345 #else
346     putp(TPARM_1(SP->_mouse_xtermcap, enable));
347 #endif
348     SP->_mouse_active = enable;
349 }
350
351 #if USE_GPM_SUPPORT
352 static int
353 allow_gpm_mouse(void)
354 {
355     /* GPM does printf's without checking if stdout is a terminal */
356     if (isatty(fileno(stdout))) {
357         char *env = getenv("TERM");
358         /* GPM checks the beginning of the $TERM variable to decide if
359          * it should pass xterm events through.  There is no real advantage
360          * in allowing GPM to do this.
361          */
362         if (env == 0 || strncmp(env, "xterm", 5))
363             return TRUE;
364     }
365     return FALSE;
366 }
367
368 static bool
369 enable_gpm_mouse(int enable)
370 {
371     bool result;
372
373     T((T_CALLED("enable_gpm_mouse(%d)"), enable));
374
375     if (enable && !SP->_mouse_active) {
376         /* GPM: initialize connection to gpm server */
377         SP->_mouse_gpm_connect.eventMask = GPM_DOWN | GPM_UP;
378         SP->_mouse_gpm_connect.defaultMask =
379             ~(SP->_mouse_gpm_connect.eventMask | GPM_HARD);
380         SP->_mouse_gpm_connect.minMod = 0;
381         SP->_mouse_gpm_connect.maxMod =
382             (unsigned short) (~((1 << KG_SHIFT) |
383                                 (1 << KG_SHIFTL) |
384                                 (1 << KG_SHIFTR)));
385         /*
386          * Note: GPM hardcodes \E[?1001s and \E[?1000h during its open.
387          * The former is recognized by wscons (SunOS), and the latter by
388          * xterm.  Those will not show up in ncurses' traces.
389          */
390         result = (my_Gpm_Open(&SP->_mouse_gpm_connect, 0) >= 0);
391         SP->_mouse_active = result;
392         T(("GPM open %s", result ? "succeeded" : "failed"));
393     } else {
394         if (!enable && SP->_mouse_active) {
395             /* GPM: close connection to gpm server */
396             my_Gpm_Close();
397             SP->_mouse_active = FALSE;
398             T(("GPM closed"));
399         }
400         result = FALSE;
401     }
402     returnBool(result);
403 }
404 #endif /* USE_GPM_SUPPORT */
405
406 #define xterm_kmous "\033[M"
407
408 static void
409 initialize_mousetype(void)
410 {
411     T((T_CALLED("initialize_mousetype()")));
412
413     /* Try gpm first, because gpm may be configured to run in xterm */
414 #if USE_GPM_SUPPORT
415     if (allow_gpm_mouse()) {
416         if (!SP->_mouse_gpm_loaded) {
417 #ifdef HAVE_LIBDL
418             void *obj;
419
420             if ((obj = dlopen(LIBGPM_SONAME, my_RTLD)) != 0) {
421                 if (GET_DLSYM(gpm_fd) == 0 ||
422                     GET_DLSYM(Gpm_Open) == 0 ||
423                     GET_DLSYM(Gpm_Close) == 0 ||
424                     GET_DLSYM(Gpm_GetEvent) == 0) {
425                     T(("GPM initialization failed: %s", dlerror()));
426                     dlclose(obj);
427                 } else {
428                     SP->_mouse_gpm_found = TRUE;
429                 }
430             }
431 #else /* !HAVE_LIBDL */
432             SP->_mouse_gpm_found = TRUE;
433 #endif
434             SP->_mouse_gpm_loaded = TRUE;
435         }
436
437         /*
438          * The gpm_fd file-descriptor may be negative (xterm).  So we have to
439          * maintain our notion of whether the mouse connection is active
440          * without testing the file-descriptor.
441          */
442         if (SP->_mouse_gpm_found && enable_gpm_mouse(TRUE)) {
443             SP->_mouse_type = M_GPM;
444             SP->_mouse_fd = *(my_gpm_fd);
445             T(("GPM mouse_fd %d", SP->_mouse_fd));
446             returnVoid;
447         }
448     }
449 #endif /* USE_GPM_SUPPORT */
450
451     /* OS/2 VIO */
452 #if USE_EMX_MOUSE
453     if (!SP->_emxmouse_thread
454         && strstr(cur_term->type.term_names, "xterm") == 0
455         && key_mouse) {
456         int handles[2];
457
458         if (pipe(handles) < 0) {
459             perror("mouse pipe error");
460             returnVoid;
461         } else {
462             int rc;
463
464             if (!SP->_emxmouse_buttons[0]) {
465                 char *s = getenv("MOUSE_BUTTONS_123");
466
467                 SP->_emxmouse_buttons[0] = 1;
468                 if (s && strlen(s) >= 3) {
469                     SP->_emxmouse_buttons[1] = s[0] - '0';
470                     SP->_emxmouse_buttons[2] = s[1] - '0';
471                     SP->_emxmouse_buttons[3] = s[2] - '0';
472                 } else {
473                     SP->_emxmouse_buttons[1] = 1;
474                     SP->_emxmouse_buttons[2] = 3;
475                     SP->_emxmouse_buttons[3] = 2;
476                 }
477             }
478             SP->_emxmouse_wfd = handles[1];
479             M_FD(SP) = handles[0];
480             /* Needed? */
481             setmode(handles[0], O_BINARY);
482             setmode(handles[1], O_BINARY);
483             /* Do not use CRT functions, we may single-threaded. */
484             rc = DosCreateThread((unsigned long *) &SP->_emxmouse_thread,
485                                  mouse_server, 0, 0, 8192);
486             if (rc) {
487                 printf("mouse thread error %d=%#x", rc, rc);
488             } else {
489                 SP->_mouse_type = M_XTERM;
490             }
491             returnVoid;
492         }
493     }
494 #endif /* USE_EMX_MOUSE */
495
496 #if USE_SYSMOUSE
497     {
498         struct mouse_info the_mouse;
499         char *the_device = 0;
500
501         if (isatty(SP->_ifd))
502             the_device = ttyname(SP->_ifd);
503         if (the_device == 0)
504             the_device = "/dev/tty";
505
506         SP->_mouse_fd = open(the_device, O_RDWR);
507
508         if (SP->_mouse_fd >= 0) {
509             /*
510              * sysmouse does not have a usable user interface for obtaining
511              * mouse events.  The logical way to proceed (reading data on a
512              * stream) only works if one opens the device as root.  Even in
513              * that mode, careful examination shows we lose events
514              * occasionally.  The interface provided for user programs is to
515              * establish a signal handler.  really.
516              *
517              * Take over SIGUSR2 for this purpose since SIGUSR1 is more
518              * likely to be used by an application.  getch() will have to
519              * handle the misleading EINTR's.
520              */
521             signal(SIGUSR2, SIG_IGN);
522             the_mouse.operation = MOUSE_MODE;
523             the_mouse.u.mode.mode = 0;
524             the_mouse.u.mode.signal = SIGUSR2;
525             if (ioctl(SP->_mouse_fd, CONS_MOUSECTL, &the_mouse) != -1) {
526                 signal(SIGUSR2, handle_sysmouse);
527                 the_mouse.operation = MOUSE_SHOW;
528                 ioctl(SP->_mouse_fd, CONS_MOUSECTL, &the_mouse);
529
530 #if defined(FBIO_MODEINFO) || defined(CONS_MODEINFO)    /* FreeBSD > 2.x */
531                 {
532 #ifndef FBIO_GETMODE            /* FreeBSD 3.x */
533 #define FBIO_GETMODE    CONS_GET
534 #define FBIO_MODEINFO   CONS_MODEINFO
535 #endif /* FBIO_GETMODE */
536                     video_info_t the_video;
537
538                     if (ioctl(SP->_mouse_fd,
539                               FBIO_GETMODE,
540                               &the_video.vi_mode) != -1
541                         && ioctl(SP->_mouse_fd,
542                                  FBIO_MODEINFO,
543                                  &the_video) != -1) {
544                         SP->_sysmouse_char_width = the_video.vi_cwidth;
545                         SP->_sysmouse_char_height = the_video.vi_cheight;
546                     }
547                 }
548 #endif /* defined(FBIO_MODEINFO) || defined(CONS_MODEINFO) */
549
550                 if (SP->_sysmouse_char_width <= 0)
551                     SP->_sysmouse_char_width = 8;
552                 if (SP->_sysmouse_char_height <= 0)
553                     SP->_sysmouse_char_height = 16;
554                 SP->_mouse_type = M_SYSMOUSE;
555                 returnVoid;
556             }
557         }
558     }
559 #endif /* USE_SYSMOUSE */
560
561     /* we know how to recognize mouse events under "xterm" */
562     if (key_mouse != 0) {
563         if (!strcmp(key_mouse, xterm_kmous)
564             || strstr(cur_term->type.term_names, "xterm") != 0) {
565             init_xterm_mouse();
566         }
567     } else if (strstr(cur_term->type.term_names, "xterm") != 0) {
568         if (_nc_add_to_try(&(SP->_keytry), xterm_kmous, KEY_MOUSE) == OK)
569             init_xterm_mouse();
570     }
571     returnVoid;
572 }
573
574 static bool
575 _nc_mouse_init(void)
576 /* initialize the mouse */
577 {
578     bool result = FALSE;
579     int i;
580
581     if (SP != 0) {
582         if (!SP->_mouse_initialized) {
583             SP->_mouse_initialized = TRUE;
584
585             TR(MY_TRACE, ("_nc_mouse_init() called"));
586
587             SP->_mouse_eventp = SP->_mouse_events;
588             for (i = 0; i < EV_MAX; i++)
589                 SP->_mouse_events[i].id = INVALID_EVENT;
590
591             initialize_mousetype();
592
593             T(("_nc_mouse_init() set mousetype to %d", SP->_mouse_type));
594         }
595         result = SP->_mouse_initialized;
596     }
597     return result;
598 }
599
600 /*
601  * Query to see if there is a pending mouse event.  This is called from
602  * fifo_push() in lib_getch.c
603  */
604 static bool
605 _nc_mouse_event(SCREEN *sp GCC_UNUSED)
606 {
607     MEVENT *eventp = SP->_mouse_eventp;
608     bool result = FALSE;
609
610     (void) eventp;
611
612     switch (SP->_mouse_type) {
613     case M_XTERM:
614         /* xterm: never have to query, mouse events are in the keyboard stream */
615 #if USE_EMX_MOUSE
616         {
617             char kbuf[3];
618
619             int i, res = read(M_FD(sp), &kbuf, 3);      /* Eat the prefix */
620             if (res != 3)
621                 printf("Got %d chars instead of 3 for prefix.\n", res);
622             for (i = 0; i < res; i++) {
623                 if (kbuf[i] != key_mouse[i])
624                     printf("Got char %d instead of %d for prefix.\n",
625                            (int) kbuf[i], (int) key_mouse[i]);
626             }
627             result = TRUE;
628         }
629 #endif /* USE_EMX_MOUSE */
630         break;
631
632 #if USE_GPM_SUPPORT
633     case M_GPM:
634         {
635             /* query server for event, return TRUE if we find one */
636             Gpm_Event ev;
637
638             if (my_Gpm_GetEvent(&ev) == 1) {
639                 /* there's only one mouse... */
640                 eventp->id = NORMAL_EVENT;
641
642                 eventp->bstate = 0;
643                 switch (ev.type & 0x0f) {
644                 case (GPM_DOWN):
645                     if (ev.buttons & GPM_B_LEFT)
646                         eventp->bstate |= BUTTON1_PRESSED;
647                     if (ev.buttons & GPM_B_MIDDLE)
648                         eventp->bstate |= BUTTON2_PRESSED;
649                     if (ev.buttons & GPM_B_RIGHT)
650                         eventp->bstate |= BUTTON3_PRESSED;
651                     break;
652                 case (GPM_UP):
653                     if (ev.buttons & GPM_B_LEFT)
654                         eventp->bstate |= BUTTON1_RELEASED;
655                     if (ev.buttons & GPM_B_MIDDLE)
656                         eventp->bstate |= BUTTON2_RELEASED;
657                     if (ev.buttons & GPM_B_RIGHT)
658                         eventp->bstate |= BUTTON3_RELEASED;
659                     break;
660                 default:
661                     break;
662                 }
663
664                 eventp->x = ev.x - 1;
665                 eventp->y = ev.y - 1;
666                 eventp->z = 0;
667
668                 /* bump the next-free pointer into the circular list */
669                 SP->_mouse_eventp = eventp = NEXT(eventp);
670                 result = TRUE;
671             }
672         }
673         break;
674 #endif
675
676 #if USE_SYSMOUSE
677     case M_SYSMOUSE:
678         if (SP->_sysmouse_head < SP->_sysmouse_tail) {
679             *eventp = SP->_sysmouse_fifo[SP->_sysmouse_head];
680
681             /*
682              * Point the fifo-head to the next possible location.  If there
683              * are none, reset the indices.  This may be interrupted by the
684              * signal handler, doing essentially the same reset.
685              */
686             SP->_sysmouse_head += 1;
687             if (SP->_sysmouse_head == SP->_sysmouse_tail) {
688                 SP->_sysmouse_tail = 0;
689                 SP->_sysmouse_head = 0;
690             }
691
692             /* bump the next-free pointer into the circular list */
693             SP->_mouse_eventp = eventp = NEXT(eventp);
694             result = TRUE;
695         }
696         break;
697 #endif /* USE_SYSMOUSE */
698
699     case M_NONE:
700         break;
701     }
702
703     return result;              /* true if we found an event */
704 }
705
706 static bool
707 _nc_mouse_inline(SCREEN *sp)
708 /* mouse report received in the keyboard stream -- parse its info */
709 {
710     int b;
711     bool result = FALSE;
712     MEVENT *eventp = SP->_mouse_eventp;
713
714     TR(MY_TRACE, ("_nc_mouse_inline() called"));
715
716     if (SP->_mouse_type == M_XTERM) {
717         unsigned char kbuf[4];
718         mmask_t prev;
719         size_t grabbed;
720         int res;
721
722         /* This code requires that your xterm entry contain the kmous
723          * capability and that it be set to the \E[M documented in the
724          * Xterm Control Sequences reference.  This is how we
725          * arrange for mouse events to be reported via a KEY_MOUSE
726          * return value from wgetch().  After this value is received,
727          * _nc_mouse_inline() gets called and is immediately
728          * responsible for parsing the mouse status information
729          * following the prefix.
730          *
731          * The following quotes from the ctrlseqs.ms document in the
732          * X distribution, describing the X mouse tracking feature:
733          *
734          * Parameters for all mouse tracking escape sequences
735          * generated by xterm encode numeric parameters in a single
736          * character as value+040.  For example, !  is 1.
737          *
738          * On button press or release, xterm sends ESC [ M CbCxCy.
739          * The low two bits of Cb encode button information: 0=MB1
740          * pressed, 1=MB2 pressed, 2=MB3 pressed, 3=release.  The
741          * upper bits encode what modifiers were down when the
742          * button was pressed and are added together.  4=Shift,
743          * 8=Meta, 16=Control.  Cx and Cy are the x and y coordinates
744          * of the mouse event.  The upper left corner is (1,1).
745          *
746          * (End quote)  By the time we get here, we've eaten the
747          * key prefix.  FYI, the loop below is necessary because
748          * mouse click info isn't guaranteed to present as a
749          * single clist item.
750          *
751          * Wheel mice may return buttons 4 and 5 when the wheel is turned.
752          * We encode those as button presses.
753          */
754         for (grabbed = 0; grabbed < 3; grabbed += res) {
755
756             /* For VIO mouse we add extra bit 64 to disambiguate button-up. */
757 #if USE_EMX_MOUSE
758             res = read(M_FD(sp) >= 0 ? M_FD(sp) : sp->_ifd, &kbuf, 3);
759 #else
760             res = read(sp->_ifd, kbuf + grabbed, 3 - grabbed);
761 #endif
762             if (res == -1)
763                 break;
764         }
765         kbuf[3] = '\0';
766
767         TR(TRACE_IEVENT,
768            ("_nc_mouse_inline sees the following xterm data: '%s'", kbuf));
769
770         /* there's only one mouse... */
771         eventp->id = NORMAL_EVENT;
772
773         /* processing code goes here */
774         eventp->bstate = 0;
775         prev = PREV(eventp)->bstate;
776
777 #if USE_EMX_MOUSE
778 #define PRESS_POSITION(n) \
779         eventp->bstate = MASK_PRESS(n); \
780         if (kbuf[0] & 0x40) \
781             eventp->bstate = MASK_RELEASE(n)
782 #else
783 #define PRESS_POSITION(n) \
784         eventp->bstate = (prev & MASK_PRESS(n) \
785                         ? REPORT_MOUSE_POSITION \
786                         : MASK_PRESS(n))
787 #endif
788
789         switch (kbuf[0] & 0x3) {
790         case 0x0:
791             if (kbuf[0] & 64)
792                 eventp->bstate = MASK_PRESS(4);
793             else
794                 PRESS_POSITION(1);
795             break;
796
797         case 0x1:
798 #if NCURSES_MOUSE_VERSION == 2
799             if (kbuf[0] & 64)
800                 eventp->bstate = MASK_PRESS(5);
801             else
802 #endif
803                 PRESS_POSITION(2);
804             break;
805
806         case 0x2:
807             PRESS_POSITION(3);
808             break;
809
810         case 0x3:
811             /*
812              * Release events aren't reported for individual buttons, just for
813              * the button set as a whole.  However, because there are normally
814              * no mouse events under xterm that intervene between press and
815              * release, we can infer the button actually released by looking at
816              * the previous event.
817              */
818             if (prev & (BUTTON_PRESSED | BUTTON_RELEASED)) {
819                 eventp->bstate = BUTTON_RELEASED;
820                 for (b = 1; b <= MAX_BUTTONS; ++b) {
821                     if (!(prev & MASK_PRESS(b)))
822                         eventp->bstate &= ~MASK_RELEASE(b);
823                 }
824             } else {
825                 /*
826                  * XFree86 xterm will return a stream of release-events to
827                  * let the application know where the mouse is going, if the
828                  * private mode 1002 or 1003 is enabled.
829                  */
830                 eventp->bstate = REPORT_MOUSE_POSITION;
831             }
832             break;
833         }
834         result = (eventp->bstate & REPORT_MOUSE_POSITION) ? TRUE : FALSE;
835
836         if (kbuf[0] & 4) {
837             eventp->bstate |= BUTTON_SHIFT;
838         }
839         if (kbuf[0] & 8) {
840             eventp->bstate |= BUTTON_ALT;
841         }
842         if (kbuf[0] & 16) {
843             eventp->bstate |= BUTTON_CTRL;
844         }
845
846         eventp->x = (kbuf[1] - ' ') - 1;
847         eventp->y = (kbuf[2] - ' ') - 1;
848         TR(MY_TRACE,
849            ("_nc_mouse_inline: primitive mouse-event %s has slot %ld",
850             _tracemouse(eventp),
851             (long) (eventp - SP->_mouse_events)));
852
853         /* bump the next-free pointer into the circular list */
854         SP->_mouse_eventp = NEXT(eventp);
855 #if 0                           /* this return would be needed for QNX's mods to lib_getch.c */
856         return (TRUE);
857 #endif
858     }
859
860     return (result);
861 }
862
863 static void
864 mouse_activate(bool on)
865 {
866     if (!on && !SP->_mouse_initialized)
867         return;
868
869     if (!_nc_mouse_init())
870         return;
871
872     if (on) {
873
874         switch (SP->_mouse_type) {
875         case M_XTERM:
876 #if NCURSES_EXT_FUNCS
877             keyok(KEY_MOUSE, on);
878 #endif
879             TPUTS_TRACE("xterm mouse initialization");
880             enable_xterm_mouse(1);
881             break;
882 #if USE_GPM_SUPPORT
883         case M_GPM:
884             if (enable_gpm_mouse(1)) {
885                 SP->_mouse_fd = *(my_gpm_fd);
886                 T(("GPM mouse_fd %d", SP->_mouse_fd));
887             }
888             break;
889 #endif
890 #if USE_SYSMOUSE
891         case M_SYSMOUSE:
892             signal(SIGUSR2, handle_sysmouse);
893             SP->_mouse_active = TRUE;
894             break;
895 #endif
896         case M_NONE:
897             return;
898         }
899         /* Make runtime binding to cut down on object size of applications that
900          * do not use the mouse (e.g., 'clear').
901          */
902         SP->_mouse_event = _nc_mouse_event;
903         SP->_mouse_inline = _nc_mouse_inline;
904         SP->_mouse_parse = _nc_mouse_parse;
905         SP->_mouse_resume = _nc_mouse_resume;
906         SP->_mouse_wrap = _nc_mouse_wrap;
907     } else {
908
909         switch (SP->_mouse_type) {
910         case M_XTERM:
911             TPUTS_TRACE("xterm mouse deinitialization");
912             enable_xterm_mouse(0);
913             break;
914 #if USE_GPM_SUPPORT
915         case M_GPM:
916             enable_gpm_mouse(0);
917             break;
918 #endif
919 #if USE_SYSMOUSE
920         case M_SYSMOUSE:
921             signal(SIGUSR2, SIG_IGN);
922             SP->_mouse_active = FALSE;
923             break;
924 #endif
925         case M_NONE:
926             return;
927         }
928     }
929     _nc_flush();
930 }
931
932 /**************************************************************************
933  *
934  * Device-independent code
935  *
936  **************************************************************************/
937
938 static bool
939 _nc_mouse_parse(int runcount)
940 /* parse a run of atomic mouse events into a gesture */
941 {
942     MEVENT *eventp = SP->_mouse_eventp;
943     MEVENT *ep, *runp, *next, *prev = PREV(eventp);
944     int n;
945     int b;
946     bool merge;
947
948     TR(MY_TRACE, ("_nc_mouse_parse(%d) called", runcount));
949
950     /*
951      * When we enter this routine, the event list next-free pointer
952      * points just past a run of mouse events that we know were separated
953      * in time by less than the critical click interval. The job of this
954      * routine is to collapse this run into a single higher-level event
955      * or gesture.
956      *
957      * We accomplish this in two passes.  The first pass merges press/release
958      * pairs into click events.  The second merges runs of click events into
959      * double or triple-click events.
960      *
961      * It's possible that the run may not resolve to a single event (for
962      * example, if the user quadruple-clicks).  If so, leading events
963      * in the run are ignored.
964      *
965      * Note that this routine is independent of the format of the specific
966      * format of the pointing-device's reports.  We can use it to parse
967      * gestures on anything that reports press/release events on a per-
968      * button basis, as long as the device-dependent mouse code puts stuff
969      * on the queue in MEVENT format.
970      */
971     if (runcount == 1) {
972         TR(MY_TRACE,
973            ("_nc_mouse_parse: returning simple mouse event %s at slot %ld",
974             _tracemouse(prev),
975             (long) (prev - SP->_mouse_events)));
976         return (prev->id >= NORMAL_EVENT)
977             ? ((prev->bstate & SP->_mouse_mask) ? TRUE : FALSE)
978             : FALSE;
979     }
980
981     /* find the start of the run */
982     runp = eventp;
983     for (n = runcount; n > 0; n--) {
984         runp = PREV(runp);
985     }
986
987 #ifdef TRACE
988     if (USE_TRACEF(TRACE_IEVENT)) {
989         _trace_slot("before mouse press/release merge:");
990         _tracef("_nc_mouse_parse: run starts at %ld, ends at %ld, count %d",
991                 (long) (runp - SP->_mouse_events),
992                 (long) ((eventp - SP->_mouse_events) + (EV_MAX - 1)) % EV_MAX,
993                 runcount);
994         _nc_unlock_global(tracef);
995     }
996 #endif /* TRACE */
997
998     /* first pass; merge press/release pairs */
999     do {
1000         merge = FALSE;
1001         for (ep = runp; (next = NEXT(ep)) != eventp; ep = next) {
1002
1003 #define MASK_CHANGED(x) (!(ep->bstate & MASK_PRESS(x)) \
1004                       == !(next->bstate & MASK_RELEASE(x)))
1005
1006             if (ep->x == next->x && ep->y == next->y
1007                 && (ep->bstate & BUTTON_PRESSED)
1008                 && MASK_CHANGED(1)
1009                 && MASK_CHANGED(2)
1010                 && MASK_CHANGED(3)
1011                 && MASK_CHANGED(4)
1012 #if NCURSES_MOUSE_VERSION == 2
1013                 && MASK_CHANGED(5)
1014 #endif
1015                 ) {
1016                 for (b = 1; b <= MAX_BUTTONS; ++b) {
1017                     if ((SP->_mouse_mask & MASK_CLICK(b))
1018                         && (ep->bstate & MASK_PRESS(b))) {
1019                         ep->bstate &= ~MASK_PRESS(b);
1020                         ep->bstate |= MASK_CLICK(b);
1021                         merge = TRUE;
1022                     }
1023                 }
1024                 if (merge)
1025                     next->id = INVALID_EVENT;
1026             }
1027         }
1028     } while
1029         (merge);
1030
1031 #ifdef TRACE
1032     if (USE_TRACEF(TRACE_IEVENT)) {
1033         _trace_slot("before mouse click merge:");
1034         _tracef("_nc_mouse_parse: run starts at %ld, ends at %ld, count %d",
1035                 (long) (runp - SP->_mouse_events),
1036                 (long) ((eventp - SP->_mouse_events) + (EV_MAX - 1)) % EV_MAX,
1037                 runcount);
1038         _nc_unlock_global(tracef);
1039     }
1040 #endif /* TRACE */
1041
1042     /*
1043      * Second pass; merge click runs.  At this point, click events are
1044      * each followed by one invalid event. We merge click events
1045      * forward in the queue.
1046      *
1047      * NOTE: There is a problem with this design!  If the application
1048      * allows enough click events to pile up in the circular queue so
1049      * they wrap around, it will cheerfully merge the newest forward
1050      * into the oldest, creating a bogus doubleclick and confusing
1051      * the queue-traversal logic rather badly.  Generally this won't
1052      * happen, because calling getmouse() marks old events invalid and
1053      * ineligible for merges.  The true solution to this problem would
1054      * be to timestamp each MEVENT and perform the obvious sanity check,
1055      * but the timer element would have to have sub-second resolution,
1056      * which would get us into portability trouble.
1057      */
1058     do {
1059         MEVENT *follower;
1060
1061         merge = FALSE;
1062         for (ep = runp; (next = NEXT(ep)) != eventp; ep = next)
1063             if (ep->id != INVALID_EVENT) {
1064                 if (next->id != INVALID_EVENT)
1065                     continue;
1066                 follower = NEXT(next);
1067                 if (follower->id == INVALID_EVENT)
1068                     continue;
1069
1070                 /* merge click events forward */
1071                 if ((ep->bstate & BUTTON_CLICKED)
1072                     && (follower->bstate & BUTTON_CLICKED)) {
1073                     for (b = 1; b <= MAX_BUTTONS; ++b) {
1074                         if ((SP->_mouse_mask & MASK_DOUBLE_CLICK(b))
1075                             && (follower->bstate & MASK_CLICK(b))) {
1076                             follower->bstate &= ~MASK_CLICK(b);
1077                             follower->bstate |= MASK_DOUBLE_CLICK(b);
1078                             merge = TRUE;
1079                         }
1080                     }
1081                     if (merge)
1082                         ep->id = INVALID_EVENT;
1083                 }
1084
1085                 /* merge double-click events forward */
1086                 if ((ep->bstate & BUTTON_DOUBLE_CLICKED)
1087                     && (follower->bstate & BUTTON_CLICKED)) {
1088                     for (b = 1; b <= MAX_BUTTONS; ++b) {
1089                         if ((SP->_mouse_mask & MASK_TRIPLE_CLICK(b))
1090                             && (follower->bstate & MASK_CLICK(b))) {
1091                             follower->bstate &= ~MASK_CLICK(b);
1092                             follower->bstate |= MASK_TRIPLE_CLICK(b);
1093                             merge = TRUE;
1094                         }
1095                     }
1096                     if (merge)
1097                         ep->id = INVALID_EVENT;
1098                 }
1099             }
1100     } while
1101         (merge);
1102
1103 #ifdef TRACE
1104     if (USE_TRACEF(TRACE_IEVENT)) {
1105         _trace_slot("before mouse event queue compaction:");
1106         _tracef("_nc_mouse_parse: run starts at %ld, ends at %ld, count %d",
1107                 (long) (runp - SP->_mouse_events),
1108                 (long) ((eventp - SP->_mouse_events) + (EV_MAX - 1)) % EV_MAX,
1109                 runcount);
1110         _nc_unlock_global(tracef);
1111     }
1112 #endif /* TRACE */
1113
1114     /*
1115      * Now try to throw away trailing events flagged invalid, or that
1116      * don't match the current event mask.
1117      */
1118     for (; runcount; prev = PREV(eventp), runcount--)
1119         if (prev->id == INVALID_EVENT || !(prev->bstate & SP->_mouse_mask)) {
1120             SP->_mouse_eventp = eventp = prev;
1121         }
1122 #ifdef TRACE
1123     if (USE_TRACEF(TRACE_IEVENT)) {
1124         _trace_slot("after mouse event queue compaction:");
1125         _tracef("_nc_mouse_parse: run starts at %ld, ends at %ld, count %d",
1126                 (long) (runp - SP->_mouse_events),
1127                 (long) ((eventp - SP->_mouse_events) + (EV_MAX - 1)) % EV_MAX,
1128                 runcount);
1129         _nc_unlock_global(tracef);
1130     }
1131     for (ep = runp; ep != eventp; ep = NEXT(ep))
1132         if (ep->id != INVALID_EVENT)
1133             TR(MY_TRACE,
1134                ("_nc_mouse_parse: returning composite mouse event %s at slot %ld",
1135                 _tracemouse(ep),
1136                 (long) (ep - SP->_mouse_events)));
1137 #endif /* TRACE */
1138
1139     /* after all this, do we have a valid event? */
1140     return (PREV(eventp)->id != INVALID_EVENT);
1141 }
1142
1143 static void
1144 _nc_mouse_wrap(SCREEN *sp GCC_UNUSED)
1145 /* release mouse -- called by endwin() before shellout/exit */
1146 {
1147     TR(MY_TRACE, ("_nc_mouse_wrap() called"));
1148
1149     switch (SP->_mouse_type) {
1150     case M_XTERM:
1151         if (SP->_mouse_mask)
1152             mouse_activate(FALSE);
1153         break;
1154 #if USE_GPM_SUPPORT
1155         /* GPM: pass all mouse events to next client */
1156     case M_GPM:
1157         if (SP->_mouse_mask)
1158             mouse_activate(FALSE);
1159         break;
1160 #endif
1161 #if USE_SYSMOUSE
1162     case M_SYSMOUSE:
1163         mouse_activate(FALSE);
1164         break;
1165 #endif
1166     case M_NONE:
1167         break;
1168     }
1169 }
1170
1171 static void
1172 _nc_mouse_resume(SCREEN *sp GCC_UNUSED)
1173 /* re-connect to mouse -- called by doupdate() after shellout */
1174 {
1175     TR(MY_TRACE, ("_nc_mouse_resume() called"));
1176
1177     switch (SP->_mouse_type) {
1178     case M_XTERM:
1179         /* xterm: re-enable reporting */
1180         if (SP->_mouse_mask)
1181             mouse_activate(TRUE);
1182         break;
1183
1184 #if USE_GPM_SUPPORT
1185     case M_GPM:
1186         /* GPM: reclaim our event set */
1187         if (SP->_mouse_mask)
1188             mouse_activate(TRUE);
1189         break;
1190 #endif
1191
1192 #if USE_SYSMOUSE
1193     case M_SYSMOUSE:
1194         mouse_activate(TRUE);
1195         break;
1196 #endif
1197     case M_NONE:
1198         break;
1199     }
1200 }
1201
1202 /**************************************************************************
1203  *
1204  * Mouse interface entry points for the API
1205  *
1206  **************************************************************************/
1207
1208 NCURSES_EXPORT(int)
1209 getmouse(MEVENT * aevent)
1210 /* grab a copy of the current mouse event */
1211 {
1212     T((T_CALLED("getmouse(%p)"), aevent));
1213
1214     if ((aevent != 0) && (SP != 0) && (SP->_mouse_type != M_NONE)) {
1215         MEVENT *eventp = SP->_mouse_eventp;
1216         /* compute the current-event pointer */
1217         MEVENT *prev = PREV(eventp);
1218
1219         /* copy the event we find there */
1220         *aevent = *prev;
1221
1222         TR(TRACE_IEVENT, ("getmouse: returning event %s from slot %ld",
1223                           _tracemouse(prev),
1224                           (long) (prev - SP->_mouse_events)));
1225
1226         prev->id = INVALID_EVENT;       /* so the queue slot becomes free */
1227         returnCode(OK);
1228     }
1229     returnCode(ERR);
1230 }
1231
1232 NCURSES_EXPORT(int)
1233 ungetmouse(MEVENT * aevent)
1234 /* enqueue a synthesized mouse event to be seen by the next wgetch() */
1235 {
1236     int result = ERR;
1237
1238     T((T_CALLED("ungetmouse(%p)"), aevent));
1239
1240     if (aevent != 0 && SP != 0) {
1241         MEVENT *eventp = SP->_mouse_eventp;
1242
1243         /* stick the given event in the next-free slot */
1244         *eventp = *aevent;
1245
1246         /* bump the next-free pointer into the circular list */
1247         SP->_mouse_eventp = NEXT(eventp);
1248
1249         /* push back the notification event on the keyboard queue */
1250         result = ungetch(KEY_MOUSE);
1251     }
1252     returnCode(result);
1253 }
1254
1255 NCURSES_EXPORT(mmask_t)
1256 mousemask(mmask_t newmask, mmask_t * oldmask)
1257 /* set the mouse event mask */
1258 {
1259     mmask_t result = 0;
1260
1261     T((T_CALLED("mousemask(%#lx,%p)"), (unsigned long) newmask, oldmask));
1262
1263     if (SP != 0) {
1264         if (oldmask)
1265             *oldmask = SP->_mouse_mask;
1266
1267         if (newmask || SP->_mouse_initialized) {
1268             _nc_mouse_init();
1269             if (SP->_mouse_type != M_NONE) {
1270                 result = newmask &
1271                     (REPORT_MOUSE_POSITION
1272                      | BUTTON_ALT
1273                      | BUTTON_CTRL
1274                      | BUTTON_SHIFT
1275                      | BUTTON_PRESSED
1276                      | BUTTON_RELEASED
1277                      | BUTTON_CLICKED
1278                      | BUTTON_DOUBLE_CLICKED
1279                      | BUTTON_TRIPLE_CLICKED);
1280
1281                 mouse_activate((bool) (result != 0));
1282
1283                 SP->_mouse_mask = result;
1284             }
1285         }
1286     } else {
1287         if (oldmask)
1288             *oldmask = SP->_mouse_mask;
1289     }
1290     returnBits(result);
1291 }
1292
1293 NCURSES_EXPORT(bool)
1294 wenclose(const WINDOW *win, int y, int x)
1295 /* check to see if given window encloses given screen location */
1296 {
1297     bool result = FALSE;
1298
1299     T((T_CALLED("wenclose(%p,%d,%d)"), win, y, x));
1300
1301     if (win != 0) {
1302         y -= win->_yoffset;
1303         result = ((win->_begy <= y &&
1304                    win->_begx <= x &&
1305                    (win->_begx + win->_maxx) >= x &&
1306                    (win->_begy + win->_maxy) >= y) ? TRUE : FALSE);
1307     }
1308     returnBool(result);
1309 }
1310
1311 NCURSES_EXPORT(int)
1312 mouseinterval(int maxclick)
1313 /* set the maximum mouse interval within which to recognize a click */
1314 {
1315     int oldval;
1316
1317     T((T_CALLED("mouseinterval(%d)"), maxclick));
1318
1319     if (SP != 0) {
1320         oldval = SP->_maxclick;
1321         if (maxclick >= 0)
1322             SP->_maxclick = maxclick;
1323     } else {
1324         oldval = DEFAULT_MAXCLICK;
1325     }
1326
1327     returnCode(oldval);
1328 }
1329
1330 /* This may be used by other routines to ask for the existence of mouse
1331    support */
1332 NCURSES_EXPORT(int)
1333 _nc_has_mouse(void)
1334 {
1335     return (SP->_mouse_type == M_NONE ? 0 : 1);
1336 }
1337
1338 NCURSES_EXPORT(bool)
1339 wmouse_trafo(const WINDOW *win, int *pY, int *pX, bool to_screen)
1340 {
1341     bool result = FALSE;
1342
1343     T((T_CALLED("wmouse_trafo(%p,%p,%p,%d)"), win, pY, pX, to_screen));
1344
1345     if (win && pY && pX) {
1346         int y = *pY;
1347         int x = *pX;
1348
1349         if (to_screen) {
1350             y += win->_begy + win->_yoffset;
1351             x += win->_begx;
1352             if (wenclose(win, y, x))
1353                 result = TRUE;
1354         } else {
1355             if (wenclose(win, y, x)) {
1356                 y -= (win->_begy + win->_yoffset);
1357                 x -= win->_begx;
1358                 result = TRUE;
1359             }
1360         }
1361         if (result) {
1362             *pX = x;
1363             *pY = y;
1364         }
1365     }
1366     returnBool(result);
1367 }