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