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