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