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