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