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