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