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