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