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