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