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