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