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