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