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