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