xref: /freebsd/usr.sbin/moused/moused.c (revision 83409a93)
1 /**
2  ** SPDX-License-Identifier: BSD-4-Clause
3  **
4  ** Copyright (c) 1995 Michael Smith, All rights reserved.
5  **
6  ** Redistribution and use in source and binary forms, with or without
7  ** modification, are permitted provided that the following conditions
8  ** are met:
9  ** 1. Redistributions of source code must retain the above copyright
10  **    notice, this list of conditions and the following disclaimer as
11  **    the first lines of this file unmodified.
12  ** 2. Redistributions in binary form must reproduce the above copyright
13  **    notice, this list of conditions and the following disclaimer in the
14  **    documentation and/or other materials provided with the distribution.
15  ** 3. All advertising materials mentioning features or use of this software
16  **    must display the following acknowledgment:
17  **      This product includes software developed by Michael Smith.
18  ** 4. The name of the author may not be used to endorse or promote products
19  **    derived from this software without specific prior written permission.
20  **
21  **
22  ** THIS SOFTWARE IS PROVIDED BY Michael Smith ``AS IS'' AND ANY
23  ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  ** PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Michael Smith BE LIABLE FOR
26  ** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  ** CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  ** SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
29  ** BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
30  ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
31  ** OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
32  ** EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  **
34  **/
35 
36 /**
37  ** MOUSED.C
38  **
39  ** Mouse daemon : listens to a serial port, the bus mouse interface, or
40  ** the PS/2 mouse port for mouse data stream, interprets data and passes
41  ** ioctls off to the console driver.
42  **
43  ** The mouse interface functions are derived closely from the mouse
44  ** handler in the XFree86 X server.  Many thanks to the XFree86 people
45  ** for their great work!
46  **
47  **/
48 
49 #include <sys/param.h>
50 #include <sys/consio.h>
51 #include <sys/mouse.h>
52 #include <sys/socket.h>
53 #include <sys/stat.h>
54 #include <sys/time.h>
55 #include <sys/un.h>
56 
57 #include <ctype.h>
58 #include <err.h>
59 #include <errno.h>
60 #include <fcntl.h>
61 #include <libutil.h>
62 #include <limits.h>
63 #include <setjmp.h>
64 #include <signal.h>
65 #include <stdarg.h>
66 #include <stdint.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <syslog.h>
71 #include <termios.h>
72 #include <unistd.h>
73 #include <math.h>
74 
75 #define MAX_CLICKTHRESHOLD	2000	/* 2 seconds */
76 #define MAX_BUTTON2TIMEOUT	2000	/* 2 seconds */
77 #define DFLT_CLICKTHRESHOLD	 500	/* 0.5 second */
78 #define DFLT_BUTTON2TIMEOUT	 100	/* 0.1 second */
79 #define DFLT_SCROLLTHRESHOLD	   3	/* 3 pixels */
80 #define DFLT_SCROLLSPEED	   2	/* 2 pixels */
81 
82 /* Abort 3-button emulation delay after this many movement events. */
83 #define BUTTON2_MAXMOVE	3
84 
85 #define TRUE		1
86 #define FALSE		0
87 
88 #define MOUSE_XAXIS	(-1)
89 #define MOUSE_YAXIS	(-2)
90 
91 /* Logitech PS2++ protocol */
92 #define MOUSE_PS2PLUS_CHECKBITS(b)	\
93 			((((b[2] & 0x03) << 2) | 0x02) == (b[1] & 0x0f))
94 #define MOUSE_PS2PLUS_PACKET_TYPE(b)	\
95 			(((b[0] & 0x30) >> 2) | ((b[1] & 0x30) >> 4))
96 
97 #define	ChordMiddle	0x0001
98 #define Emulate3Button	0x0002
99 #define ClearDTR	0x0004
100 #define ClearRTS	0x0008
101 #define NoPnP		0x0010
102 #define VirtualScroll	0x0020
103 #define HVirtualScroll	0x0040
104 #define ExponentialAcc	0x0080
105 
106 #define ID_NONE		0
107 #define ID_PORT		1
108 #define ID_IF		2
109 #define ID_TYPE		4
110 #define ID_MODEL	8
111 #define ID_ALL		(ID_PORT | ID_IF | ID_TYPE | ID_MODEL)
112 
113 /* Operations on timespecs */
114 #define	tsclr(tvp)	((tvp)->tv_sec = (tvp)->tv_nsec = 0)
115 #define	tscmp(tvp, uvp, cmp)						\
116 	(((tvp)->tv_sec == (uvp)->tv_sec) ?				\
117 	    ((tvp)->tv_nsec cmp (uvp)->tv_nsec) :			\
118 	    ((tvp)->tv_sec cmp (uvp)->tv_sec))
119 #define	tssub(tvp, uvp, vvp)						\
120 	do {								\
121 		(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;		\
122 		(vvp)->tv_nsec = (tvp)->tv_nsec - (uvp)->tv_nsec;	\
123 		if ((vvp)->tv_nsec < 0) {				\
124 			(vvp)->tv_sec--;				\
125 			(vvp)->tv_nsec += 1000000000;			\
126 		}							\
127 	} while (0)
128 
129 #define debug(...) do {						\
130 	if (debug && nodaemon)					\
131 		warnx(__VA_ARGS__);				\
132 } while (0)
133 
134 #define logerr(e, ...) do {					\
135 	log_or_warn(LOG_DAEMON | LOG_ERR, errno, __VA_ARGS__);	\
136 	exit(e);						\
137 } while (0)
138 
139 #define logerrx(e, ...) do {					\
140 	log_or_warn(LOG_DAEMON | LOG_ERR, 0, __VA_ARGS__);	\
141 	exit(e);						\
142 } while (0)
143 
144 #define logwarn(...)						\
145 	log_or_warn(LOG_DAEMON | LOG_WARNING, errno, __VA_ARGS__)
146 
147 #define logwarnx(...)						\
148 	log_or_warn(LOG_DAEMON | LOG_WARNING, 0, __VA_ARGS__)
149 
150 /* structures */
151 
152 /* symbol table entry */
153 typedef struct {
154     const char *name;
155     int val;
156     int val2;
157 } symtab_t;
158 
159 /* serial PnP ID string */
160 typedef struct {
161     int revision;	/* PnP revision, 100 for 1.00 */
162     const char *eisaid;	/* EISA ID including mfr ID and product ID */
163     char *serial;	/* serial No, optional */
164     const char *class;	/* device class, optional */
165     char *compat;	/* list of compatible drivers, optional */
166     char *description;	/* product description, optional */
167     int neisaid;	/* length of the above fields... */
168     int nserial;
169     int nclass;
170     int ncompat;
171     int ndescription;
172 } pnpid_t;
173 
174 /* global variables */
175 
176 static int	debug = 0;
177 static int	nodaemon = FALSE;
178 static int	background = FALSE;
179 static int	paused = FALSE;
180 static int	identify = ID_NONE;
181 static int	extioctl = FALSE;
182 static const char *pidfile = "/var/run/moused.pid";
183 static struct pidfh *pfh;
184 
185 #define SCROLL_NOTSCROLLING	0
186 #define SCROLL_PREPARE		1
187 #define SCROLL_SCROLLING	2
188 
189 static int	scroll_state;
190 static int	scroll_movement;
191 static int	hscroll_movement;
192 
193 /* local variables */
194 
195 /* interface (the table must be ordered by MOUSE_IF_XXX in mouse.h) */
196 static symtab_t rifs[] = {
197     { "serial",		MOUSE_IF_SERIAL,	0 },
198     { "ps/2",		MOUSE_IF_PS2,		0 },
199     { "sysmouse",	MOUSE_IF_SYSMOUSE,	0 },
200     { "usb",		MOUSE_IF_USB,		0 },
201     { NULL,		MOUSE_IF_UNKNOWN,	0 },
202 };
203 
204 /* types (the table must be ordered by MOUSE_PROTO_XXX in mouse.h) */
205 static const char *rnames[] = {
206     "microsoft",
207     "mousesystems",
208     "logitech",
209     "mmseries",
210     "mouseman",
211     "wasbusmouse",
212     "wasinportmouse",
213     "ps/2",
214     "mmhitab",
215     "glidepoint",
216     "intellimouse",
217     "thinkingmouse",
218     "sysmouse",
219     "x10mouseremote",
220     "kidspad",
221     "versapad",
222     "jogdial",
223 #if notyet
224     "mariqua",
225 #endif
226     "gtco_digipad",
227     NULL
228 };
229 
230 /* models */
231 static symtab_t	rmodels[] = {
232     { "NetScroll",		MOUSE_MODEL_NETSCROLL,		0 },
233     { "NetMouse/NetScroll Optical", MOUSE_MODEL_NET,		0 },
234     { "GlidePoint",		MOUSE_MODEL_GLIDEPOINT,		0 },
235     { "ThinkingMouse",		MOUSE_MODEL_THINK,		0 },
236     { "IntelliMouse",		MOUSE_MODEL_INTELLI,		0 },
237     { "EasyScroll/SmartScroll",	MOUSE_MODEL_EASYSCROLL,		0 },
238     { "MouseMan+",		MOUSE_MODEL_MOUSEMANPLUS,	0 },
239     { "Kidspad",		MOUSE_MODEL_KIDSPAD,		0 },
240     { "VersaPad",		MOUSE_MODEL_VERSAPAD,		0 },
241     { "IntelliMouse Explorer",	MOUSE_MODEL_EXPLORER,		0 },
242     { "4D Mouse",		MOUSE_MODEL_4D,			0 },
243     { "4D+ Mouse",		MOUSE_MODEL_4DPLUS,		0 },
244     { "Synaptics Touchpad",	MOUSE_MODEL_SYNAPTICS,		0 },
245     { "TrackPoint",		MOUSE_MODEL_TRACKPOINT,		0 },
246     { "Elantech Touchpad",	MOUSE_MODEL_ELANTECH,		0 },
247     { "generic",		MOUSE_MODEL_GENERIC,		0 },
248     { NULL,			MOUSE_MODEL_UNKNOWN,		0 },
249 };
250 
251 /* PnP EISA/product IDs */
252 static symtab_t pnpprod[] = {
253     /* Kensignton ThinkingMouse */
254     { "KML0001",	MOUSE_PROTO_THINK,	MOUSE_MODEL_THINK },
255     /* MS IntelliMouse */
256     { "MSH0001",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_INTELLI },
257     /* MS IntelliMouse TrackBall */
258     { "MSH0004",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_INTELLI },
259     /* Tremon Wheel Mouse MUSD */
260     { "HTK0001",        MOUSE_PROTO_INTELLI,    MOUSE_MODEL_INTELLI },
261     /* Genius PnP Mouse */
262     { "KYE0001",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
263     /* MouseSystems SmartScroll Mouse (OEM from Genius?) */
264     { "KYE0002",	MOUSE_PROTO_MS,		MOUSE_MODEL_EASYSCROLL },
265     /* Genius NetMouse */
266     { "KYE0003",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_NET },
267     /* Genius Kidspad, Easypad and other tablets */
268     { "KYE0005",	MOUSE_PROTO_KIDSPAD,	MOUSE_MODEL_KIDSPAD },
269     /* Genius EZScroll */
270     { "KYEEZ00",	MOUSE_PROTO_MS,		MOUSE_MODEL_EASYSCROLL },
271     /* Logitech Cordless MouseMan Wheel */
272     { "LGI8033",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_MOUSEMANPLUS },
273     /* Logitech MouseMan (new 4 button model) */
274     { "LGI800C",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_MOUSEMANPLUS },
275     /* Logitech MouseMan+ */
276     { "LGI8050",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_MOUSEMANPLUS },
277     /* Logitech FirstMouse+ */
278     { "LGI8051",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_MOUSEMANPLUS },
279     /* Logitech serial */
280     { "LGI8001",	MOUSE_PROTO_LOGIMOUSEMAN, MOUSE_MODEL_GENERIC },
281     /* A4 Tech 4D/4D+ Mouse */
282     { "A4W0005",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_4D },
283     /* 8D Scroll Mouse */
284     { "PEC9802",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_INTELLI },
285     /* Mitsumi Wireless Scroll Mouse */
286     { "MTM6401",	MOUSE_PROTO_INTELLI,	MOUSE_MODEL_INTELLI },
287 
288     /* MS serial */
289     { "PNP0F01",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
290     /* MS PS/2 */
291     { "PNP0F03",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
292     /*
293      * EzScroll returns PNP0F04 in the compatible device field; but it
294      * doesn't look compatible... XXX
295      */
296     /* MouseSystems */
297     { "PNP0F04",	MOUSE_PROTO_MSC,	MOUSE_MODEL_GENERIC },
298     /* MouseSystems */
299     { "PNP0F05",	MOUSE_PROTO_MSC,	MOUSE_MODEL_GENERIC },
300 #if notyet
301     /* Genius Mouse */
302     { "PNP0F06",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
303     /* Genius Mouse */
304     { "PNP0F07",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
305 #endif
306     /* Logitech serial */
307     { "PNP0F08",	MOUSE_PROTO_LOGIMOUSEMAN, MOUSE_MODEL_GENERIC },
308     /* MS BallPoint serial */
309     { "PNP0F09",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
310     /* MS PnP serial */
311     { "PNP0F0A",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
312     /* MS PnP BallPoint serial */
313     { "PNP0F0B",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
314     /* MS serial compatible */
315     { "PNP0F0C",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
316     /* MS PS/2 compatible */
317     { "PNP0F0E",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
318     /* MS BallPoint compatible */
319     { "PNP0F0F",	MOUSE_PROTO_MS,		MOUSE_MODEL_GENERIC },
320 #if notyet
321     /* TI QuickPort */
322     { "PNP0F10",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
323 #endif
324     /* Logitech PS/2 */
325     { "PNP0F12",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
326     /* PS/2 */
327     { "PNP0F13",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
328 #if notyet
329     /* MS Kids Mouse */
330     { "PNP0F14",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
331 #endif
332 #if notyet
333     /* Logitech SWIFT */
334     { "PNP0F16",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
335 #endif
336     /* Logitech serial compat */
337     { "PNP0F17",	MOUSE_PROTO_LOGIMOUSEMAN, MOUSE_MODEL_GENERIC },
338     /* Logitech PS/2 compatible */
339     { "PNP0F19",	MOUSE_PROTO_PS2,	MOUSE_MODEL_GENERIC },
340 #if notyet
341     /* Logitech SWIFT compatible */
342     { "PNP0F1A",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
343     /* HP Omnibook */
344     { "PNP0F1B",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
345     /* Compaq LTE TrackBall PS/2 */
346     { "PNP0F1C",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
347     /* Compaq LTE TrackBall serial */
348     { "PNP0F1D",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
349     /* MS Kidts Trackball */
350     { "PNP0F1E",	MOUSE_PROTO_XXX,	MOUSE_MODEL_GENERIC },
351 #endif
352     /* Interlink VersaPad */
353     { "LNK0001",	MOUSE_PROTO_VERSAPAD,	MOUSE_MODEL_VERSAPAD },
354 
355     { NULL,		MOUSE_PROTO_UNKNOWN,	MOUSE_MODEL_GENERIC },
356 };
357 
358 /* the table must be ordered by MOUSE_PROTO_XXX in mouse.h */
359 static unsigned short rodentcflags[] =
360 {
361     (CS7	           | CREAD | CLOCAL | HUPCL),	/* MicroSoft */
362     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL),	/* MouseSystems */
363     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL),	/* Logitech */
364     (CS8 | PARENB | PARODD | CREAD | CLOCAL | HUPCL),	/* MMSeries */
365     (CS7		   | CREAD | CLOCAL | HUPCL),	/* MouseMan */
366     0,							/* Bus */
367     0,							/* InPort */
368     0,							/* PS/2 */
369     (CS8		   | CREAD | CLOCAL | HUPCL),	/* MM HitTablet */
370     (CS7	           | CREAD | CLOCAL | HUPCL),	/* GlidePoint */
371     (CS7                   | CREAD | CLOCAL | HUPCL),	/* IntelliMouse */
372     (CS7                   | CREAD | CLOCAL | HUPCL),	/* Thinking Mouse */
373     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL),	/* sysmouse */
374     (CS7	           | CREAD | CLOCAL | HUPCL),	/* X10 MouseRemote */
375     (CS8 | PARENB | PARODD | CREAD | CLOCAL | HUPCL),	/* kidspad etc. */
376     (CS8		   | CREAD | CLOCAL | HUPCL),	/* VersaPad */
377     0,							/* JogDial */
378 #if notyet
379     (CS8 | CSTOPB	   | CREAD | CLOCAL | HUPCL),	/* Mariqua */
380 #endif
381     (CS8		   | CREAD |	      HUPCL ),	/* GTCO Digi-Pad */
382 };
383 
384 static struct rodentparam {
385     int flags;
386     const char *portname;	/* /dev/XXX */
387     int rtype;			/* MOUSE_PROTO_XXX */
388     int level;			/* operation level: 0 or greater */
389     int baudrate;
390     int rate;			/* report rate */
391     int resolution;		/* MOUSE_RES_XXX or a positive number */
392     int zmap[4];		/* MOUSE_{X|Y}AXIS or a button number */
393     int wmode;			/* wheel mode button number */
394     int mfd;			/* mouse file descriptor */
395     int cfd;			/* /dev/consolectl file descriptor */
396     int mremsfd;		/* mouse remote server file descriptor */
397     int mremcfd;		/* mouse remote client file descriptor */
398     int is_removable;		/* set if device is removable, like USB */
399     long clickthreshold;	/* double click speed in msec */
400     long button2timeout;	/* 3 button emulation timeout */
401     mousehw_t hw;		/* mouse device hardware information */
402     mousemode_t mode;		/* protocol information */
403     float accelx;		/* Acceleration in the X axis */
404     float accely;		/* Acceleration in the Y axis */
405     float expoaccel;		/* Exponential acceleration */
406     float expoffset;		/* Movement offset for exponential accel. */
407     float remainx;		/* Remainder on X and Y axis, respectively... */
408     float remainy;		/*    ... to compensate for rounding errors. */
409     int scrollthreshold;	/* Movement distance before virtual scrolling */
410     int scrollspeed;		/* Movement distance to rate of scrolling */
411 } rodent = {
412     .flags = 0,
413     .portname = NULL,
414     .rtype = MOUSE_PROTO_UNKNOWN,
415     .level = -1,
416     .baudrate = 1200,
417     .rate = 0,
418     .resolution = MOUSE_RES_UNKNOWN,
419     .zmap = { 0, 0, 0, 0 },
420     .wmode = 0,
421     .mfd = -1,
422     .cfd = -1,
423     .mremsfd = -1,
424     .mremcfd = -1,
425     .is_removable = 0,
426     .clickthreshold = DFLT_CLICKTHRESHOLD,
427     .button2timeout = DFLT_BUTTON2TIMEOUT,
428     .accelx = 1.0,
429     .accely = 1.0,
430     .expoaccel = 1.0,
431     .expoffset = 1.0,
432     .remainx = 0.0,
433     .remainy = 0.0,
434     .scrollthreshold = DFLT_SCROLLTHRESHOLD,
435     .scrollspeed = DFLT_SCROLLSPEED,
436 };
437 
438 /* button status */
439 struct button_state {
440     int count;		/* 0: up, 1: single click, 2: double click,... */
441     struct timespec ts;	/* timestamp on the last button event */
442 };
443 static struct button_state	bstate[MOUSE_MAXBUTTON];	/* button state */
444 static struct button_state	*mstate[MOUSE_MAXBUTTON];/* mapped button st.*/
445 static struct button_state	zstate[4];		 /* Z/W axis state */
446 
447 /* state machine for 3 button emulation */
448 
449 #define S0	0	/* start */
450 #define S1	1	/* button 1 delayed down */
451 #define S2	2	/* button 3 delayed down */
452 #define S3	3	/* both buttons down -> button 2 down */
453 #define S4	4	/* button 1 delayed up */
454 #define S5	5	/* button 1 down */
455 #define S6	6	/* button 3 down */
456 #define S7	7	/* both buttons down */
457 #define S8	8	/* button 3 delayed up */
458 #define S9	9	/* button 1 or 3 up after S3 */
459 
460 #define A(b1, b3)	(((b1) ? 2 : 0) | ((b3) ? 1 : 0))
461 #define A_TIMEOUT	4
462 #define S_DELAYED(st)	(states[st].s[A_TIMEOUT] != (st))
463 
464 static struct {
465     int s[A_TIMEOUT + 1];
466     int buttons;
467     int mask;
468     int timeout;
469 } states[10] = {
470     /* S0 */
471     { { S0, S2, S1, S3, S0 }, 0, ~(MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN), FALSE },
472     /* S1 */
473     { { S4, S2, S1, S3, S5 }, 0, ~MOUSE_BUTTON1DOWN, FALSE },
474     /* S2 */
475     { { S8, S2, S1, S3, S6 }, 0, ~MOUSE_BUTTON3DOWN, FALSE },
476     /* S3 */
477     { { S0, S9, S9, S3, S3 }, MOUSE_BUTTON2DOWN, ~0, FALSE },
478     /* S4 */
479     { { S0, S2, S1, S3, S0 }, MOUSE_BUTTON1DOWN, ~0, TRUE },
480     /* S5 */
481     { { S0, S2, S5, S7, S5 }, MOUSE_BUTTON1DOWN, ~0, FALSE },
482     /* S6 */
483     { { S0, S6, S1, S7, S6 }, MOUSE_BUTTON3DOWN, ~0, FALSE },
484     /* S7 */
485     { { S0, S6, S5, S7, S7 }, MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN, ~0, FALSE },
486     /* S8 */
487     { { S0, S2, S1, S3, S0 }, MOUSE_BUTTON3DOWN, ~0, TRUE },
488     /* S9 */
489     { { S0, S9, S9, S3, S9 }, 0, ~(MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN), FALSE },
490 };
491 static int		mouse_button_state;
492 static struct timespec	mouse_button_state_ts;
493 static int		mouse_move_delayed;
494 
495 static jmp_buf env;
496 
497 struct drift_xy {
498     int x;
499     int y;
500 };
501 static int		drift_distance = 4;	/* max steps X+Y */
502 static int		drift_time = 500;	/* in 0.5 sec */
503 static struct timespec	drift_time_ts;
504 static struct timespec	drift_2time_ts;		/* 2*drift_time */
505 static int		drift_after = 4000;	/* 4 sec */
506 static struct timespec	drift_after_ts;
507 static int		drift_terminate = FALSE;
508 static struct timespec	drift_current_ts;
509 static struct timespec	drift_tmp;
510 static struct timespec	drift_last_activity = {0, 0};
511 static struct timespec	drift_since = {0, 0};
512 static struct drift_xy	drift_last = {0, 0};	/* steps in last drift_time */
513 static struct drift_xy  drift_previous = {0, 0};	/* steps in prev. drift_time */
514 
515 /* function prototypes */
516 
517 static void	linacc(int, int, int*, int*);
518 static void	expoacc(int, int, int*, int*);
519 static void	moused(void);
520 static void	hup(int sig);
521 static void	cleanup(int sig);
522 static void	pause_mouse(int sig);
523 static void	usage(void);
524 static void	log_or_warn(int log_pri, int errnum, const char *fmt, ...)
525 		    __printflike(3, 4);
526 
527 static int	r_identify(void);
528 static const char *r_if(int type);
529 static const char *r_name(int type);
530 static const char *r_model(int model);
531 static void	r_init(void);
532 static int	r_protocol(u_char b, mousestatus_t *act);
533 static int	r_statetrans(mousestatus_t *a1, mousestatus_t *a2, int trans);
534 static int	r_installmap(char *arg);
535 static void	r_map(mousestatus_t *act1, mousestatus_t *act2);
536 static void	r_timestamp(mousestatus_t *act);
537 static int	r_timeout(void);
538 static void	r_click(mousestatus_t *act);
539 static void	setmousespeed(int old, int new, unsigned cflag);
540 
541 static int	pnpwakeup1(void);
542 static int	pnpwakeup2(void);
543 static int	pnpgets(char *buf);
544 static int	pnpparse(pnpid_t *id, char *buf, int len);
545 static symtab_t	*pnpproto(pnpid_t *id);
546 
547 static symtab_t	*gettoken(symtab_t *tab, const char *s, int len);
548 static const char *gettokenname(symtab_t *tab, int val);
549 
550 static void	mremote_serversetup(void);
551 static void	mremote_clientchg(int add);
552 
553 static int	kidspad(u_char rxc, mousestatus_t *act);
554 static int	gtco_digipad(u_char, mousestatus_t *);
555 
556 int
main(int argc,char * argv[])557 main(int argc, char *argv[])
558 {
559     int c;
560     int	i;
561     int	j;
562 
563     for (i = 0; i < MOUSE_MAXBUTTON; ++i)
564 	mstate[i] = &bstate[i];
565 
566     while ((c = getopt(argc, argv, "3A:C:DE:F:HI:L:PRS:T:VU:a:cdfhi:l:m:p:r:st:w:z:")) != -1)
567 	switch(c) {
568 
569 	case '3':
570 	    rodent.flags |= Emulate3Button;
571 	    break;
572 
573 	case 'E':
574 	    rodent.button2timeout = atoi(optarg);
575 	    if ((rodent.button2timeout < 0) ||
576 		(rodent.button2timeout > MAX_BUTTON2TIMEOUT)) {
577 		warnx("invalid argument `%s'", optarg);
578 		usage();
579 	    }
580 	    break;
581 
582 	case 'a':
583 	    i = sscanf(optarg, "%f,%f", &rodent.accelx, &rodent.accely);
584 	    if (i == 0) {
585 		warnx("invalid linear acceleration argument '%s'", optarg);
586 		usage();
587 	    }
588 
589 	    if (i == 1)
590 		rodent.accely = rodent.accelx;
591 
592 	    break;
593 
594 	case 'A':
595 	    rodent.flags |= ExponentialAcc;
596 	    i = sscanf(optarg, "%f,%f", &rodent.expoaccel, &rodent.expoffset);
597 	    if (i == 0) {
598 		warnx("invalid exponential acceleration argument '%s'", optarg);
599 		usage();
600 	    }
601 
602 	    if (i == 1)
603 		rodent.expoffset = 1.0;
604 
605 	    break;
606 
607 	case 'c':
608 	    rodent.flags |= ChordMiddle;
609 	    break;
610 
611 	case 'd':
612 	    ++debug;
613 	    break;
614 
615 	case 'f':
616 	    nodaemon = TRUE;
617 	    break;
618 
619 	case 'i':
620 	    if (strcmp(optarg, "all") == 0)
621 		identify = ID_ALL;
622 	    else if (strcmp(optarg, "port") == 0)
623 		identify = ID_PORT;
624 	    else if (strcmp(optarg, "if") == 0)
625 		identify = ID_IF;
626 	    else if (strcmp(optarg, "type") == 0)
627 		identify = ID_TYPE;
628 	    else if (strcmp(optarg, "model") == 0)
629 		identify = ID_MODEL;
630 	    else {
631 		warnx("invalid argument `%s'", optarg);
632 		usage();
633 	    }
634 	    nodaemon = TRUE;
635 	    break;
636 
637 	case 'l':
638 	    rodent.level = atoi(optarg);
639 	    if ((rodent.level < 0) || (rodent.level > 4)) {
640 		warnx("invalid argument `%s'", optarg);
641 		usage();
642 	    }
643 	    break;
644 
645 	case 'm':
646 	    if (!r_installmap(optarg)) {
647 		warnx("invalid argument `%s'", optarg);
648 		usage();
649 	    }
650 	    break;
651 
652 	case 'p':
653 	    rodent.portname = optarg;
654 	    break;
655 
656 	case 'r':
657 	    if (strcmp(optarg, "high") == 0)
658 		rodent.resolution = MOUSE_RES_HIGH;
659 	    else if (strcmp(optarg, "medium-high") == 0)
660 		rodent.resolution = MOUSE_RES_HIGH;
661 	    else if (strcmp(optarg, "medium-low") == 0)
662 		rodent.resolution = MOUSE_RES_MEDIUMLOW;
663 	    else if (strcmp(optarg, "low") == 0)
664 		rodent.resolution = MOUSE_RES_LOW;
665 	    else if (strcmp(optarg, "default") == 0)
666 		rodent.resolution = MOUSE_RES_DEFAULT;
667 	    else {
668 		rodent.resolution = atoi(optarg);
669 		if (rodent.resolution <= 0) {
670 		    warnx("invalid argument `%s'", optarg);
671 		    usage();
672 		}
673 	    }
674 	    break;
675 
676 	case 's':
677 	    rodent.baudrate = 9600;
678 	    break;
679 
680 	case 'w':
681 	    i = atoi(optarg);
682 	    if ((i <= 0) || (i > MOUSE_MAXBUTTON)) {
683 		warnx("invalid argument `%s'", optarg);
684 		usage();
685 	    }
686 	    rodent.wmode = 1 << (i - 1);
687 	    break;
688 
689 	case 'z':
690 	    if (strcmp(optarg, "x") == 0)
691 		rodent.zmap[0] = MOUSE_XAXIS;
692 	    else if (strcmp(optarg, "y") == 0)
693 		rodent.zmap[0] = MOUSE_YAXIS;
694 	    else {
695 		i = atoi(optarg);
696 		/*
697 		 * Use button i for negative Z axis movement and
698 		 * button (i + 1) for positive Z axis movement.
699 		 */
700 		if ((i <= 0) || (i > MOUSE_MAXBUTTON - 1)) {
701 		    warnx("invalid argument `%s'", optarg);
702 		    usage();
703 		}
704 		rodent.zmap[0] = i;
705 		rodent.zmap[1] = i + 1;
706 		debug("optind: %d, optarg: '%s'", optind, optarg);
707 		for (j = 1; j < 4; ++j) {
708 		    if ((optind >= argc) || !isdigit(*argv[optind]))
709 			break;
710 		    i = atoi(argv[optind]);
711 		    if ((i <= 0) || (i > MOUSE_MAXBUTTON - 1)) {
712 			warnx("invalid argument `%s'", argv[optind]);
713 			usage();
714 		    }
715 		    rodent.zmap[j] = i;
716 		    ++optind;
717 		}
718 		if ((rodent.zmap[2] != 0) && (rodent.zmap[3] == 0))
719 		    rodent.zmap[3] = rodent.zmap[2] + 1;
720 	    }
721 	    break;
722 
723 	case 'C':
724 	    rodent.clickthreshold = atoi(optarg);
725 	    if ((rodent.clickthreshold < 0) ||
726 		(rodent.clickthreshold > MAX_CLICKTHRESHOLD)) {
727 		warnx("invalid argument `%s'", optarg);
728 		usage();
729 	    }
730 	    break;
731 
732 	case 'D':
733 	    rodent.flags |= ClearDTR;
734 	    break;
735 
736 	case 'F':
737 	    rodent.rate = atoi(optarg);
738 	    if (rodent.rate <= 0) {
739 		warnx("invalid argument `%s'", optarg);
740 		usage();
741 	    }
742 	    break;
743 
744 	case 'H':
745 	    rodent.flags |= HVirtualScroll;
746 	    break;
747 
748 	case 'I':
749 	    pidfile = optarg;
750 	    break;
751 
752 	case 'L':
753 	    rodent.scrollspeed = atoi(optarg);
754 	    if (rodent.scrollspeed < 0) {
755 		warnx("invalid argument `%s'", optarg);
756 		usage();
757 	    }
758 	    break;
759 
760 	case 'P':
761 	    rodent.flags |= NoPnP;
762 	    break;
763 
764 	case 'R':
765 	    rodent.flags |= ClearRTS;
766 	    break;
767 
768 	case 'S':
769 	    rodent.baudrate = atoi(optarg);
770 	    if (rodent.baudrate <= 0) {
771 		warnx("invalid argument `%s'", optarg);
772 		usage();
773 	    }
774 	    debug("rodent baudrate %d", rodent.baudrate);
775 	    break;
776 
777 	case 'T':
778 	    drift_terminate = TRUE;
779 	    sscanf(optarg, "%d,%d,%d", &drift_distance, &drift_time,
780 		&drift_after);
781 	    if (drift_distance <= 0 || drift_time <= 0 || drift_after <= 0) {
782 		warnx("invalid argument `%s'", optarg);
783 		usage();
784 	    }
785 	    debug("terminate drift: distance %d, time %d, after %d",
786 		drift_distance, drift_time, drift_after);
787 	    drift_time_ts.tv_sec = drift_time / 1000;
788 	    drift_time_ts.tv_nsec = (drift_time % 1000) * 1000000;
789  	    drift_2time_ts.tv_sec = (drift_time *= 2) / 1000;
790 	    drift_2time_ts.tv_nsec = (drift_time % 1000) * 1000000;
791 	    drift_after_ts.tv_sec = drift_after / 1000;
792 	    drift_after_ts.tv_nsec = (drift_after % 1000) * 1000000;
793 	    break;
794 
795 	case 't':
796 	    if (strcmp(optarg, "auto") == 0) {
797 		rodent.rtype = MOUSE_PROTO_UNKNOWN;
798 		rodent.flags &= ~NoPnP;
799 		rodent.level = -1;
800 		break;
801 	    }
802 	    for (i = 0; rnames[i] != NULL; i++)
803 		if (strcmp(optarg, rnames[i]) == 0) {
804 		    rodent.rtype = i;
805 		    rodent.flags |= NoPnP;
806 		    rodent.level = (i == MOUSE_PROTO_SYSMOUSE) ? 1 : 0;
807 		    break;
808 		}
809 	    if (rnames[i] == NULL) {
810 		warnx("no such mouse type `%s'", optarg);
811 		usage();
812 	    }
813 	    break;
814 
815 	case 'V':
816 	    rodent.flags |= VirtualScroll;
817 	    break;
818 	case 'U':
819 	    rodent.scrollthreshold = atoi(optarg);
820 	    if (rodent.scrollthreshold < 0) {
821 		warnx("invalid argument `%s'", optarg);
822 		usage();
823 	    }
824 	    break;
825 
826 	case 'h':
827 	case '?':
828 	default:
829 	    usage();
830 	}
831 
832     /* fix Z axis mapping */
833     for (i = 0; i < 4; ++i) {
834 	if (rodent.zmap[i] > 0) {
835 	    for (j = 0; j < MOUSE_MAXBUTTON; ++j) {
836 		if (mstate[j] == &bstate[rodent.zmap[i] - 1])
837 		    mstate[j] = &zstate[i];
838 	    }
839 	    rodent.zmap[i] = 1 << (rodent.zmap[i] - 1);
840 	}
841     }
842 
843     /* the default port name */
844     switch(rodent.rtype) {
845 
846     case MOUSE_PROTO_PS2:
847 	if (!rodent.portname)
848 	    rodent.portname = "/dev/psm0";
849 	break;
850 
851     default:
852 	if (rodent.portname)
853 	    break;
854 	warnx("no port name specified");
855 	usage();
856     }
857 
858     if (strncmp(rodent.portname, "/dev/ums", 8) == 0)
859 	rodent.is_removable = 1;
860 
861     for (;;) {
862 	if (setjmp(env) == 0) {
863 	    signal(SIGHUP, hup);
864 	    signal(SIGINT , cleanup);
865 	    signal(SIGQUIT, cleanup);
866 	    signal(SIGTERM, cleanup);
867 	    signal(SIGUSR1, pause_mouse);
868 
869 	    rodent.mfd = open(rodent.portname, O_RDWR | O_NONBLOCK);
870 	    if (rodent.mfd == -1)
871 		logerr(1, "unable to open %s", rodent.portname);
872 	    if (r_identify() == MOUSE_PROTO_UNKNOWN) {
873 		logwarnx("cannot determine mouse type on %s", rodent.portname);
874 		close(rodent.mfd);
875 		rodent.mfd = -1;
876 	    }
877 
878 	    /* print some information */
879 	    if (identify != ID_NONE) {
880 		if (identify == ID_ALL)
881 		    printf("%s %s %s %s\n",
882 			rodent.portname, r_if(rodent.hw.iftype),
883 			r_name(rodent.rtype), r_model(rodent.hw.model));
884 		else if (identify & ID_PORT)
885 		    printf("%s\n", rodent.portname);
886 		else if (identify & ID_IF)
887 		    printf("%s\n", r_if(rodent.hw.iftype));
888 		else if (identify & ID_TYPE)
889 		    printf("%s\n", r_name(rodent.rtype));
890 		else if (identify & ID_MODEL)
891 		    printf("%s\n", r_model(rodent.hw.model));
892 		exit(0);
893 	    } else {
894 		debug("port: %s  interface: %s  type: %s  model: %s",
895 		    rodent.portname, r_if(rodent.hw.iftype),
896 		    r_name(rodent.rtype), r_model(rodent.hw.model));
897 	    }
898 
899 	    if (rodent.mfd == -1) {
900 		/*
901 		 * We cannot continue because of error.  Exit if the
902 		 * program has not become a daemon.  Otherwise, block
903 		 * until the user corrects the problem and issues SIGHUP.
904 		 */
905 		if (!background)
906 		    exit(1);
907 		sigpause(0);
908 	    }
909 
910 	    r_init();			/* call init function */
911 	    moused();
912 	}
913 
914 	if (rodent.mfd != -1)
915 	    close(rodent.mfd);
916 	if (rodent.cfd != -1)
917 	    close(rodent.cfd);
918 	rodent.mfd = rodent.cfd = -1;
919 	if (rodent.is_removable)
920 		exit(0);
921     }
922     /* NOT REACHED */
923 
924     exit(0);
925 }
926 
927 /*
928  * Function to calculate linear acceleration.
929  *
930  * If there are any rounding errors, the remainder
931  * is stored in the remainx and remainy variables
932  * and taken into account upon the next movement.
933  */
934 
935 static void
linacc(int dx,int dy,int * movex,int * movey)936 linacc(int dx, int dy, int *movex, int *movey)
937 {
938     float fdx, fdy;
939 
940     if (dx == 0 && dy == 0) {
941 	*movex = *movey = 0;
942 	return;
943     }
944     fdx = dx * rodent.accelx + rodent.remainx;
945     fdy = dy * rodent.accely + rodent.remainy;
946     *movex = lround(fdx);
947     *movey = lround(fdy);
948     rodent.remainx = fdx - *movex;
949     rodent.remainy = fdy - *movey;
950 }
951 
952 /*
953  * Function to calculate exponential acceleration.
954  * (Also includes linear acceleration if enabled.)
955  *
956  * In order to give a smoother behaviour, we record the four
957  * most recent non-zero movements and use their average value
958  * to calculate the acceleration.
959  */
960 
961 static void
expoacc(int dx,int dy,int * movex,int * movey)962 expoacc(int dx, int dy, int *movex, int *movey)
963 {
964     static float lastlength[3] = {0.0, 0.0, 0.0};
965     float fdx, fdy, length, lbase, accel;
966 
967     if (dx == 0 && dy == 0) {
968 	*movex = *movey = 0;
969 	return;
970     }
971     fdx = dx * rodent.accelx;
972     fdy = dy * rodent.accely;
973     length = sqrtf((fdx * fdx) + (fdy * fdy));		/* Pythagoras */
974     length = (length + lastlength[0] + lastlength[1] + lastlength[2]) / 4;
975     lbase = length / rodent.expoffset;
976     accel = powf(lbase, rodent.expoaccel) / lbase;
977     fdx = fdx * accel + rodent.remainx;
978     fdy = fdy * accel + rodent.remainy;
979     *movex = lroundf(fdx);
980     *movey = lroundf(fdy);
981     rodent.remainx = fdx - *movex;
982     rodent.remainy = fdy - *movey;
983     lastlength[2] = lastlength[1];
984     lastlength[1] = lastlength[0];
985     lastlength[0] = length;	/* Insert new average, not original length! */
986 }
987 
988 static void
moused(void)989 moused(void)
990 {
991     struct mouse_info mouse;
992     mousestatus_t action0;		/* original mouse action */
993     mousestatus_t action;		/* interim buffer */
994     mousestatus_t action2;		/* mapped action */
995     struct timeval timeout;
996     fd_set fds;
997     u_char b;
998     pid_t mpid;
999     int flags;
1000     int c;
1001     int i;
1002 
1003     if ((rodent.cfd = open("/dev/consolectl", O_RDWR, 0)) == -1)
1004 	logerr(1, "cannot open /dev/consolectl");
1005 
1006     if (!nodaemon && !background) {
1007 	pfh = pidfile_open(pidfile, 0600, &mpid);
1008 	if (pfh == NULL) {
1009 	    if (errno == EEXIST)
1010 		logerrx(1, "moused already running, pid: %d", mpid);
1011 	    logwarn("cannot open pid file");
1012 	}
1013 	if (daemon(0, 0)) {
1014 	    int saved_errno = errno;
1015 	    pidfile_remove(pfh);
1016 	    errno = saved_errno;
1017 	    logerr(1, "failed to become a daemon");
1018 	} else {
1019 	    background = TRUE;
1020 	    pidfile_write(pfh);
1021 	}
1022     }
1023 
1024     /* clear mouse data */
1025     bzero(&action0, sizeof(action0));
1026     bzero(&action, sizeof(action));
1027     bzero(&action2, sizeof(action2));
1028     bzero(&mouse, sizeof(mouse));
1029     mouse_button_state = S0;
1030     clock_gettime(CLOCK_MONOTONIC_FAST, &mouse_button_state_ts);
1031     mouse_move_delayed = 0;
1032     for (i = 0; i < MOUSE_MAXBUTTON; ++i) {
1033 	bstate[i].count = 0;
1034 	bstate[i].ts = mouse_button_state_ts;
1035     }
1036     for (i = 0; i < (int)nitems(zstate); ++i) {
1037 	zstate[i].count = 0;
1038 	zstate[i].ts = mouse_button_state_ts;
1039     }
1040 
1041     /* choose which ioctl command to use */
1042     mouse.operation = MOUSE_MOTION_EVENT;
1043     extioctl = (ioctl(rodent.cfd, CONS_MOUSECTL, &mouse) == 0);
1044 
1045     /* process mouse data */
1046     timeout.tv_sec = 0;
1047     timeout.tv_usec = 20000;		/* 20 msec */
1048     for (;;) {
1049 
1050 	FD_ZERO(&fds);
1051 	FD_SET(rodent.mfd, &fds);
1052 	if (rodent.mremsfd >= 0)
1053 	    FD_SET(rodent.mremsfd, &fds);
1054 	if (rodent.mremcfd >= 0)
1055 	    FD_SET(rodent.mremcfd, &fds);
1056 
1057 	c = select(FD_SETSIZE, &fds, NULL, NULL,
1058 		   ((rodent.flags & Emulate3Button) &&
1059 		    S_DELAYED(mouse_button_state)) ? &timeout : NULL);
1060 	if (c < 0) {                    /* error */
1061 	    logwarn("failed to read from mouse");
1062 	    continue;
1063 	} else if (c == 0) {            /* timeout */
1064 	    /* assert(rodent.flags & Emulate3Button) */
1065 	    action0.button = action0.obutton;
1066 	    action0.dx = action0.dy = action0.dz = 0;
1067 	    action0.flags = flags = 0;
1068 	    if (r_timeout() && r_statetrans(&action0, &action, A_TIMEOUT)) {
1069 		if (debug > 2)
1070 		    debug("flags:%08x buttons:%08x obuttons:%08x",
1071 			  action.flags, action.button, action.obutton);
1072 	    } else {
1073 		action0.obutton = action0.button;
1074 		continue;
1075 	    }
1076 	} else {
1077 	    /*  MouseRemote client connect/disconnect  */
1078 	    if ((rodent.mremsfd >= 0) && FD_ISSET(rodent.mremsfd, &fds)) {
1079 		mremote_clientchg(TRUE);
1080 		continue;
1081 	    }
1082 	    if ((rodent.mremcfd >= 0) && FD_ISSET(rodent.mremcfd, &fds)) {
1083 		mremote_clientchg(FALSE);
1084 		continue;
1085 	    }
1086 	    /* mouse movement */
1087 	    if (read(rodent.mfd, &b, 1) == -1) {
1088 		if (errno == EWOULDBLOCK)
1089 		    continue;
1090 		else
1091 		    return;
1092 	    }
1093 	    if ((flags = r_protocol(b, &action0)) == 0)
1094 		continue;
1095 
1096 	    if ((rodent.flags & VirtualScroll) || (rodent.flags & HVirtualScroll)) {
1097 		/* Allow middle button drags to scroll up and down */
1098 		if (action0.button == MOUSE_BUTTON2DOWN) {
1099 		    if (scroll_state == SCROLL_NOTSCROLLING) {
1100 			scroll_state = SCROLL_PREPARE;
1101 			scroll_movement = hscroll_movement = 0;
1102 			debug("PREPARING TO SCROLL");
1103 		    }
1104 		    debug("[BUTTON2] flags:%08x buttons:%08x obuttons:%08x",
1105 			  action.flags, action.button, action.obutton);
1106 		} else {
1107 		    debug("[NOTBUTTON2] flags:%08x buttons:%08x obuttons:%08x",
1108 			  action.flags, action.button, action.obutton);
1109 
1110 		    /* This isn't a middle button down... move along... */
1111 		    if (scroll_state == SCROLL_SCROLLING) {
1112 			/*
1113 			 * We were scrolling, someone let go of button 2.
1114 			 * Now turn autoscroll off.
1115 			 */
1116 			scroll_state = SCROLL_NOTSCROLLING;
1117 			debug("DONE WITH SCROLLING / %d", scroll_state);
1118 		    } else if (scroll_state == SCROLL_PREPARE) {
1119 			mousestatus_t newaction = action0;
1120 
1121 			/* We were preparing to scroll, but we never moved... */
1122 			r_timestamp(&action0);
1123 			r_statetrans(&action0, &newaction,
1124 				     A(newaction.button & MOUSE_BUTTON1DOWN,
1125 				       action0.button & MOUSE_BUTTON3DOWN));
1126 
1127 			/* Send middle down */
1128 			newaction.button = MOUSE_BUTTON2DOWN;
1129 			r_click(&newaction);
1130 
1131 			/* Send middle up */
1132 			r_timestamp(&newaction);
1133 			newaction.obutton = newaction.button;
1134 			newaction.button = action0.button;
1135 			r_click(&newaction);
1136 		    }
1137 		}
1138 	    }
1139 
1140 	    r_timestamp(&action0);
1141 	    r_statetrans(&action0, &action,
1142 			 A(action0.button & MOUSE_BUTTON1DOWN,
1143 			   action0.button & MOUSE_BUTTON3DOWN));
1144 	    debug("flags:%08x buttons:%08x obuttons:%08x", action.flags,
1145 		  action.button, action.obutton);
1146 	}
1147 	action0.obutton = action0.button;
1148 	flags &= MOUSE_POSCHANGED;
1149 	flags |= action.obutton ^ action.button;
1150 	action.flags = flags;
1151 
1152 	if (flags) {			/* handler detected action */
1153 	    r_map(&action, &action2);
1154 	    debug("activity : buttons 0x%08x  dx %d  dy %d  dz %d",
1155 		action2.button, action2.dx, action2.dy, action2.dz);
1156 
1157 	    if ((rodent.flags & VirtualScroll) || (rodent.flags & HVirtualScroll)) {
1158 		/*
1159 		 * If *only* the middle button is pressed AND we are moving
1160 		 * the stick/trackpoint/nipple, scroll!
1161 		 */
1162 		if (scroll_state == SCROLL_PREPARE) {
1163 			/* Middle button down, waiting for movement threshold */
1164 			if (action2.dy || action2.dx) {
1165 				if (rodent.flags & VirtualScroll) {
1166 					scroll_movement += action2.dy;
1167 					if (scroll_movement < -rodent.scrollthreshold) {
1168 						scroll_state = SCROLL_SCROLLING;
1169 					} else if (scroll_movement > rodent.scrollthreshold) {
1170 						scroll_state = SCROLL_SCROLLING;
1171 					}
1172 				}
1173 				if (rodent.flags & HVirtualScroll) {
1174 					hscroll_movement += action2.dx;
1175 					if (hscroll_movement < -rodent.scrollthreshold) {
1176 						scroll_state = SCROLL_SCROLLING;
1177 					} else if (hscroll_movement > rodent.scrollthreshold) {
1178 						scroll_state = SCROLL_SCROLLING;
1179 					}
1180 				}
1181 				if (scroll_state == SCROLL_SCROLLING) scroll_movement = hscroll_movement = 0;
1182 			}
1183 		} else if (scroll_state == SCROLL_SCROLLING) {
1184 			 if (rodent.flags & VirtualScroll) {
1185 				 scroll_movement += action2.dy;
1186 				 debug("SCROLL: %d", scroll_movement);
1187 			    if (scroll_movement < -rodent.scrollspeed) {
1188 				/* Scroll down */
1189 				action2.dz = -1;
1190 				scroll_movement = 0;
1191 			    }
1192 			    else if (scroll_movement > rodent.scrollspeed) {
1193 				/* Scroll up */
1194 				action2.dz = 1;
1195 				scroll_movement = 0;
1196 			    }
1197 			 }
1198 			 if (rodent.flags & HVirtualScroll) {
1199 				 hscroll_movement += action2.dx;
1200 				 debug("HORIZONTAL SCROLL: %d", hscroll_movement);
1201 
1202 				 if (hscroll_movement < -rodent.scrollspeed) {
1203 					 action2.dz = -2;
1204 					 hscroll_movement = 0;
1205 				 }
1206 				 else if (hscroll_movement > rodent.scrollspeed) {
1207 					 action2.dz = 2;
1208 					 hscroll_movement = 0;
1209 				 }
1210 			 }
1211 
1212 		    /* Don't move while scrolling */
1213 		    action2.dx = action2.dy = 0;
1214 		}
1215 	    }
1216 
1217 	    if (drift_terminate) {
1218 		if ((flags & MOUSE_POSCHANGED) == 0 || action.dz || action2.dz)
1219 		    drift_last_activity = drift_current_ts;
1220 		else {
1221 		    /* X or/and Y movement only - possibly drift */
1222 		    tssub(&drift_current_ts, &drift_last_activity, &drift_tmp);
1223 		    if (tscmp(&drift_tmp, &drift_after_ts, >)) {
1224 			tssub(&drift_current_ts, &drift_since, &drift_tmp);
1225 			if (tscmp(&drift_tmp, &drift_time_ts, <)) {
1226 			    drift_last.x += action2.dx;
1227 			    drift_last.y += action2.dy;
1228 			} else {
1229 			    /* discard old accumulated steps (drift) */
1230 			    if (tscmp(&drift_tmp, &drift_2time_ts, >))
1231 				drift_previous.x = drift_previous.y = 0;
1232 			    else
1233 				drift_previous = drift_last;
1234 			    drift_last.x = action2.dx;
1235 			    drift_last.y = action2.dy;
1236 			    drift_since = drift_current_ts;
1237 			}
1238 			if (abs(drift_last.x) + abs(drift_last.y)
1239 			  > drift_distance) {
1240 			    /* real movement, pass all accumulated steps */
1241 			    action2.dx = drift_previous.x + drift_last.x;
1242 			    action2.dy = drift_previous.y + drift_last.y;
1243 			    /* and reset accumulators */
1244 			    tsclr(&drift_since);
1245 			    drift_last.x = drift_last.y = 0;
1246 			    /* drift_previous will be cleared at next movement*/
1247 			    drift_last_activity = drift_current_ts;
1248 			} else {
1249 			    continue;   /* don't pass current movement to
1250 					 * console driver */
1251 			}
1252 		    }
1253 		}
1254 	    }
1255 
1256 	    if (extioctl) {
1257 		/* Defer clicks until we aren't VirtualScroll'ing. */
1258 		if (scroll_state == SCROLL_NOTSCROLLING)
1259 		    r_click(&action2);
1260 
1261 		if (action2.flags & MOUSE_POSCHANGED) {
1262 		    mouse.operation = MOUSE_MOTION_EVENT;
1263 		    mouse.u.data.buttons = action2.button;
1264 		    if (rodent.flags & ExponentialAcc) {
1265 			expoacc(action2.dx, action2.dy,
1266 			    &mouse.u.data.x, &mouse.u.data.y);
1267 		    }
1268 		    else {
1269 			linacc(action2.dx, action2.dy,
1270 			    &mouse.u.data.x, &mouse.u.data.y);
1271 		    }
1272 		    mouse.u.data.z = action2.dz;
1273 		    if (debug < 2)
1274 			if (!paused)
1275 				ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
1276 		}
1277 	    } else {
1278 		mouse.operation = MOUSE_ACTION;
1279 		mouse.u.data.buttons = action2.button;
1280 		if (rodent.flags & ExponentialAcc) {
1281 		    expoacc(action2.dx, action2.dy,
1282 			&mouse.u.data.x, &mouse.u.data.y);
1283 		}
1284 		else {
1285 		    linacc(action2.dx, action2.dy,
1286 			&mouse.u.data.x, &mouse.u.data.y);
1287 		}
1288 		mouse.u.data.z = action2.dz;
1289 		if (debug < 2)
1290 		    if (!paused)
1291 			ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
1292 	    }
1293 
1294 	    /*
1295 	     * If the Z axis movement is mapped to an imaginary physical
1296 	     * button, we need to cook up a corresponding button `up' event
1297 	     * after sending a button `down' event.
1298 	     */
1299 	    if ((rodent.zmap[0] > 0) && (action.dz != 0)) {
1300 		action.obutton = action.button;
1301 		action.dx = action.dy = action.dz = 0;
1302 		r_map(&action, &action2);
1303 		debug("activity : buttons 0x%08x  dx %d  dy %d  dz %d",
1304 		    action2.button, action2.dx, action2.dy, action2.dz);
1305 
1306 		if (extioctl) {
1307 		    r_click(&action2);
1308 		} else {
1309 		    mouse.operation = MOUSE_ACTION;
1310 		    mouse.u.data.buttons = action2.button;
1311 		    mouse.u.data.x = mouse.u.data.y = mouse.u.data.z = 0;
1312 		    if (debug < 2)
1313 			if (!paused)
1314 			    ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
1315 		}
1316 	    }
1317 	}
1318     }
1319     /* NOT REACHED */
1320 }
1321 
1322 static void
hup(__unused int sig)1323 hup(__unused int sig)
1324 {
1325     longjmp(env, 1);
1326 }
1327 
1328 static void
cleanup(__unused int sig)1329 cleanup(__unused int sig)
1330 {
1331     if (rodent.rtype == MOUSE_PROTO_X10MOUSEREM)
1332 	unlink(_PATH_MOUSEREMOTE);
1333     exit(0);
1334 }
1335 
1336 static void
pause_mouse(__unused int sig)1337 pause_mouse(__unused int sig)
1338 {
1339     paused = !paused;
1340 }
1341 
1342 /**
1343  ** usage
1344  **
1345  ** Complain, and free the CPU for more worthy tasks
1346  **/
1347 static void
usage(void)1348 usage(void)
1349 {
1350     fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n",
1351 	"usage: moused [-DRcdfs] [-I file] [-F rate] [-r resolution] [-S baudrate]",
1352 	"              [-VH [-U threshold]] [-a X[,Y]] [-C threshold] [-m N=M] [-w N]",
1353 	"              [-z N] [-t <mousetype>] [-l level] [-3 [-E timeout]]",
1354 	"              [-T distance[,time[,after]]] -p <port>",
1355 	"       moused [-d] -i <port|if|type|model|all> -p <port>");
1356     exit(1);
1357 }
1358 
1359 /*
1360  * Output an error message to syslog or stderr as appropriate. If
1361  * `errnum' is non-zero, append its string form to the message.
1362  */
1363 static void
log_or_warn(int log_pri,int errnum,const char * fmt,...)1364 log_or_warn(int log_pri, int errnum, const char *fmt, ...)
1365 {
1366 	va_list ap;
1367 	char buf[256];
1368 
1369 	va_start(ap, fmt);
1370 	vsnprintf(buf, sizeof(buf), fmt, ap);
1371 	va_end(ap);
1372 	if (errnum) {
1373 		strlcat(buf, ": ", sizeof(buf));
1374 		strlcat(buf, strerror(errnum), sizeof(buf));
1375 	}
1376 
1377 	if (background)
1378 		syslog(log_pri, "%s", buf);
1379 	else
1380 		warnx("%s", buf);
1381 }
1382 
1383 /**
1384  ** Mouse interface code, courtesy of XFree86 3.1.2.
1385  **
1386  ** Note: Various bits have been trimmed, and in my shortsighted enthusiasm
1387  ** to clean, reformat and rationalise naming, it's quite possible that
1388  ** some things in here have been broken.
1389  **
1390  ** I hope not 8)
1391  **
1392  ** The following code is derived from a module marked :
1393  **/
1394 
1395 /* $XConsortium: xf86_Mouse.c,v 1.2 94/10/12 20:33:21 kaleb Exp $ */
1396 /* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86_Mouse.c,v 3.2 1995/01/28
1397  17:03:40 dawes Exp $ */
1398 /*
1399  *
1400  * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
1401  * Copyright 1993 by David Dawes <dawes@physics.su.oz.au>
1402  *
1403  * Permission to use, copy, modify, distribute, and sell this software and its
1404  * documentation for any purpose is hereby granted without fee, provided that
1405  * the above copyright notice appear in all copies and that both that
1406  * copyright notice and this permission notice appear in supporting
1407  * documentation, and that the names of Thomas Roell and David Dawes not be
1408  * used in advertising or publicity pertaining to distribution of the
1409  * software without specific, written prior permission.  Thomas Roell
1410  * and David Dawes makes no representations about the suitability of this
1411  * software for any purpose.  It is provided "as is" without express or
1412  * implied warranty.
1413  *
1414  * THOMAS ROELL AND DAVID DAWES DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
1415  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
1416  * FITNESS, IN NO EVENT SHALL THOMAS ROELL OR DAVID DAWES BE LIABLE FOR ANY
1417  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
1418  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
1419  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
1420  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1421  *
1422  */
1423 
1424 /**
1425  ** GlidePoint support from XFree86 3.2.
1426  ** Derived from the module:
1427  **/
1428 
1429 /* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86_Mouse.c,v 3.19 1996/10/16 14:40:51 dawes Exp $ */
1430 /* $XConsortium: xf86_Mouse.c /main/10 1996/01/30 15:16:12 kaleb $ */
1431 
1432 /* the following table must be ordered by MOUSE_PROTO_XXX in mouse.h */
1433 static unsigned char proto[][7] = {
1434     /*  hd_mask hd_id   dp_mask dp_id   bytes b4_mask b4_id */
1435     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x23,  0x00 }, /* MicroSoft */
1436     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* MouseSystems */
1437     {	0xe0,	0x80,	0x80,	0x00,	3,    0x00,  0xff }, /* Logitech */
1438     {	0xe0,	0x80,	0x80,	0x00,	3,    0x00,  0xff }, /* MMSeries */
1439     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x33,  0x00 }, /* MouseMan */
1440     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* Bus */
1441     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* InPort */
1442     {	0xc0,	0x00,	0x00,	0x00,	3,    0x00,  0xff }, /* PS/2 mouse */
1443     {	0xe0,	0x80,	0x80,	0x00,	3,    0x00,  0xff }, /* MM HitTablet */
1444     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x33,  0x00 }, /* GlidePoint */
1445     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x3f,  0x00 }, /* IntelliMouse */
1446     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x33,  0x00 }, /* ThinkingMouse */
1447     {	0xf8,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* sysmouse */
1448     {	0x40,	0x40,	0x40,	0x00,	3,   ~0x23,  0x00 }, /* X10 MouseRem */
1449     {	0x80,	0x80,	0x00,	0x00,	5,    0x00,  0xff }, /* KIDSPAD */
1450     {	0xc3,	0xc0,	0x00,	0x00,	6,    0x00,  0xff }, /* VersaPad */
1451     {	0x00,	0x00,	0x00,	0x00,	1,    0x00,  0xff }, /* JogDial */
1452 #if notyet
1453     {	0xf8,	0x80,	0x00,	0x00,	5,   ~0x2f,  0x10 }, /* Mariqua */
1454 #endif
1455 };
1456 static unsigned char cur_proto[7];
1457 
1458 static int
r_identify(void)1459 r_identify(void)
1460 {
1461     char pnpbuf[256];	/* PnP identifier string may be up to 256 bytes long */
1462     pnpid_t pnpid;
1463     symtab_t *t;
1464     int level;
1465     int len;
1466 
1467     /* set the driver operation level, if applicable */
1468     if (rodent.level < 0)
1469 	rodent.level = 1;
1470     ioctl(rodent.mfd, MOUSE_SETLEVEL, &rodent.level);
1471     rodent.level = (ioctl(rodent.mfd, MOUSE_GETLEVEL, &level) == 0) ? level : 0;
1472 
1473     /*
1474      * Interrogate the driver and get some intelligence on the device...
1475      * The following ioctl functions are not always supported by device
1476      * drivers.  When the driver doesn't support them, we just trust the
1477      * user to supply valid information.
1478      */
1479     rodent.hw.iftype = MOUSE_IF_UNKNOWN;
1480     rodent.hw.model = MOUSE_MODEL_GENERIC;
1481     ioctl(rodent.mfd, MOUSE_GETHWINFO, &rodent.hw);
1482 
1483     if (rodent.rtype != MOUSE_PROTO_UNKNOWN)
1484 	bcopy(proto[rodent.rtype], cur_proto, sizeof(cur_proto));
1485     rodent.mode.protocol = MOUSE_PROTO_UNKNOWN;
1486     rodent.mode.rate = -1;
1487     rodent.mode.resolution = MOUSE_RES_UNKNOWN;
1488     rodent.mode.accelfactor = 0;
1489     rodent.mode.level = 0;
1490     if (ioctl(rodent.mfd, MOUSE_GETMODE, &rodent.mode) == 0) {
1491 	if (rodent.mode.protocol == MOUSE_PROTO_UNKNOWN ||
1492 	    rodent.mode.protocol >= (int)nitems(proto)) {
1493 	    logwarnx("unknown mouse protocol (%d)", rodent.mode.protocol);
1494 	    return (MOUSE_PROTO_UNKNOWN);
1495 	} else {
1496 	    if (rodent.mode.protocol != rodent.rtype) {
1497 		/* Hmm, the driver doesn't agree with the user... */
1498 		if (rodent.rtype != MOUSE_PROTO_UNKNOWN)
1499 		    logwarnx("mouse type mismatch (%s != %s), %s is assumed",
1500 			r_name(rodent.mode.protocol), r_name(rodent.rtype),
1501 			r_name(rodent.mode.protocol));
1502 		rodent.rtype = rodent.mode.protocol;
1503 		bcopy(proto[rodent.rtype], cur_proto, sizeof(cur_proto));
1504 	    }
1505 	}
1506 	cur_proto[4] = rodent.mode.packetsize;
1507 	cur_proto[0] = rodent.mode.syncmask[0];	/* header byte bit mask */
1508 	cur_proto[1] = rodent.mode.syncmask[1];	/* header bit pattern */
1509     }
1510 
1511     /* maybe this is a PnP mouse... */
1512     if (rodent.mode.protocol == MOUSE_PROTO_UNKNOWN) {
1513 
1514 	if (rodent.flags & NoPnP)
1515 	    return (rodent.rtype);
1516 	if (((len = pnpgets(pnpbuf)) <= 0) || !pnpparse(&pnpid, pnpbuf, len))
1517 	    return (rodent.rtype);
1518 
1519 	debug("PnP serial mouse: '%*.*s' '%*.*s' '%*.*s'",
1520 	    pnpid.neisaid, pnpid.neisaid, pnpid.eisaid,
1521 	    pnpid.ncompat, pnpid.ncompat, pnpid.compat,
1522 	    pnpid.ndescription, pnpid.ndescription, pnpid.description);
1523 
1524 	/* we have a valid PnP serial device ID */
1525 	rodent.hw.iftype = MOUSE_IF_SERIAL;
1526 	t = pnpproto(&pnpid);
1527 	if (t != NULL) {
1528 	    rodent.mode.protocol = t->val;
1529 	    rodent.hw.model = t->val2;
1530 	} else {
1531 	    rodent.mode.protocol = MOUSE_PROTO_UNKNOWN;
1532 	}
1533 
1534 	/* make final adjustment */
1535 	if (rodent.mode.protocol != MOUSE_PROTO_UNKNOWN) {
1536 	    if (rodent.mode.protocol != rodent.rtype) {
1537 		/* Hmm, the device doesn't agree with the user... */
1538 		if (rodent.rtype != MOUSE_PROTO_UNKNOWN)
1539 		    logwarnx("mouse type mismatch (%s != %s), %s is assumed",
1540 			r_name(rodent.mode.protocol), r_name(rodent.rtype),
1541 			r_name(rodent.mode.protocol));
1542 		rodent.rtype = rodent.mode.protocol;
1543 		bcopy(proto[rodent.rtype], cur_proto, sizeof(cur_proto));
1544 	    }
1545 	}
1546     }
1547 
1548     debug("proto params: %02x %02x %02x %02x %d %02x %02x",
1549 	cur_proto[0], cur_proto[1], cur_proto[2], cur_proto[3],
1550 	cur_proto[4], cur_proto[5], cur_proto[6]);
1551 
1552     return (rodent.rtype);
1553 }
1554 
1555 static const char *
r_if(int iftype)1556 r_if(int iftype)
1557 {
1558 
1559     return (gettokenname(rifs, iftype));
1560 }
1561 
1562 static const char *
r_name(int type)1563 r_name(int type)
1564 {
1565     const char *unknown = "unknown";
1566 
1567     return (type == MOUSE_PROTO_UNKNOWN || type >= (int)nitems(rnames) ?
1568 	unknown : rnames[type]);
1569 }
1570 
1571 static const char *
r_model(int model)1572 r_model(int model)
1573 {
1574 
1575     return (gettokenname(rmodels, model));
1576 }
1577 
1578 static void
r_init(void)1579 r_init(void)
1580 {
1581     unsigned char buf[16];	/* scrach buffer */
1582     fd_set fds;
1583     const char *s;
1584     char c;
1585     int i;
1586 
1587     /**
1588      ** This comment is a little out of context here, but it contains
1589      ** some useful information...
1590      ********************************************************************
1591      **
1592      ** The following lines take care of the Logitech MouseMan protocols.
1593      **
1594      ** NOTE: There are different versions of both MouseMan and TrackMan!
1595      **       Hence I add another protocol P_LOGIMAN, which the user can
1596      **       specify as MouseMan in his XF86Config file. This entry was
1597      **       formerly handled as a special case of P_MS. However, people
1598      **       who don't have the middle button problem, can still specify
1599      **       Microsoft and use P_MS.
1600      **
1601      ** By default, these mice should use a 3 byte Microsoft protocol
1602      ** plus a 4th byte for the middle button. However, the mouse might
1603      ** have switched to a different protocol before we use it, so I send
1604      ** the proper sequence just in case.
1605      **
1606      ** NOTE: - all commands to (at least the European) MouseMan have to
1607      **         be sent at 1200 Baud.
1608      **       - each command starts with a '*'.
1609      **       - whenever the MouseMan receives a '*', it will switch back
1610      **	 to 1200 Baud. Hence I have to select the desired protocol
1611      **	 first, then select the baud rate.
1612      **
1613      ** The protocols supported by the (European) MouseMan are:
1614      **   -  5 byte packed binary protocol, as with the Mouse Systems
1615      **      mouse. Selected by sequence "*U".
1616      **   -  2 button 3 byte MicroSoft compatible protocol. Selected
1617      **      by sequence "*V".
1618      **   -  3 button 3+1 byte MicroSoft compatible protocol (default).
1619      **      Selected by sequence "*X".
1620      **
1621      ** The following baud rates are supported:
1622      **   -  1200 Baud (default). Selected by sequence "*n".
1623      **   -  9600 Baud. Selected by sequence "*q".
1624      **
1625      ** Selecting a sample rate is no longer supported with the MouseMan!
1626      ** Some additional lines in xf86Config.c take care of ill configured
1627      ** baud rates and sample rates. (The user will get an error.)
1628      */
1629 
1630     switch (rodent.rtype) {
1631 
1632     case MOUSE_PROTO_LOGI:
1633 	/*
1634 	 * The baud rate selection command must be sent at the current
1635 	 * baud rate; try all likely settings
1636 	 */
1637 	setmousespeed(9600, rodent.baudrate, rodentcflags[rodent.rtype]);
1638 	setmousespeed(4800, rodent.baudrate, rodentcflags[rodent.rtype]);
1639 	setmousespeed(2400, rodent.baudrate, rodentcflags[rodent.rtype]);
1640 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1641 	/* select MM series data format */
1642 	write(rodent.mfd, "S", 1);
1643 	setmousespeed(rodent.baudrate, rodent.baudrate,
1644 		      rodentcflags[MOUSE_PROTO_MM]);
1645 	/* select report rate/frequency */
1646 	if      (rodent.rate <= 0)   write(rodent.mfd, "O", 1);
1647 	else if (rodent.rate <= 15)  write(rodent.mfd, "J", 1);
1648 	else if (rodent.rate <= 27)  write(rodent.mfd, "K", 1);
1649 	else if (rodent.rate <= 42)  write(rodent.mfd, "L", 1);
1650 	else if (rodent.rate <= 60)  write(rodent.mfd, "R", 1);
1651 	else if (rodent.rate <= 85)  write(rodent.mfd, "M", 1);
1652 	else if (rodent.rate <= 125) write(rodent.mfd, "Q", 1);
1653 	else			     write(rodent.mfd, "N", 1);
1654 	break;
1655 
1656     case MOUSE_PROTO_LOGIMOUSEMAN:
1657 	/* The command must always be sent at 1200 baud */
1658 	setmousespeed(1200, 1200, rodentcflags[rodent.rtype]);
1659 	write(rodent.mfd, "*X", 2);
1660 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1661 	break;
1662 
1663     case MOUSE_PROTO_HITTAB:
1664 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1665 
1666 	/*
1667 	 * Initialize Hitachi PUMA Plus - Model 1212E to desired settings.
1668 	 * The tablet must be configured to be in MM mode, NO parity,
1669 	 * Binary Format.  xf86Info.sampleRate controls the sensativity
1670 	 * of the tablet.  We only use this tablet for it's 4-button puck
1671 	 * so we don't run in "Absolute Mode"
1672 	 */
1673 	write(rodent.mfd, "z8", 2);	/* Set Parity = "NONE" */
1674 	usleep(50000);
1675 	write(rodent.mfd, "zb", 2);	/* Set Format = "Binary" */
1676 	usleep(50000);
1677 	write(rodent.mfd, "@", 1);	/* Set Report Mode = "Stream" */
1678 	usleep(50000);
1679 	write(rodent.mfd, "R", 1);	/* Set Output Rate = "45 rps" */
1680 	usleep(50000);
1681 	write(rodent.mfd, "I\x20", 2);	/* Set Incrememtal Mode "20" */
1682 	usleep(50000);
1683 	write(rodent.mfd, "E", 1);	/* Set Data Type = "Relative */
1684 	usleep(50000);
1685 
1686 	/* Resolution is in 'lines per inch' on the Hitachi tablet */
1687 	if      (rodent.resolution == MOUSE_RES_LOW)		c = 'g';
1688 	else if (rodent.resolution == MOUSE_RES_MEDIUMLOW)	c = 'e';
1689 	else if (rodent.resolution == MOUSE_RES_MEDIUMHIGH)	c = 'h';
1690 	else if (rodent.resolution == MOUSE_RES_HIGH)		c = 'd';
1691 	else if (rodent.resolution <=   40)			c = 'g';
1692 	else if (rodent.resolution <=  100)			c = 'd';
1693 	else if (rodent.resolution <=  200)			c = 'e';
1694 	else if (rodent.resolution <=  500)			c = 'h';
1695 	else if (rodent.resolution <= 1000)			c = 'j';
1696 	else			c = 'd';
1697 	write(rodent.mfd, &c, 1);
1698 	usleep(50000);
1699 
1700 	write(rodent.mfd, "\021", 1);	/* Resume DATA output */
1701 	break;
1702 
1703     case MOUSE_PROTO_THINK:
1704 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1705 	/* the PnP ID string may be sent again, discard it */
1706 	usleep(200000);
1707 	i = FREAD;
1708 	ioctl(rodent.mfd, TIOCFLUSH, &i);
1709 	/* send the command to initialize the beast */
1710 	for (s = "E5E5"; *s; ++s) {
1711 	    write(rodent.mfd, s, 1);
1712 	    FD_ZERO(&fds);
1713 	    FD_SET(rodent.mfd, &fds);
1714 	    if (select(FD_SETSIZE, &fds, NULL, NULL, NULL) <= 0)
1715 		break;
1716 	    read(rodent.mfd, &c, 1);
1717 	    debug("%c", c);
1718 	    if (c != *s)
1719 		break;
1720 	}
1721 	break;
1722 
1723     case MOUSE_PROTO_JOGDIAL:
1724 	break;
1725     case MOUSE_PROTO_MSC:
1726 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1727 	if (rodent.flags & ClearDTR) {
1728 	   i = TIOCM_DTR;
1729 	   ioctl(rodent.mfd, TIOCMBIC, &i);
1730 	}
1731 	if (rodent.flags & ClearRTS) {
1732 	   i = TIOCM_RTS;
1733 	   ioctl(rodent.mfd, TIOCMBIC, &i);
1734 	}
1735 	break;
1736 
1737     case MOUSE_PROTO_SYSMOUSE:
1738 	if (rodent.hw.iftype == MOUSE_IF_SYSMOUSE)
1739 	    setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1740 	/* FALLTHROUGH */
1741 
1742     case MOUSE_PROTO_PS2:
1743 	if (rodent.rate >= 0)
1744 	    rodent.mode.rate = rodent.rate;
1745 	if (rodent.resolution != MOUSE_RES_UNKNOWN)
1746 	    rodent.mode.resolution = rodent.resolution;
1747 	ioctl(rodent.mfd, MOUSE_SETMODE, &rodent.mode);
1748 	break;
1749 
1750     case MOUSE_PROTO_X10MOUSEREM:
1751 	mremote_serversetup();
1752 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1753 	break;
1754 
1755 
1756     case MOUSE_PROTO_VERSAPAD:
1757 	tcsendbreak(rodent.mfd, 0);	/* send break for 400 msec */
1758 	i = FREAD;
1759 	ioctl(rodent.mfd, TIOCFLUSH, &i);
1760 	for (i = 0; i < 7; ++i) {
1761 	    FD_ZERO(&fds);
1762 	    FD_SET(rodent.mfd, &fds);
1763 	    if (select(FD_SETSIZE, &fds, NULL, NULL, NULL) <= 0)
1764 		break;
1765 	    read(rodent.mfd, &c, 1);
1766 	    buf[i] = c;
1767 	}
1768 	debug("%s\n", buf);
1769 	if ((buf[0] != 'V') || (buf[1] != 'P')|| (buf[7] != '\r'))
1770 	    break;
1771 	setmousespeed(9600, rodent.baudrate, rodentcflags[rodent.rtype]);
1772 	tcsendbreak(rodent.mfd, 0);	/* send break for 400 msec again */
1773 	for (i = 0; i < 7; ++i) {
1774 	    FD_ZERO(&fds);
1775 	    FD_SET(rodent.mfd, &fds);
1776 	    if (select(FD_SETSIZE, &fds, NULL, NULL, NULL) <= 0)
1777 		break;
1778 	    read(rodent.mfd, &c, 1);
1779 	    debug("%c", c);
1780 	    if (c != buf[i])
1781 		break;
1782 	}
1783 	i = FREAD;
1784 	ioctl(rodent.mfd, TIOCFLUSH, &i);
1785 	break;
1786 
1787     default:
1788 	setmousespeed(1200, rodent.baudrate, rodentcflags[rodent.rtype]);
1789 	break;
1790     }
1791 }
1792 
1793 static int
r_protocol(u_char rBuf,mousestatus_t * act)1794 r_protocol(u_char rBuf, mousestatus_t *act)
1795 {
1796     /* MOUSE_MSS_BUTTON?DOWN -> MOUSE_BUTTON?DOWN */
1797     static int butmapmss[4] = {	/* Microsoft, MouseMan, GlidePoint,
1798 				   IntelliMouse, Thinking Mouse */
1799 	0,
1800 	MOUSE_BUTTON3DOWN,
1801 	MOUSE_BUTTON1DOWN,
1802 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1803     };
1804     static int butmapmss2[4] = { /* Microsoft, MouseMan, GlidePoint,
1805 				    Thinking Mouse */
1806 	0,
1807 	MOUSE_BUTTON4DOWN,
1808 	MOUSE_BUTTON2DOWN,
1809 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON4DOWN,
1810     };
1811     /* MOUSE_INTELLI_BUTTON?DOWN -> MOUSE_BUTTON?DOWN */
1812     static int butmapintelli[4] = { /* IntelliMouse, NetMouse, Mie Mouse,
1813 				       MouseMan+ */
1814 	0,
1815 	MOUSE_BUTTON2DOWN,
1816 	MOUSE_BUTTON4DOWN,
1817 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON4DOWN,
1818     };
1819     /* MOUSE_MSC_BUTTON?UP -> MOUSE_BUTTON?DOWN */
1820     static int butmapmsc[8] = {	/* MouseSystems, MMSeries, Logitech,
1821 				   Bus, sysmouse */
1822 	0,
1823 	MOUSE_BUTTON3DOWN,
1824 	MOUSE_BUTTON2DOWN,
1825 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
1826 	MOUSE_BUTTON1DOWN,
1827 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1828 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
1829 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
1830     };
1831     /* MOUSE_PS2_BUTTON?DOWN -> MOUSE_BUTTON?DOWN */
1832     static int butmapps2[8] = {	/* PS/2 */
1833 	0,
1834 	MOUSE_BUTTON1DOWN,
1835 	MOUSE_BUTTON3DOWN,
1836 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1837 	MOUSE_BUTTON2DOWN,
1838 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
1839 	MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
1840 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
1841     };
1842     /* for Hitachi tablet */
1843     static int butmaphit[8] = {	/* MM HitTablet */
1844 	0,
1845 	MOUSE_BUTTON3DOWN,
1846 	MOUSE_BUTTON2DOWN,
1847 	MOUSE_BUTTON1DOWN,
1848 	MOUSE_BUTTON4DOWN,
1849 	MOUSE_BUTTON5DOWN,
1850 	MOUSE_BUTTON6DOWN,
1851 	MOUSE_BUTTON7DOWN,
1852     };
1853     /* for serial VersaPad */
1854     static int butmapversa[8] = { /* VersaPad */
1855 	0,
1856 	0,
1857 	MOUSE_BUTTON3DOWN,
1858 	MOUSE_BUTTON3DOWN,
1859 	MOUSE_BUTTON1DOWN,
1860 	MOUSE_BUTTON1DOWN,
1861 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1862 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1863     };
1864     /* for PS/2 VersaPad */
1865     static int butmapversaps2[8] = { /* VersaPad */
1866 	0,
1867 	MOUSE_BUTTON3DOWN,
1868 	0,
1869 	MOUSE_BUTTON3DOWN,
1870 	MOUSE_BUTTON1DOWN,
1871 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1872 	MOUSE_BUTTON1DOWN,
1873 	MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
1874     };
1875     static int           pBufP = 0;
1876     static unsigned char pBuf[8];
1877     static int		 prev_x, prev_y;
1878     static int		 on = FALSE;
1879     int			 x, y;
1880 
1881     debug("received char 0x%x",(int)rBuf);
1882     if (rodent.rtype == MOUSE_PROTO_KIDSPAD)
1883 	return (kidspad(rBuf, act));
1884     if (rodent.rtype == MOUSE_PROTO_GTCO_DIGIPAD)
1885 	return (gtco_digipad(rBuf, act));
1886 
1887     /*
1888      * Hack for resyncing: We check here for a package that is:
1889      *  a) illegal (detected by wrong data-package header)
1890      *  b) invalid (0x80 == -128 and that might be wrong for MouseSystems)
1891      *  c) bad header-package
1892      *
1893      * NOTE: b) is a voilation of the MouseSystems-Protocol, since values of
1894      *       -128 are allowed, but since they are very seldom we can easily
1895      *       use them as package-header with no button pressed.
1896      * NOTE/2: On a PS/2 mouse any byte is valid as a data byte. Furthermore,
1897      *         0x80 is not valid as a header byte. For a PS/2 mouse we skip
1898      *         checking data bytes.
1899      *         For resyncing a PS/2 mouse we require the two most significant
1900      *         bits in the header byte to be 0. These are the overflow bits,
1901      *         and in case of an overflow we actually lose sync. Overflows
1902      *         are very rare, however, and we quickly gain sync again after
1903      *         an overflow condition. This is the best we can do. (Actually,
1904      *         we could use bit 0x08 in the header byte for resyncing, since
1905      *         that bit is supposed to be always on, but nobody told
1906      *         Microsoft...)
1907      */
1908 
1909     if (pBufP != 0 && rodent.rtype != MOUSE_PROTO_PS2 &&
1910 	((rBuf & cur_proto[2]) != cur_proto[3] || rBuf == 0x80))
1911     {
1912 	pBufP = 0;		/* skip package */
1913     }
1914 
1915     if (pBufP == 0 && (rBuf & cur_proto[0]) != cur_proto[1])
1916 	return (0);
1917 
1918     /* is there an extra data byte? */
1919     if (pBufP >= cur_proto[4] && (rBuf & cur_proto[0]) != cur_proto[1])
1920     {
1921 	/*
1922 	 * Hack for Logitech MouseMan Mouse - Middle button
1923 	 *
1924 	 * Unfortunately this mouse has variable length packets: the standard
1925 	 * Microsoft 3 byte packet plus an optional 4th byte whenever the
1926 	 * middle button status changes.
1927 	 *
1928 	 * We have already processed the standard packet with the movement
1929 	 * and button info.  Now post an event message with the old status
1930 	 * of the left and right buttons and the updated middle button.
1931 	 */
1932 
1933 	/*
1934 	 * Even worse, different MouseMen and TrackMen differ in the 4th
1935 	 * byte: some will send 0x00/0x20, others 0x01/0x21, or even
1936 	 * 0x02/0x22, so I have to strip off the lower bits.
1937 	 *
1938 	 * [JCH-96/01/21]
1939 	 * HACK for ALPS "fourth button". (It's bit 0x10 of the "fourth byte"
1940 	 * and it is activated by tapping the glidepad with the finger! 8^)
1941 	 * We map it to bit bit3, and the reverse map in xf86Events just has
1942 	 * to be extended so that it is identified as Button 4. The lower
1943 	 * half of the reverse-map may remain unchanged.
1944 	 */
1945 
1946 	/*
1947 	 * [KY-97/08/03]
1948 	 * Receive the fourth byte only when preceding three bytes have
1949 	 * been detected (pBufP >= cur_proto[4]).  In the previous
1950 	 * versions, the test was pBufP == 0; thus, we may have mistakingly
1951 	 * received a byte even if we didn't see anything preceding
1952 	 * the byte.
1953 	 */
1954 
1955 	if ((rBuf & cur_proto[5]) != cur_proto[6]) {
1956 	    pBufP = 0;
1957 	    return (0);
1958 	}
1959 
1960 	switch (rodent.rtype) {
1961 #if notyet
1962 	case MOUSE_PROTO_MARIQUA:
1963 	    /*
1964 	     * This mouse has 16! buttons in addition to the standard
1965 	     * three of them.  They return 0x10 though 0x1f in the
1966 	     * so-called `ten key' mode and 0x30 though 0x3f in the
1967 	     * `function key' mode.  As there are only 31 bits for
1968 	     * button state (including the standard three), we ignore
1969 	     * the bit 0x20 and don't distinguish the two modes.
1970 	     */
1971 	    act->dx = act->dy = act->dz = 0;
1972 	    act->obutton = act->button;
1973 	    rBuf &= 0x1f;
1974 	    act->button = (1 << (rBuf - 13))
1975 		| (act->obutton & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN));
1976 	    /*
1977 	     * FIXME: this is a button "down" event. There needs to be
1978 	     * a corresponding button "up" event... XXX
1979 	     */
1980 	    break;
1981 #endif /* notyet */
1982 	case MOUSE_PROTO_JOGDIAL:
1983 	    break;
1984 
1985 	/*
1986 	 * IntelliMouse, NetMouse (including NetMouse Pro) and Mie Mouse
1987 	 * always send the fourth byte, whereas the fourth byte is
1988 	 * optional for GlidePoint and ThinkingMouse. The fourth byte
1989 	 * is also optional for MouseMan+ and FirstMouse+ in their
1990 	 * native mode. It is always sent if they are in the IntelliMouse
1991 	 * compatible mode.
1992 	 */
1993 	case MOUSE_PROTO_INTELLI:	/* IntelliMouse, NetMouse, Mie Mouse,
1994 					   MouseMan+ */
1995 	    act->dx = act->dy = 0;
1996 	    act->dz = (rBuf & 0x08) ? (rBuf & 0x0f) - 16 : (rBuf & 0x0f);
1997 	    if ((act->dz >= 7) || (act->dz <= -7))
1998 		act->dz = 0;
1999 	    act->obutton = act->button;
2000 	    act->button = butmapintelli[(rBuf & MOUSE_MSS_BUTTONS) >> 4]
2001 		| (act->obutton & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN));
2002 	    break;
2003 
2004 	default:
2005 	    act->dx = act->dy = act->dz = 0;
2006 	    act->obutton = act->button;
2007 	    act->button = butmapmss2[(rBuf & MOUSE_MSS_BUTTONS) >> 4]
2008 		| (act->obutton & (MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN));
2009 	    break;
2010 	}
2011 
2012 	act->flags = ((act->dx || act->dy || act->dz) ? MOUSE_POSCHANGED : 0)
2013 	    | (act->obutton ^ act->button);
2014 	pBufP = 0;
2015 	return (act->flags);
2016     }
2017 
2018     if (pBufP >= cur_proto[4])
2019 	pBufP = 0;
2020     pBuf[pBufP++] = rBuf;
2021     if (pBufP != cur_proto[4])
2022 	return (0);
2023 
2024     /*
2025      * assembly full package
2026      */
2027 
2028     debug("assembled full packet (len %d) %x,%x,%x,%x,%x,%x,%x,%x",
2029 	cur_proto[4],
2030 	pBuf[0], pBuf[1], pBuf[2], pBuf[3],
2031 	pBuf[4], pBuf[5], pBuf[6], pBuf[7]);
2032 
2033     act->dz = 0;
2034     act->obutton = act->button;
2035     switch (rodent.rtype)
2036     {
2037     case MOUSE_PROTO_MS:		/* Microsoft */
2038     case MOUSE_PROTO_LOGIMOUSEMAN:	/* MouseMan/TrackMan */
2039     case MOUSE_PROTO_X10MOUSEREM:	/* X10 MouseRemote */
2040 	act->button = act->obutton & MOUSE_BUTTON4DOWN;
2041 	if (rodent.flags & ChordMiddle)
2042 	    act->button |= ((pBuf[0] & MOUSE_MSS_BUTTONS) == MOUSE_MSS_BUTTONS)
2043 		? MOUSE_BUTTON2DOWN
2044 		: butmapmss[(pBuf[0] & MOUSE_MSS_BUTTONS) >> 4];
2045 	else
2046 	    act->button |= (act->obutton & MOUSE_BUTTON2DOWN)
2047 		| butmapmss[(pBuf[0] & MOUSE_MSS_BUTTONS) >> 4];
2048 
2049 	/* Send X10 btn events to remote client (ensure -128-+127 range) */
2050 	if ((rodent.rtype == MOUSE_PROTO_X10MOUSEREM) &&
2051 	    ((pBuf[0] & 0xFC) == 0x44) && (pBuf[2] == 0x3F)) {
2052 	    if (rodent.mremcfd >= 0) {
2053 		unsigned char key = (signed char)(((pBuf[0] & 0x03) << 6) |
2054 						  (pBuf[1] & 0x3F));
2055 		write(rodent.mremcfd, &key, 1);
2056 	    }
2057 	    return (0);
2058 	}
2059 
2060 	act->dx = (signed char)(((pBuf[0] & 0x03) << 6) | (pBuf[1] & 0x3F));
2061 	act->dy = (signed char)(((pBuf[0] & 0x0C) << 4) | (pBuf[2] & 0x3F));
2062 	break;
2063 
2064     case MOUSE_PROTO_GLIDEPOINT:	/* GlidePoint */
2065     case MOUSE_PROTO_THINK:		/* ThinkingMouse */
2066     case MOUSE_PROTO_INTELLI:		/* IntelliMouse, NetMouse, Mie Mouse,
2067 					   MouseMan+ */
2068 	act->button = (act->obutton & (MOUSE_BUTTON2DOWN | MOUSE_BUTTON4DOWN))
2069 	    | butmapmss[(pBuf[0] & MOUSE_MSS_BUTTONS) >> 4];
2070 	act->dx = (signed char)(((pBuf[0] & 0x03) << 6) | (pBuf[1] & 0x3F));
2071 	act->dy = (signed char)(((pBuf[0] & 0x0C) << 4) | (pBuf[2] & 0x3F));
2072 	break;
2073 
2074     case MOUSE_PROTO_MSC:		/* MouseSystems Corp */
2075 #if notyet
2076     case MOUSE_PROTO_MARIQUA:		/* Mariqua */
2077 #endif
2078 	act->button = butmapmsc[(~pBuf[0]) & MOUSE_MSC_BUTTONS];
2079 	act->dx =    (signed char)(pBuf[1]) + (signed char)(pBuf[3]);
2080 	act->dy = - ((signed char)(pBuf[2]) + (signed char)(pBuf[4]));
2081 	break;
2082 
2083     case MOUSE_PROTO_JOGDIAL:		/* JogDial */
2084 	    if (rBuf == 0x6c)
2085 	      act->dz = -1;
2086 	    if (rBuf == 0x72)
2087 	      act->dz = 1;
2088 	    if (rBuf == 0x64)
2089 	      act->button = MOUSE_BUTTON1DOWN;
2090 	    if (rBuf == 0x75)
2091 	      act->button = 0;
2092 	break;
2093 
2094     case MOUSE_PROTO_HITTAB:		/* MM HitTablet */
2095 	act->button = butmaphit[pBuf[0] & 0x07];
2096 	act->dx = (pBuf[0] & MOUSE_MM_XPOSITIVE) ?   pBuf[1] : - pBuf[1];
2097 	act->dy = (pBuf[0] & MOUSE_MM_YPOSITIVE) ? - pBuf[2] :   pBuf[2];
2098 	break;
2099 
2100     case MOUSE_PROTO_MM:		/* MM Series */
2101     case MOUSE_PROTO_LOGI:		/* Logitech Mice */
2102 	act->button = butmapmsc[pBuf[0] & MOUSE_MSC_BUTTONS];
2103 	act->dx = (pBuf[0] & MOUSE_MM_XPOSITIVE) ?   pBuf[1] : - pBuf[1];
2104 	act->dy = (pBuf[0] & MOUSE_MM_YPOSITIVE) ? - pBuf[2] :   pBuf[2];
2105 	break;
2106 
2107     case MOUSE_PROTO_VERSAPAD:		/* VersaPad */
2108 	act->button = butmapversa[(pBuf[0] & MOUSE_VERSA_BUTTONS) >> 3];
2109 	act->button |= (pBuf[0] & MOUSE_VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
2110 	act->dx = act->dy = 0;
2111 	if (!(pBuf[0] & MOUSE_VERSA_IN_USE)) {
2112 	    on = FALSE;
2113 	    break;
2114 	}
2115 	x = (pBuf[2] << 6) | pBuf[1];
2116 	if (x & 0x800)
2117 	    x -= 0x1000;
2118 	y = (pBuf[4] << 6) | pBuf[3];
2119 	if (y & 0x800)
2120 	    y -= 0x1000;
2121 	if (on) {
2122 	    act->dx = prev_x - x;
2123 	    act->dy = prev_y - y;
2124 	} else {
2125 	    on = TRUE;
2126 	}
2127 	prev_x = x;
2128 	prev_y = y;
2129 	break;
2130 
2131     case MOUSE_PROTO_PS2:		/* PS/2 */
2132 	act->button = butmapps2[pBuf[0] & MOUSE_PS2_BUTTONS];
2133 	act->dx = (pBuf[0] & MOUSE_PS2_XNEG) ?    pBuf[1] - 256  :  pBuf[1];
2134 	act->dy = (pBuf[0] & MOUSE_PS2_YNEG) ?  -(pBuf[2] - 256) : -pBuf[2];
2135 	/*
2136 	 * Moused usually operates the psm driver at the operation level 1
2137 	 * which sends mouse data in MOUSE_PROTO_SYSMOUSE protocol.
2138 	 * The following code takes effect only when the user explicitly
2139 	 * requets the level 2 at which wheel movement and additional button
2140 	 * actions are encoded in model-dependent formats. At the level 0
2141 	 * the following code is no-op because the psm driver says the model
2142 	 * is MOUSE_MODEL_GENERIC.
2143 	 */
2144 	switch (rodent.hw.model) {
2145 	case MOUSE_MODEL_EXPLORER:
2146 	    /* wheel and additional button data is in the fourth byte */
2147 	    act->dz = (pBuf[3] & MOUSE_EXPLORER_ZNEG)
2148 		? (pBuf[3] & 0x0f) - 16 : (pBuf[3] & 0x0f);
2149 	    act->button |= (pBuf[3] & MOUSE_EXPLORER_BUTTON4DOWN)
2150 		? MOUSE_BUTTON4DOWN : 0;
2151 	    act->button |= (pBuf[3] & MOUSE_EXPLORER_BUTTON5DOWN)
2152 		? MOUSE_BUTTON5DOWN : 0;
2153 	    break;
2154 	case MOUSE_MODEL_INTELLI:
2155 	case MOUSE_MODEL_NET:
2156 	    /* wheel data is in the fourth byte */
2157 	    act->dz = (signed char)pBuf[3];
2158 	    if ((act->dz >= 7) || (act->dz <= -7))
2159 		act->dz = 0;
2160 	    /* some compatible mice may have additional buttons */
2161 	    act->button |= (pBuf[0] & MOUSE_PS2INTELLI_BUTTON4DOWN)
2162 		? MOUSE_BUTTON4DOWN : 0;
2163 	    act->button |= (pBuf[0] & MOUSE_PS2INTELLI_BUTTON5DOWN)
2164 		? MOUSE_BUTTON5DOWN : 0;
2165 	    break;
2166 	case MOUSE_MODEL_MOUSEMANPLUS:
2167 	    if (((pBuf[0] & MOUSE_PS2PLUS_SYNCMASK) == MOUSE_PS2PLUS_SYNC)
2168 		    && (abs(act->dx) > 191)
2169 		    && MOUSE_PS2PLUS_CHECKBITS(pBuf)) {
2170 		/* the extended data packet encodes button and wheel events */
2171 		switch (MOUSE_PS2PLUS_PACKET_TYPE(pBuf)) {
2172 		case 1:
2173 		    /* wheel data packet */
2174 		    act->dx = act->dy = 0;
2175 		    if (pBuf[2] & 0x80) {
2176 			/* horizontal roller count - ignore it XXX*/
2177 		    } else {
2178 			/* vertical roller count */
2179 			act->dz = (pBuf[2] & MOUSE_PS2PLUS_ZNEG)
2180 			    ? (pBuf[2] & 0x0f) - 16 : (pBuf[2] & 0x0f);
2181 		    }
2182 		    act->button |= (pBuf[2] & MOUSE_PS2PLUS_BUTTON4DOWN)
2183 			? MOUSE_BUTTON4DOWN : 0;
2184 		    act->button |= (pBuf[2] & MOUSE_PS2PLUS_BUTTON5DOWN)
2185 			? MOUSE_BUTTON5DOWN : 0;
2186 		    break;
2187 		case 2:
2188 		    /* this packet type is reserved by Logitech */
2189 		    /*
2190 		     * IBM ScrollPoint Mouse uses this packet type to
2191 		     * encode both vertical and horizontal scroll movement.
2192 		     */
2193 		    act->dx = act->dy = 0;
2194 		    /* horizontal roller count */
2195 		    if (pBuf[2] & 0x0f)
2196 			act->dz = (pBuf[2] & MOUSE_SPOINT_WNEG) ? -2 : 2;
2197 		    /* vertical roller count */
2198 		    if (pBuf[2] & 0xf0)
2199 			act->dz = (pBuf[2] & MOUSE_SPOINT_ZNEG) ? -1 : 1;
2200 #if 0
2201 		    /* vertical roller count */
2202 		    act->dz = (pBuf[2] & MOUSE_SPOINT_ZNEG)
2203 			? ((pBuf[2] >> 4) & 0x0f) - 16
2204 			: ((pBuf[2] >> 4) & 0x0f);
2205 		    /* horizontal roller count */
2206 		    act->dw = (pBuf[2] & MOUSE_SPOINT_WNEG)
2207 			? (pBuf[2] & 0x0f) - 16 : (pBuf[2] & 0x0f);
2208 #endif
2209 		    break;
2210 		case 0:
2211 		    /* device type packet - shouldn't happen */
2212 		    /* FALLTHROUGH */
2213 		default:
2214 		    act->dx = act->dy = 0;
2215 		    act->button = act->obutton;
2216 		    debug("unknown PS2++ packet type %d: 0x%02x 0x%02x 0x%02x\n",
2217 			  MOUSE_PS2PLUS_PACKET_TYPE(pBuf),
2218 			  pBuf[0], pBuf[1], pBuf[2]);
2219 		    break;
2220 		}
2221 	    } else {
2222 		/* preserve button states */
2223 		act->button |= act->obutton & MOUSE_EXTBUTTONS;
2224 	    }
2225 	    break;
2226 	case MOUSE_MODEL_GLIDEPOINT:
2227 	    /* `tapping' action */
2228 	    act->button |= ((pBuf[0] & MOUSE_PS2_TAP)) ? 0 : MOUSE_BUTTON4DOWN;
2229 	    break;
2230 	case MOUSE_MODEL_NETSCROLL:
2231 	    /* three additional bytes encode buttons and wheel events */
2232 	    act->button |= (pBuf[3] & MOUSE_PS2_BUTTON3DOWN)
2233 		? MOUSE_BUTTON4DOWN : 0;
2234 	    act->button |= (pBuf[3] & MOUSE_PS2_BUTTON1DOWN)
2235 		? MOUSE_BUTTON5DOWN : 0;
2236 	    act->dz = (pBuf[3] & MOUSE_PS2_XNEG) ? pBuf[4] - 256 : pBuf[4];
2237 	    break;
2238 	case MOUSE_MODEL_THINK:
2239 	    /* the fourth button state in the first byte */
2240 	    act->button |= (pBuf[0] & MOUSE_PS2_TAP) ? MOUSE_BUTTON4DOWN : 0;
2241 	    break;
2242 	case MOUSE_MODEL_VERSAPAD:
2243 	    act->button = butmapversaps2[pBuf[0] & MOUSE_PS2VERSA_BUTTONS];
2244 	    act->button |=
2245 		(pBuf[0] & MOUSE_PS2VERSA_TAP) ? MOUSE_BUTTON4DOWN : 0;
2246 	    act->dx = act->dy = 0;
2247 	    if (!(pBuf[0] & MOUSE_PS2VERSA_IN_USE)) {
2248 		on = FALSE;
2249 		break;
2250 	    }
2251 	    x = ((pBuf[4] << 8) & 0xf00) | pBuf[1];
2252 	    if (x & 0x800)
2253 		x -= 0x1000;
2254 	    y = ((pBuf[4] << 4) & 0xf00) | pBuf[2];
2255 	    if (y & 0x800)
2256 		y -= 0x1000;
2257 	    if (on) {
2258 		act->dx = prev_x - x;
2259 		act->dy = prev_y - y;
2260 	    } else {
2261 		on = TRUE;
2262 	    }
2263 	    prev_x = x;
2264 	    prev_y = y;
2265 	    break;
2266 	case MOUSE_MODEL_4D:
2267 	    act->dx = (pBuf[1] & 0x80) ?    pBuf[1] - 256  :  pBuf[1];
2268 	    act->dy = (pBuf[2] & 0x80) ?  -(pBuf[2] - 256) : -pBuf[2];
2269 	    switch (pBuf[0] & MOUSE_4D_WHEELBITS) {
2270 	    case 0x10:
2271 		act->dz = 1;
2272 		break;
2273 	    case 0x30:
2274 		act->dz = -1;
2275 		break;
2276 	    case 0x40:	/* 2nd wheel rolling right XXX */
2277 		act->dz = 2;
2278 		break;
2279 	    case 0xc0:	/* 2nd wheel rolling left XXX */
2280 		act->dz = -2;
2281 		break;
2282 	    }
2283 	    break;
2284 	case MOUSE_MODEL_4DPLUS:
2285 	    if ((act->dx < 16 - 256) && (act->dy > 256 - 16)) {
2286 		act->dx = act->dy = 0;
2287 		if (pBuf[2] & MOUSE_4DPLUS_BUTTON4DOWN)
2288 		    act->button |= MOUSE_BUTTON4DOWN;
2289 		act->dz = (pBuf[2] & MOUSE_4DPLUS_ZNEG)
2290 			      ? ((pBuf[2] & 0x07) - 8) : (pBuf[2] & 0x07);
2291 	    } else {
2292 		/* preserve previous button states */
2293 		act->button |= act->obutton & MOUSE_EXTBUTTONS;
2294 	    }
2295 	    break;
2296 	case MOUSE_MODEL_GENERIC:
2297 	default:
2298 	    break;
2299 	}
2300 	break;
2301 
2302     case MOUSE_PROTO_SYSMOUSE:		/* sysmouse */
2303 	act->button = butmapmsc[(~pBuf[0]) & MOUSE_SYS_STDBUTTONS];
2304 	act->dx =    (signed char)(pBuf[1]) + (signed char)(pBuf[3]);
2305 	act->dy = - ((signed char)(pBuf[2]) + (signed char)(pBuf[4]));
2306 	if (rodent.level == 1) {
2307 	    act->dz = ((signed char)(pBuf[5] << 1) + (signed char)(pBuf[6] << 1)) >> 1;
2308 	    act->button |= ((~pBuf[7] & MOUSE_SYS_EXTBUTTONS) << 3);
2309 	}
2310 	break;
2311 
2312     default:
2313 	return (0);
2314     }
2315     /*
2316      * We don't reset pBufP here yet, as there may be an additional data
2317      * byte in some protocols. See above.
2318      */
2319 
2320     /* has something changed? */
2321     act->flags = ((act->dx || act->dy || act->dz) ? MOUSE_POSCHANGED : 0)
2322 	| (act->obutton ^ act->button);
2323 
2324     return (act->flags);
2325 }
2326 
2327 static int
r_statetrans(mousestatus_t * a1,mousestatus_t * a2,int trans)2328 r_statetrans(mousestatus_t *a1, mousestatus_t *a2, int trans)
2329 {
2330     int changed;
2331     int flags;
2332 
2333     a2->dx = a1->dx;
2334     a2->dy = a1->dy;
2335     a2->dz = a1->dz;
2336     a2->obutton = a2->button;
2337     a2->button = a1->button;
2338     a2->flags = a1->flags;
2339     changed = FALSE;
2340 
2341     if (rodent.flags & Emulate3Button) {
2342 	if (debug > 2)
2343 	    debug("state:%d, trans:%d -> state:%d",
2344 		  mouse_button_state, trans,
2345 		  states[mouse_button_state].s[trans]);
2346 	/*
2347 	 * Avoid re-ordering button and movement events. While a button
2348 	 * event is deferred, throw away up to BUTTON2_MAXMOVE movement
2349 	 * events to allow for mouse jitter. If more movement events
2350 	 * occur, then complete the deferred button events immediately.
2351 	 */
2352 	if ((a2->dx != 0 || a2->dy != 0) &&
2353 	    S_DELAYED(states[mouse_button_state].s[trans])) {
2354 		if (++mouse_move_delayed > BUTTON2_MAXMOVE) {
2355 			mouse_move_delayed = 0;
2356 			mouse_button_state =
2357 			    states[mouse_button_state].s[A_TIMEOUT];
2358 			changed = TRUE;
2359 		} else
2360 			a2->dx = a2->dy = 0;
2361 	} else
2362 		mouse_move_delayed = 0;
2363 	if (mouse_button_state != states[mouse_button_state].s[trans])
2364 		changed = TRUE;
2365 	if (changed)
2366 		clock_gettime(CLOCK_MONOTONIC_FAST, &mouse_button_state_ts);
2367 	mouse_button_state = states[mouse_button_state].s[trans];
2368 	a2->button &=
2369 	    ~(MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN);
2370 	a2->button &= states[mouse_button_state].mask;
2371 	a2->button |= states[mouse_button_state].buttons;
2372 	flags = a2->flags & MOUSE_POSCHANGED;
2373 	flags |= a2->obutton ^ a2->button;
2374 	if (flags & MOUSE_BUTTON2DOWN) {
2375 	    a2->flags = flags & MOUSE_BUTTON2DOWN;
2376 	    r_timestamp(a2);
2377 	}
2378 	a2->flags = flags;
2379     }
2380     return (changed);
2381 }
2382 
2383 /* phisical to logical button mapping */
2384 static int p2l[MOUSE_MAXBUTTON] = {
2385     MOUSE_BUTTON1DOWN, MOUSE_BUTTON2DOWN, MOUSE_BUTTON3DOWN, MOUSE_BUTTON4DOWN,
2386     MOUSE_BUTTON5DOWN, MOUSE_BUTTON6DOWN, MOUSE_BUTTON7DOWN, MOUSE_BUTTON8DOWN,
2387     0x00000100,        0x00000200,        0x00000400,        0x00000800,
2388     0x00001000,        0x00002000,        0x00004000,        0x00008000,
2389     0x00010000,        0x00020000,        0x00040000,        0x00080000,
2390     0x00100000,        0x00200000,        0x00400000,        0x00800000,
2391     0x01000000,        0x02000000,        0x04000000,        0x08000000,
2392     0x10000000,        0x20000000,        0x40000000,
2393 };
2394 
2395 static char *
skipspace(char * s)2396 skipspace(char *s)
2397 {
2398     while(isspace(*s))
2399 	++s;
2400     return (s);
2401 }
2402 
2403 static int
r_installmap(char * arg)2404 r_installmap(char *arg)
2405 {
2406     int pbutton;
2407     int lbutton;
2408     char *s;
2409 
2410     while (*arg) {
2411 	arg = skipspace(arg);
2412 	s = arg;
2413 	while (isdigit(*arg))
2414 	    ++arg;
2415 	arg = skipspace(arg);
2416 	if ((arg <= s) || (*arg != '='))
2417 	    return (FALSE);
2418 	lbutton = atoi(s);
2419 
2420 	arg = skipspace(++arg);
2421 	s = arg;
2422 	while (isdigit(*arg))
2423 	    ++arg;
2424 	if ((arg <= s) || (!isspace(*arg) && (*arg != '\0')))
2425 	    return (FALSE);
2426 	pbutton = atoi(s);
2427 
2428 	if ((lbutton <= 0) || (lbutton > MOUSE_MAXBUTTON))
2429 	    return (FALSE);
2430 	if ((pbutton <= 0) || (pbutton > MOUSE_MAXBUTTON))
2431 	    return (FALSE);
2432 	p2l[pbutton - 1] = 1 << (lbutton - 1);
2433 	mstate[lbutton - 1] = &bstate[pbutton - 1];
2434     }
2435 
2436     return (TRUE);
2437 }
2438 
2439 static void
r_map(mousestatus_t * act1,mousestatus_t * act2)2440 r_map(mousestatus_t *act1, mousestatus_t *act2)
2441 {
2442     register int pb;
2443     register int pbuttons;
2444     int lbuttons;
2445 
2446     pbuttons = act1->button;
2447     lbuttons = 0;
2448 
2449     act2->obutton = act2->button;
2450     if (pbuttons & rodent.wmode) {
2451 	pbuttons &= ~rodent.wmode;
2452 	act1->dz = act1->dy;
2453 	act1->dx = 0;
2454 	act1->dy = 0;
2455     }
2456     act2->dx = act1->dx;
2457     act2->dy = act1->dy;
2458     act2->dz = act1->dz;
2459 
2460     switch (rodent.zmap[0]) {
2461     case 0:	/* do nothing */
2462 	break;
2463     case MOUSE_XAXIS:
2464 	if (act1->dz != 0) {
2465 	    act2->dx = act1->dz;
2466 	    act2->dz = 0;
2467 	}
2468 	break;
2469     case MOUSE_YAXIS:
2470 	if (act1->dz != 0) {
2471 	    act2->dy = act1->dz;
2472 	    act2->dz = 0;
2473 	}
2474 	break;
2475     default:	/* buttons */
2476 	pbuttons &= ~(rodent.zmap[0] | rodent.zmap[1]
2477 		    | rodent.zmap[2] | rodent.zmap[3]);
2478 	if ((act1->dz < -1) && rodent.zmap[2]) {
2479 	    pbuttons |= rodent.zmap[2];
2480 	    zstate[2].count = 1;
2481 	} else if (act1->dz < 0) {
2482 	    pbuttons |= rodent.zmap[0];
2483 	    zstate[0].count = 1;
2484 	} else if ((act1->dz > 1) && rodent.zmap[3]) {
2485 	    pbuttons |= rodent.zmap[3];
2486 	    zstate[3].count = 1;
2487 	} else if (act1->dz > 0) {
2488 	    pbuttons |= rodent.zmap[1];
2489 	    zstate[1].count = 1;
2490 	}
2491 	act2->dz = 0;
2492 	break;
2493     }
2494 
2495     for (pb = 0; (pb < MOUSE_MAXBUTTON) && (pbuttons != 0); ++pb) {
2496 	lbuttons |= (pbuttons & 1) ? p2l[pb] : 0;
2497 	pbuttons >>= 1;
2498     }
2499     act2->button = lbuttons;
2500 
2501     act2->flags = ((act2->dx || act2->dy || act2->dz) ? MOUSE_POSCHANGED : 0)
2502 	| (act2->obutton ^ act2->button);
2503 }
2504 
2505 static void
r_timestamp(mousestatus_t * act)2506 r_timestamp(mousestatus_t *act)
2507 {
2508     struct timespec ts;
2509     struct timespec ts1;
2510     struct timespec ts2;
2511     struct timespec ts3;
2512     int button;
2513     int mask;
2514     int i;
2515 
2516     mask = act->flags & MOUSE_BUTTONS;
2517 #if 0
2518     if (mask == 0)
2519 	return;
2520 #endif
2521 
2522     clock_gettime(CLOCK_MONOTONIC_FAST, &ts1);
2523     drift_current_ts = ts1;
2524 
2525     /* double click threshold */
2526     ts2.tv_sec = rodent.clickthreshold / 1000;
2527     ts2.tv_nsec = (rodent.clickthreshold % 1000) * 1000000;
2528     tssub(&ts1, &ts2, &ts);
2529     debug("ts:  %jd %ld", (intmax_t)ts.tv_sec, ts.tv_nsec);
2530 
2531     /* 3 button emulation timeout */
2532     ts2.tv_sec = rodent.button2timeout / 1000;
2533     ts2.tv_nsec = (rodent.button2timeout % 1000) * 1000000;
2534     tssub(&ts1, &ts2, &ts3);
2535 
2536     button = MOUSE_BUTTON1DOWN;
2537     for (i = 0; (i < MOUSE_MAXBUTTON) && (mask != 0); ++i) {
2538 	if (mask & 1) {
2539 	    if (act->button & button) {
2540 		/* the button is down */
2541 		debug("  :  %jd %ld",
2542 		    (intmax_t)bstate[i].ts.tv_sec, bstate[i].ts.tv_nsec);
2543 		if (tscmp(&ts, &bstate[i].ts, >)) {
2544 		    bstate[i].count = 1;
2545 		} else {
2546 		    ++bstate[i].count;
2547 		}
2548 		bstate[i].ts = ts1;
2549 	    } else {
2550 		/* the button is up */
2551 		bstate[i].ts = ts1;
2552 	    }
2553 	} else {
2554 	    if (act->button & button) {
2555 		/* the button has been down */
2556 		if (tscmp(&ts3, &bstate[i].ts, >)) {
2557 		    bstate[i].count = 1;
2558 		    bstate[i].ts = ts1;
2559 		    act->flags |= button;
2560 		    debug("button %d timeout", i + 1);
2561 		}
2562 	    } else {
2563 		/* the button has been up */
2564 	    }
2565 	}
2566 	button <<= 1;
2567 	mask >>= 1;
2568     }
2569 }
2570 
2571 static int
r_timeout(void)2572 r_timeout(void)
2573 {
2574     struct timespec ts;
2575     struct timespec ts1;
2576     struct timespec ts2;
2577 
2578     if (states[mouse_button_state].timeout)
2579 	return (TRUE);
2580     clock_gettime(CLOCK_MONOTONIC_FAST, &ts1);
2581     ts2.tv_sec = rodent.button2timeout / 1000;
2582     ts2.tv_nsec = (rodent.button2timeout % 1000) * 1000000;
2583     tssub(&ts1, &ts2, &ts);
2584     return (tscmp(&ts, &mouse_button_state_ts, >));
2585 }
2586 
2587 static void
r_click(mousestatus_t * act)2588 r_click(mousestatus_t *act)
2589 {
2590     struct mouse_info mouse;
2591     int button;
2592     int mask;
2593     int i;
2594 
2595     mask = act->flags & MOUSE_BUTTONS;
2596     if (mask == 0)
2597 	return;
2598 
2599     button = MOUSE_BUTTON1DOWN;
2600     for (i = 0; (i < MOUSE_MAXBUTTON) && (mask != 0); ++i) {
2601 	if (mask & 1) {
2602 	    debug("mstate[%d]->count:%d", i, mstate[i]->count);
2603 	    if (act->button & button) {
2604 		/* the button is down */
2605 		mouse.u.event.value = mstate[i]->count;
2606 	    } else {
2607 		/* the button is up */
2608 		mouse.u.event.value = 0;
2609 	    }
2610 	    mouse.operation = MOUSE_BUTTON_EVENT;
2611 	    mouse.u.event.id = button;
2612 	    if (debug < 2)
2613 		if (!paused)
2614 		    ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
2615 	    debug("button %d  count %d", i + 1, mouse.u.event.value);
2616 	}
2617 	button <<= 1;
2618 	mask >>= 1;
2619     }
2620 }
2621 
2622 /* $XConsortium: posix_tty.c,v 1.3 95/01/05 20:42:55 kaleb Exp $ */
2623 /* $XFree86: xc/programs/Xserver/hw/xfree86/os-support/shared/posix_tty.c,v 3.4 1995/01/28 17:05:03 dawes Exp $ */
2624 /*
2625  * Copyright 1993 by David Dawes <dawes@physics.su.oz.au>
2626  *
2627  * Permission to use, copy, modify, distribute, and sell this software and its
2628  * documentation for any purpose is hereby granted without fee, provided that
2629  * the above copyright notice appear in all copies and that both that
2630  * copyright notice and this permission notice appear in supporting
2631  * documentation, and that the name of David Dawes
2632  * not be used in advertising or publicity pertaining to distribution of
2633  * the software without specific, written prior permission.
2634  * David Dawes makes no representations about the suitability of this
2635  * software for any purpose.  It is provided "as is" without express or
2636  * implied warranty.
2637  *
2638  * DAVID DAWES DISCLAIMS ALL WARRANTIES WITH REGARD TO
2639  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
2640  * FITNESS, IN NO EVENT SHALL DAVID DAWES BE LIABLE FOR
2641  * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
2642  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
2643  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
2644  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
2645  *
2646  */
2647 
2648 
2649 static void
setmousespeed(int old,int new,unsigned cflag)2650 setmousespeed(int old, int new, unsigned cflag)
2651 {
2652 	struct termios tty;
2653 	const char *c;
2654 
2655 	if (tcgetattr(rodent.mfd, &tty) < 0)
2656 	{
2657 		logwarn("unable to get status of mouse fd");
2658 		return;
2659 	}
2660 
2661 	tty.c_iflag = IGNBRK | IGNPAR;
2662 	tty.c_oflag = 0;
2663 	tty.c_lflag = 0;
2664 	tty.c_cflag = (tcflag_t)cflag;
2665 	tty.c_cc[VTIME] = 0;
2666 	tty.c_cc[VMIN] = 1;
2667 
2668 	switch (old)
2669 	{
2670 	case 9600:
2671 		cfsetispeed(&tty, B9600);
2672 		cfsetospeed(&tty, B9600);
2673 		break;
2674 	case 4800:
2675 		cfsetispeed(&tty, B4800);
2676 		cfsetospeed(&tty, B4800);
2677 		break;
2678 	case 2400:
2679 		cfsetispeed(&tty, B2400);
2680 		cfsetospeed(&tty, B2400);
2681 		break;
2682 	case 1200:
2683 	default:
2684 		cfsetispeed(&tty, B1200);
2685 		cfsetospeed(&tty, B1200);
2686 	}
2687 
2688 	if (tcsetattr(rodent.mfd, TCSADRAIN, &tty) < 0)
2689 	{
2690 		logwarn("unable to set status of mouse fd");
2691 		return;
2692 	}
2693 
2694 	switch (new)
2695 	{
2696 	case 9600:
2697 		c = "*q";
2698 		cfsetispeed(&tty, B9600);
2699 		cfsetospeed(&tty, B9600);
2700 		break;
2701 	case 4800:
2702 		c = "*p";
2703 		cfsetispeed(&tty, B4800);
2704 		cfsetospeed(&tty, B4800);
2705 		break;
2706 	case 2400:
2707 		c = "*o";
2708 		cfsetispeed(&tty, B2400);
2709 		cfsetospeed(&tty, B2400);
2710 		break;
2711 	case 1200:
2712 	default:
2713 		c = "*n";
2714 		cfsetispeed(&tty, B1200);
2715 		cfsetospeed(&tty, B1200);
2716 	}
2717 
2718 	if (rodent.rtype == MOUSE_PROTO_LOGIMOUSEMAN
2719 	    || rodent.rtype == MOUSE_PROTO_LOGI)
2720 	{
2721 		if (write(rodent.mfd, c, 2) != 2)
2722 		{
2723 			logwarn("unable to write to mouse fd");
2724 			return;
2725 		}
2726 	}
2727 	usleep(100000);
2728 
2729 	if (tcsetattr(rodent.mfd, TCSADRAIN, &tty) < 0)
2730 		logwarn("unable to set status of mouse fd");
2731 }
2732 
2733 /*
2734  * PnP COM device support
2735  *
2736  * It's a simplistic implementation, but it works :-)
2737  * KY, 31/7/97.
2738  */
2739 
2740 /*
2741  * Try to elicit a PnP ID as described in
2742  * Microsoft, Hayes: "Plug and Play External COM Device Specification,
2743  * rev 1.00", 1995.
2744  *
2745  * The routine does not fully implement the COM Enumerator as par Section
2746  * 2.1 of the document.  In particular, we don't have idle state in which
2747  * the driver software monitors the com port for dynamic connection or
2748  * removal of a device at the port, because `moused' simply quits if no
2749  * device is found.
2750  *
2751  * In addition, as PnP COM device enumeration procedure slightly has
2752  * changed since its first publication, devices which follow earlier
2753  * revisions of the above spec. may fail to respond if the rev 1.0
2754  * procedure is used. XXX
2755  */
2756 static int
pnpwakeup1(void)2757 pnpwakeup1(void)
2758 {
2759     struct timeval timeout;
2760     fd_set fds;
2761     int i;
2762 
2763     /*
2764      * This is the procedure described in rev 1.0 of PnP COM device spec.
2765      * Unfortunately, some devices which comform to earlier revisions of
2766      * the spec gets confused and do not return the ID string...
2767      */
2768     debug("PnP COM device rev 1.0 probe...");
2769 
2770     /* port initialization (2.1.2) */
2771     ioctl(rodent.mfd, TIOCMGET, &i);
2772     i |= TIOCM_DTR;		/* DTR = 1 */
2773     i &= ~TIOCM_RTS;		/* RTS = 0 */
2774     ioctl(rodent.mfd, TIOCMSET, &i);
2775     usleep(240000);
2776 
2777     /*
2778      * The PnP COM device spec. dictates that the mouse must set DSR
2779      * in response to DTR (by hardware or by software) and that if DSR is
2780      * not asserted, the host computer should think that there is no device
2781      * at this serial port.  But some mice just don't do that...
2782      */
2783     ioctl(rodent.mfd, TIOCMGET, &i);
2784     debug("modem status 0%o", i);
2785     if ((i & TIOCM_DSR) == 0)
2786 	return (FALSE);
2787 
2788     /* port setup, 1st phase (2.1.3) */
2789     setmousespeed(1200, 1200, (CS7 | CREAD | CLOCAL | HUPCL));
2790     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 0, RTS = 0 */
2791     ioctl(rodent.mfd, TIOCMBIC, &i);
2792     usleep(240000);
2793     i = TIOCM_DTR;		/* DTR = 1, RTS = 0 */
2794     ioctl(rodent.mfd, TIOCMBIS, &i);
2795     usleep(240000);
2796 
2797     /* wait for response, 1st phase (2.1.4) */
2798     i = FREAD;
2799     ioctl(rodent.mfd, TIOCFLUSH, &i);
2800     i = TIOCM_RTS;		/* DTR = 1, RTS = 1 */
2801     ioctl(rodent.mfd, TIOCMBIS, &i);
2802 
2803     /* try to read something */
2804     FD_ZERO(&fds);
2805     FD_SET(rodent.mfd, &fds);
2806     timeout.tv_sec = 0;
2807     timeout.tv_usec = 240000;
2808     if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) > 0) {
2809 	debug("pnpwakeup1(): valid response in first phase.");
2810 	return (TRUE);
2811     }
2812 
2813     /* port setup, 2nd phase (2.1.5) */
2814     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 0, RTS = 0 */
2815     ioctl(rodent.mfd, TIOCMBIC, &i);
2816     usleep(240000);
2817 
2818     /* wait for respose, 2nd phase (2.1.6) */
2819     i = FREAD;
2820     ioctl(rodent.mfd, TIOCFLUSH, &i);
2821     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 1, RTS = 1 */
2822     ioctl(rodent.mfd, TIOCMBIS, &i);
2823 
2824     /* try to read something */
2825     FD_ZERO(&fds);
2826     FD_SET(rodent.mfd, &fds);
2827     timeout.tv_sec = 0;
2828     timeout.tv_usec = 240000;
2829     if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) > 0) {
2830 	debug("pnpwakeup1(): valid response in second phase.");
2831 	return (TRUE);
2832     }
2833 
2834     return (FALSE);
2835 }
2836 
2837 static int
pnpwakeup2(void)2838 pnpwakeup2(void)
2839 {
2840     struct timeval timeout;
2841     fd_set fds;
2842     int i;
2843 
2844     /*
2845      * This is a simplified procedure; it simply toggles RTS.
2846      */
2847     debug("alternate probe...");
2848 
2849     ioctl(rodent.mfd, TIOCMGET, &i);
2850     i |= TIOCM_DTR;		/* DTR = 1 */
2851     i &= ~TIOCM_RTS;		/* RTS = 0 */
2852     ioctl(rodent.mfd, TIOCMSET, &i);
2853     usleep(240000);
2854 
2855     setmousespeed(1200, 1200, (CS7 | CREAD | CLOCAL | HUPCL));
2856 
2857     /* wait for respose */
2858     i = FREAD;
2859     ioctl(rodent.mfd, TIOCFLUSH, &i);
2860     i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 1, RTS = 1 */
2861     ioctl(rodent.mfd, TIOCMBIS, &i);
2862 
2863     /* try to read something */
2864     FD_ZERO(&fds);
2865     FD_SET(rodent.mfd, &fds);
2866     timeout.tv_sec = 0;
2867     timeout.tv_usec = 240000;
2868     if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) > 0) {
2869 	debug("pnpwakeup2(): valid response.");
2870 	return (TRUE);
2871     }
2872 
2873     return (FALSE);
2874 }
2875 
2876 static int
pnpgets(char * buf)2877 pnpgets(char *buf)
2878 {
2879     struct timeval timeout;
2880     fd_set fds;
2881     int begin;
2882     int i;
2883     char c;
2884 
2885     if (!pnpwakeup1() && !pnpwakeup2()) {
2886 	/*
2887 	 * According to PnP spec, we should set DTR = 1 and RTS = 0 while
2888 	 * in idle state.  But, `moused' shall set DTR = RTS = 1 and proceed,
2889 	 * assuming there is something at the port even if it didn't
2890 	 * respond to the PnP enumeration procedure.
2891 	 */
2892 	i = TIOCM_DTR | TIOCM_RTS;		/* DTR = 1, RTS = 1 */
2893 	ioctl(rodent.mfd, TIOCMBIS, &i);
2894 	return (0);
2895     }
2896 
2897     /* collect PnP COM device ID (2.1.7) */
2898     begin = -1;
2899     i = 0;
2900     usleep(240000);	/* the mouse must send `Begin ID' within 200msec */
2901     while (read(rodent.mfd, &c, 1) == 1) {
2902 	/* we may see "M", or "M3..." before `Begin ID' */
2903 	buf[i++] = c;
2904 	if ((c == 0x08) || (c == 0x28)) {	/* Begin ID */
2905 	    debug("begin-id %02x", c);
2906 	    begin = i - 1;
2907 	    break;
2908 	}
2909 	debug("%c %02x", c, c);
2910 	if (i >= 256)
2911 	    break;
2912     }
2913     if (begin < 0) {
2914 	/* we haven't seen `Begin ID' in time... */
2915 	goto connect_idle;
2916     }
2917 
2918     ++c;			/* make it `End ID' */
2919     for (;;) {
2920 	FD_ZERO(&fds);
2921 	FD_SET(rodent.mfd, &fds);
2922 	timeout.tv_sec = 0;
2923 	timeout.tv_usec = 240000;
2924 	if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) <= 0)
2925 	    break;
2926 
2927 	read(rodent.mfd, &buf[i], 1);
2928 	if (buf[i++] == c)	/* End ID */
2929 	    break;
2930 	if (i >= 256)
2931 	    break;
2932     }
2933     if (begin > 0) {
2934 	i -= begin;
2935 	bcopy(&buf[begin], &buf[0], i);
2936     }
2937     /* string may not be human readable... */
2938     debug("len:%d, '%-*.*s'", i, i, i, buf);
2939 
2940     if (buf[i - 1] == c)
2941 	return (i);		/* a valid PnP string */
2942 
2943     /*
2944      * According to PnP spec, we should set DTR = 1 and RTS = 0 while
2945      * in idle state.  But, `moused' shall leave the modem control lines
2946      * as they are. See above.
2947      */
2948 connect_idle:
2949 
2950     /* we may still have something in the buffer */
2951     return (MAX(i, 0));
2952 }
2953 
2954 static int
pnpparse(pnpid_t * id,char * buf,int len)2955 pnpparse(pnpid_t *id, char *buf, int len)
2956 {
2957     char s[3];
2958     int offset;
2959     int sum = 0;
2960     int i, j;
2961 
2962     id->revision = 0;
2963     id->eisaid = NULL;
2964     id->serial = NULL;
2965     id->class = NULL;
2966     id->compat = NULL;
2967     id->description = NULL;
2968     id->neisaid = 0;
2969     id->nserial = 0;
2970     id->nclass = 0;
2971     id->ncompat = 0;
2972     id->ndescription = 0;
2973 
2974     if ((buf[0] != 0x28) && (buf[0] != 0x08)) {
2975 	/* non-PnP mice */
2976 	switch(buf[0]) {
2977 	default:
2978 	    return (FALSE);
2979 	case 'M': /* Microsoft */
2980 	    id->eisaid = "PNP0F01";
2981 	    break;
2982 	case 'H': /* MouseSystems */
2983 	    id->eisaid = "PNP0F04";
2984 	    break;
2985 	}
2986 	id->neisaid = strlen(id->eisaid);
2987 	id->class = "MOUSE";
2988 	id->nclass = strlen(id->class);
2989 	debug("non-PnP mouse '%c'", buf[0]);
2990 	return (TRUE);
2991     }
2992 
2993     /* PnP mice */
2994     offset = 0x28 - buf[0];
2995 
2996     /* calculate checksum */
2997     for (i = 0; i < len - 3; ++i) {
2998 	sum += buf[i];
2999 	buf[i] += offset;
3000     }
3001     sum += buf[len - 1];
3002     for (; i < len; ++i)
3003 	buf[i] += offset;
3004     debug("PnP ID string: '%*.*s'", len, len, buf);
3005 
3006     /* revision */
3007     buf[1] -= offset;
3008     buf[2] -= offset;
3009     id->revision = ((buf[1] & 0x3f) << 6) | (buf[2] & 0x3f);
3010     debug("PnP rev %d.%02d", id->revision / 100, id->revision % 100);
3011 
3012     /* EISA vendor and product ID */
3013     id->eisaid = &buf[3];
3014     id->neisaid = 7;
3015 
3016     /* option strings */
3017     i = 10;
3018     if (buf[i] == '\\') {
3019 	/* device serial # */
3020 	for (j = ++i; i < len; ++i) {
3021 	    if (buf[i] == '\\')
3022 		break;
3023 	}
3024 	if (i >= len)
3025 	    i -= 3;
3026 	if (i - j == 8) {
3027 	    id->serial = &buf[j];
3028 	    id->nserial = 8;
3029 	}
3030     }
3031     if (buf[i] == '\\') {
3032 	/* PnP class */
3033 	for (j = ++i; i < len; ++i) {
3034 	    if (buf[i] == '\\')
3035 		break;
3036 	}
3037 	if (i >= len)
3038 	    i -= 3;
3039 	if (i > j + 1) {
3040 	    id->class = &buf[j];
3041 	    id->nclass = i - j;
3042 	}
3043     }
3044     if (buf[i] == '\\') {
3045 	/* compatible driver */
3046 	for (j = ++i; i < len; ++i) {
3047 	    if (buf[i] == '\\')
3048 		break;
3049 	}
3050 	/*
3051 	 * PnP COM spec prior to v0.96 allowed '*' in this field,
3052 	 * it's not allowed now; just ignore it.
3053 	 */
3054 	if (buf[j] == '*')
3055 	    ++j;
3056 	if (i >= len)
3057 	    i -= 3;
3058 	if (i > j + 1) {
3059 	    id->compat = &buf[j];
3060 	    id->ncompat = i - j;
3061 	}
3062     }
3063     if (buf[i] == '\\') {
3064 	/* product description */
3065 	for (j = ++i; i < len; ++i) {
3066 	    if (buf[i] == ';')
3067 		break;
3068 	}
3069 	if (i >= len)
3070 	    i -= 3;
3071 	if (i > j + 1) {
3072 	    id->description = &buf[j];
3073 	    id->ndescription = i - j;
3074 	}
3075     }
3076 
3077     /* checksum exists if there are any optional fields */
3078     if ((id->nserial > 0) || (id->nclass > 0)
3079 	|| (id->ncompat > 0) || (id->ndescription > 0)) {
3080 	debug("PnP checksum: 0x%X", sum);
3081 	sprintf(s, "%02X", sum & 0x0ff);
3082 	if (strncmp(s, &buf[len - 3], 2) != 0) {
3083 #if 0
3084 	    /*
3085 	     * I found some mice do not comply with the PnP COM device
3086 	     * spec regarding checksum... XXX
3087 	     */
3088 	    logwarnx("PnP checksum error", 0);
3089 	    return (FALSE);
3090 #endif
3091 	}
3092     }
3093 
3094     return (TRUE);
3095 }
3096 
3097 static symtab_t *
pnpproto(pnpid_t * id)3098 pnpproto(pnpid_t *id)
3099 {
3100     symtab_t *t;
3101     int i, j;
3102 
3103     if (id->nclass > 0)
3104 	if (strncmp(id->class, "MOUSE", id->nclass) != 0 &&
3105 	    strncmp(id->class, "TABLET", id->nclass) != 0)
3106 	    /* this is not a mouse! */
3107 	    return (NULL);
3108 
3109     if (id->neisaid > 0) {
3110 	t = gettoken(pnpprod, id->eisaid, id->neisaid);
3111 	if (t->val != MOUSE_PROTO_UNKNOWN)
3112 	    return (t);
3113     }
3114 
3115     /*
3116      * The 'Compatible drivers' field may contain more than one
3117      * ID separated by ','.
3118      */
3119     if (id->ncompat <= 0)
3120 	return (NULL);
3121     for (i = 0; i < id->ncompat; ++i) {
3122 	for (j = i; id->compat[i] != ','; ++i)
3123 	    if (i >= id->ncompat)
3124 		break;
3125 	if (i > j) {
3126 	    t = gettoken(pnpprod, id->compat + j, i - j);
3127 	    if (t->val != MOUSE_PROTO_UNKNOWN)
3128 		return (t);
3129 	}
3130     }
3131 
3132     return (NULL);
3133 }
3134 
3135 /* name/val mapping */
3136 
3137 static symtab_t *
gettoken(symtab_t * tab,const char * s,int len)3138 gettoken(symtab_t *tab, const char *s, int len)
3139 {
3140     int i;
3141 
3142     for (i = 0; tab[i].name != NULL; ++i) {
3143 	if (strncmp(tab[i].name, s, len) == 0)
3144 	    break;
3145     }
3146     return (&tab[i]);
3147 }
3148 
3149 static const char *
gettokenname(symtab_t * tab,int val)3150 gettokenname(symtab_t *tab, int val)
3151 {
3152     static const char unknown[] = "unknown";
3153     int i;
3154 
3155     for (i = 0; tab[i].name != NULL; ++i) {
3156 	if (tab[i].val == val)
3157 	    return (tab[i].name);
3158     }
3159     return (unknown);
3160 }
3161 
3162 
3163 /*
3164  * code to read from the Genius Kidspad tablet.
3165 
3166 The tablet responds to the COM PnP protocol 1.0 with EISA-ID KYE0005,
3167 and to pre-pnp probes (RTS toggle) with 'T' (tablet ?)
3168 9600, 8 bit, parity odd.
3169 
3170 The tablet puts out 5 bytes. b0 (mask 0xb8, value 0xb8) contains
3171 the proximity, tip and button info:
3172    (byte0 & 0x1)	true = tip pressed
3173    (byte0 & 0x2)	true = button pressed
3174    (byte0 & 0x40)	false = pen in proximity of tablet.
3175 
3176 The next 4 bytes are used for coordinates xl, xh, yl, yh (7 bits valid).
3177 
3178 Only absolute coordinates are returned, so we use the following approach:
3179 we store the last coordinates sent when the pen went out of the tablet,
3180 
3181 
3182  *
3183  */
3184 
3185 typedef enum {
3186     S_IDLE, S_PROXY, S_FIRST, S_DOWN, S_UP
3187 } k_status;
3188 
3189 static int
kidspad(u_char rxc,mousestatus_t * act)3190 kidspad(u_char rxc, mousestatus_t *act)
3191 {
3192     static int buf[5];
3193     static int buflen = 0, b_prev = 0 , x_prev = -1, y_prev = -1;
3194     static k_status status = S_IDLE;
3195     static struct timespec now;
3196 
3197     int x, y;
3198 
3199     if (buflen > 0 && (rxc & 0x80)) {
3200 	fprintf(stderr, "invalid code %d 0x%x\n", buflen, rxc);
3201 	buflen = 0;
3202     }
3203     if (buflen == 0 && (rxc & 0xb8) != 0xb8) {
3204 	fprintf(stderr, "invalid code 0 0x%x\n", rxc);
3205 	return (0);	/* invalid code, no action */
3206     }
3207     buf[buflen++] = rxc;
3208     if (buflen < 5)
3209 	return (0);
3210 
3211     buflen = 0;	/* for next time... */
3212 
3213     x = buf[1]+128*(buf[2] - 7);
3214     if (x < 0) x = 0;
3215     y = 28*128 - (buf[3] + 128* (buf[4] - 7));
3216     if (y < 0) y = 0;
3217 
3218     x /= 8;
3219     y /= 8;
3220 
3221     act->flags = 0;
3222     act->obutton = act->button;
3223     act->dx = act->dy = act->dz = 0;
3224     clock_gettime(CLOCK_MONOTONIC_FAST, &now);
3225     if (buf[0] & 0x40) /* pen went out of reach */
3226 	status = S_IDLE;
3227     else if (status == S_IDLE) { /* pen is newly near the tablet */
3228 	act->flags |= MOUSE_POSCHANGED;	/* force update */
3229 	status = S_PROXY;
3230 	x_prev = x;
3231 	y_prev = y;
3232     }
3233     act->dx = x - x_prev;
3234     act->dy = y - y_prev;
3235     if (act->dx || act->dy)
3236 	act->flags |= MOUSE_POSCHANGED;
3237     x_prev = x;
3238     y_prev = y;
3239     if (b_prev != 0 && b_prev != buf[0]) { /* possibly record button change */
3240 	act->button = 0;
3241 	if (buf[0] & 0x01) /* tip pressed */
3242 	    act->button |= MOUSE_BUTTON1DOWN;
3243 	if (buf[0] & 0x02) /* button pressed */
3244 	    act->button |= MOUSE_BUTTON2DOWN;
3245 	act->flags |= MOUSE_BUTTONSCHANGED;
3246     }
3247     b_prev = buf[0];
3248     return (act->flags);
3249 }
3250 
3251 static int
gtco_digipad(u_char rxc,mousestatus_t * act)3252 gtco_digipad (u_char rxc, mousestatus_t *act)
3253 {
3254 	static u_char buf[5];
3255  	static int buflen = 0, b_prev = 0 , x_prev = -1, y_prev = -1;
3256 	static k_status status = S_IDLE;
3257 	int x, y;
3258 
3259 #define	GTCO_HEADER	0x80
3260 #define	GTCO_PROXIMITY	0x40
3261 #define	GTCO_START	(GTCO_HEADER|GTCO_PROXIMITY)
3262 #define	GTCO_BUTTONMASK	0x3c
3263 
3264 
3265 	if (buflen > 0 && ((rxc & GTCO_HEADER) != GTCO_HEADER)) {
3266 		fprintf(stderr, "invalid code %d 0x%x\n", buflen, rxc);
3267 		buflen = 0;
3268 	}
3269 	if (buflen == 0 && (rxc & GTCO_START) != GTCO_START) {
3270 		fprintf(stderr, "invalid code 0 0x%x\n", rxc);
3271 		return (0);	/* invalid code, no action */
3272 	}
3273 
3274 	buf[buflen++] = rxc;
3275 	if (buflen < 5)
3276 		return (0);
3277 
3278 	buflen = 0;	/* for next time... */
3279 
3280 	x = ((buf[2] & ~GTCO_START) << 6 | (buf[1] & ~GTCO_START));
3281 	y = 4768 - ((buf[4] & ~GTCO_START) << 6 | (buf[3] & ~GTCO_START));
3282 
3283 	x /= 2.5;
3284 	y /= 2.5;
3285 
3286 	act->flags = 0;
3287 	act->obutton = act->button;
3288 	act->dx = act->dy = act->dz = 0;
3289 
3290 	if ((buf[0] & 0x40) == 0) /* pen went out of reach */
3291 		status = S_IDLE;
3292 	else if (status == S_IDLE) { /* pen is newly near the tablet */
3293 		act->flags |= MOUSE_POSCHANGED;	/* force update */
3294 		status = S_PROXY;
3295 		x_prev = x;
3296 		y_prev = y;
3297 	}
3298 
3299 	act->dx = x - x_prev;
3300 	act->dy = y - y_prev;
3301 	if (act->dx || act->dy)
3302 		act->flags |= MOUSE_POSCHANGED;
3303 	x_prev = x;
3304 	y_prev = y;
3305 
3306 	/* possibly record button change */
3307 	if (b_prev != 0 && b_prev != buf[0]) {
3308 		act->button = 0;
3309 		if (buf[0] & 0x04) {
3310 			/* tip pressed/yellow */
3311 			act->button |= MOUSE_BUTTON1DOWN;
3312 		}
3313 		if (buf[0] & 0x08) {
3314 			/* grey/white */
3315 			act->button |= MOUSE_BUTTON2DOWN;
3316 		}
3317 		if (buf[0] & 0x10) {
3318 			/* black/green */
3319 			act->button |= MOUSE_BUTTON3DOWN;
3320 		}
3321 		if (buf[0] & 0x20) {
3322 			/* tip+grey/blue */
3323 			act->button |= MOUSE_BUTTON4DOWN;
3324 		}
3325 		act->flags |= MOUSE_BUTTONSCHANGED;
3326 	}
3327 	b_prev = buf[0];
3328 	return (act->flags);
3329 }
3330 
3331 static void
mremote_serversetup(void)3332 mremote_serversetup(void)
3333 {
3334     struct sockaddr_un ad;
3335 
3336     /* Open a UNIX domain stream socket to listen for mouse remote clients */
3337     unlink(_PATH_MOUSEREMOTE);
3338 
3339     if ((rodent.mremsfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
3340 	logerrx(1, "unable to create unix domain socket %s",_PATH_MOUSEREMOTE);
3341 
3342     umask(0111);
3343 
3344     bzero(&ad, sizeof(ad));
3345     ad.sun_family = AF_UNIX;
3346     strcpy(ad.sun_path, _PATH_MOUSEREMOTE);
3347 #ifndef SUN_LEN
3348 #define SUN_LEN(unp) (((char *)(unp)->sun_path - (char *)(unp)) + \
3349 		       strlen((unp)->path))
3350 #endif
3351     if (bind(rodent.mremsfd, (struct sockaddr *) &ad, SUN_LEN(&ad)) < 0)
3352 	logerrx(1, "unable to bind unix domain socket %s", _PATH_MOUSEREMOTE);
3353 
3354     listen(rodent.mremsfd, 1);
3355 }
3356 
3357 static void
mremote_clientchg(int add)3358 mremote_clientchg(int add)
3359 {
3360     struct sockaddr_un ad;
3361     socklen_t ad_len;
3362     int fd;
3363 
3364     if (rodent.rtype != MOUSE_PROTO_X10MOUSEREM)
3365 	return;
3366 
3367     if (add) {
3368 	/*  Accept client connection, if we don't already have one  */
3369 	ad_len = sizeof(ad);
3370 	fd = accept(rodent.mremsfd, (struct sockaddr *) &ad, &ad_len);
3371 	if (fd < 0)
3372 	    logwarnx("failed accept on mouse remote socket");
3373 
3374 	if (rodent.mremcfd < 0) {
3375 	    rodent.mremcfd = fd;
3376 	    debug("remote client connect...accepted");
3377 	}
3378 	else {
3379 	    close(fd);
3380 	    debug("another remote client connect...disconnected");
3381 	}
3382     }
3383     else {
3384 	/* Client disconnected */
3385 	debug("remote client disconnected");
3386 	close(rodent.mremcfd);
3387 	rodent.mremcfd = -1;
3388     }
3389 }
3390