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