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