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