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