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