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