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