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