moused.c revision 79430
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 79430 2001-07-08 20:23:59Z iedowse $";
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",
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 <info> -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			mouse_move_delayed++;
1995		}
1996	} else
1997		mouse_move_delayed = 0;
1998	if (mouse_button_state != states[mouse_button_state].s[trans])
1999		changed = TRUE;
2000	if (changed)
2001		gettimeofday(&mouse_button_state_tv, NULL);
2002	mouse_button_state = states[mouse_button_state].s[trans];
2003	a2->button &=
2004	    ~(MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN);
2005	a2->button &= states[mouse_button_state].mask;
2006	a2->button |= states[mouse_button_state].buttons;
2007	flags = a2->flags & MOUSE_POSCHANGED;
2008	flags |= a2->obutton ^ a2->button;
2009	if (flags & MOUSE_BUTTON2DOWN) {
2010	    a2->flags = flags & MOUSE_BUTTON2DOWN;
2011	    r_timestamp(a2);
2012	}
2013	a2->flags = flags;
2014    }
2015    return changed;
2016}
2017
2018/* phisical to logical button mapping */
2019static int p2l[MOUSE_MAXBUTTON] = {
2020    MOUSE_BUTTON1DOWN, MOUSE_BUTTON2DOWN, MOUSE_BUTTON3DOWN, MOUSE_BUTTON4DOWN,
2021    MOUSE_BUTTON5DOWN, MOUSE_BUTTON6DOWN, MOUSE_BUTTON7DOWN, MOUSE_BUTTON8DOWN,
2022    0x00000100,        0x00000200,        0x00000400,        0x00000800,
2023    0x00001000,        0x00002000,        0x00004000,        0x00008000,
2024    0x00010000,        0x00020000,        0x00040000,        0x00080000,
2025    0x00100000,        0x00200000,        0x00400000,        0x00800000,
2026    0x01000000,        0x02000000,        0x04000000,        0x08000000,
2027    0x10000000,        0x20000000,        0x40000000,
2028};
2029
2030static char *
2031skipspace(char *s)
2032{
2033    while(isspace(*s))
2034	++s;
2035    return s;
2036}
2037
2038static int
2039r_installmap(char *arg)
2040{
2041    int pbutton;
2042    int lbutton;
2043    char *s;
2044
2045    while (*arg) {
2046	arg = skipspace(arg);
2047	s = arg;
2048	while (isdigit(*arg))
2049	    ++arg;
2050	arg = skipspace(arg);
2051	if ((arg <= s) || (*arg != '='))
2052	    return FALSE;
2053	lbutton = atoi(s);
2054
2055	arg = skipspace(++arg);
2056	s = arg;
2057	while (isdigit(*arg))
2058	    ++arg;
2059	if ((arg <= s) || (!isspace(*arg) && (*arg != '\0')))
2060	    return FALSE;
2061	pbutton = atoi(s);
2062
2063	if ((lbutton <= 0) || (lbutton > MOUSE_MAXBUTTON))
2064	    return FALSE;
2065	if ((pbutton <= 0) || (pbutton > MOUSE_MAXBUTTON))
2066	    return FALSE;
2067	p2l[pbutton - 1] = 1 << (lbutton - 1);
2068	mstate[lbutton - 1] = &bstate[pbutton - 1];
2069    }
2070
2071    return TRUE;
2072}
2073
2074static void
2075r_map(mousestatus_t *act1, mousestatus_t *act2)
2076{
2077    register int pb;
2078    register int pbuttons;
2079    int lbuttons;
2080
2081    pbuttons = act1->button;
2082    lbuttons = 0;
2083
2084    act2->obutton = act2->button;
2085    if (pbuttons & rodent.wmode) {
2086	pbuttons &= ~rodent.wmode;
2087	act1->dz = act1->dy;
2088	act1->dx = 0;
2089	act1->dy = 0;
2090    }
2091    act2->dx = act1->dx;
2092    act2->dy = act1->dy;
2093    act2->dz = act1->dz;
2094
2095    switch (rodent.zmap[0]) {
2096    case 0:	/* do nothing */
2097	break;
2098    case MOUSE_XAXIS:
2099	if (act1->dz != 0) {
2100	    act2->dx = act1->dz;
2101	    act2->dz = 0;
2102	}
2103	break;
2104    case MOUSE_YAXIS:
2105	if (act1->dz != 0) {
2106	    act2->dy = act1->dz;
2107	    act2->dz = 0;
2108	}
2109	break;
2110    default:	/* buttons */
2111	pbuttons &= ~(rodent.zmap[0] | rodent.zmap[1]
2112		    | rodent.zmap[2] | rodent.zmap[3]);
2113	if ((act1->dz < -1) && rodent.zmap[2]) {
2114	    pbuttons |= rodent.zmap[2];
2115	    zstate[2].count = 1;
2116	} else if (act1->dz < 0) {
2117	    pbuttons |= rodent.zmap[0];
2118	    zstate[0].count = 1;
2119	} else if ((act1->dz > 1) && rodent.zmap[3]) {
2120	    pbuttons |= rodent.zmap[3];
2121	    zstate[3].count = 1;
2122	} else if (act1->dz > 0) {
2123	    pbuttons |= rodent.zmap[1];
2124	    zstate[1].count = 1;
2125	}
2126	act2->dz = 0;
2127	break;
2128    }
2129
2130    for (pb = 0; (pb < MOUSE_MAXBUTTON) && (pbuttons != 0); ++pb) {
2131	lbuttons |= (pbuttons & 1) ? p2l[pb] : 0;
2132	pbuttons >>= 1;
2133    }
2134    act2->button = lbuttons;
2135
2136    act2->flags = ((act2->dx || act2->dy || act2->dz) ? MOUSE_POSCHANGED : 0)
2137	| (act2->obutton ^ act2->button);
2138}
2139
2140static void
2141r_timestamp(mousestatus_t *act)
2142{
2143    struct timeval tv;
2144    struct timeval tv1;
2145    struct timeval tv2;
2146    struct timeval tv3;
2147    int button;
2148    int mask;
2149    int i;
2150
2151    mask = act->flags & MOUSE_BUTTONS;
2152#if 0
2153    if (mask == 0)
2154	return;
2155#endif
2156
2157    gettimeofday(&tv1, NULL);
2158
2159    /* double click threshold */
2160    tv2.tv_sec = rodent.clickthreshold/1000;
2161    tv2.tv_usec = (rodent.clickthreshold%1000)*1000;
2162    timersub(&tv1, &tv2, &tv);
2163    debug("tv:  %ld %ld", tv.tv_sec, tv.tv_usec);
2164
2165    /* 3 button emulation timeout */
2166    tv2.tv_sec = rodent.button2timeout/1000;
2167    tv2.tv_usec = (rodent.button2timeout%1000)*1000;
2168    timersub(&tv1, &tv2, &tv3);
2169
2170    button = MOUSE_BUTTON1DOWN;
2171    for (i = 0; (i < MOUSE_MAXBUTTON) && (mask != 0); ++i) {
2172        if (mask & 1) {
2173            if (act->button & button) {
2174                /* the button is down */
2175    		debug("  :  %ld %ld",
2176		    bstate[i].tv.tv_sec, bstate[i].tv.tv_usec);
2177		if (timercmp(&tv, &bstate[i].tv, >)) {
2178                    bstate[i].count = 1;
2179                } else {
2180                    ++bstate[i].count;
2181                }
2182		bstate[i].tv = tv1;
2183            } else {
2184                /* the button is up */
2185                bstate[i].tv = tv1;
2186            }
2187        } else {
2188	    if (act->button & button) {
2189		/* the button has been down */
2190		if (timercmp(&tv3, &bstate[i].tv, >)) {
2191		    bstate[i].count = 1;
2192		    bstate[i].tv = tv1;
2193		    act->flags |= button;
2194		    debug("button %d timeout", i + 1);
2195		}
2196	    } else {
2197		/* the button has been up */
2198	    }
2199	}
2200	button <<= 1;
2201	mask >>= 1;
2202    }
2203}
2204
2205static int
2206r_timeout(void)
2207{
2208    struct timeval tv;
2209    struct timeval tv1;
2210    struct timeval tv2;
2211
2212    if (states[mouse_button_state].timeout)
2213	return TRUE;
2214    gettimeofday(&tv1, NULL);
2215    tv2.tv_sec = rodent.button2timeout/1000;
2216    tv2.tv_usec = (rodent.button2timeout%1000)*1000;
2217    timersub(&tv1, &tv2, &tv);
2218    return timercmp(&tv, &mouse_button_state_tv, >);
2219}
2220
2221static void
2222r_click(mousestatus_t *act)
2223{
2224    struct mouse_info mouse;
2225    int button;
2226    int mask;
2227    int i;
2228
2229    mask = act->flags & MOUSE_BUTTONS;
2230    if (mask == 0)
2231	return;
2232
2233    button = MOUSE_BUTTON1DOWN;
2234    for (i = 0; (i < MOUSE_MAXBUTTON) && (mask != 0); ++i) {
2235        if (mask & 1) {
2236	    debug("mstate[%d]->count:%d", i, mstate[i]->count);
2237            if (act->button & button) {
2238                /* the button is down */
2239	        mouse.u.event.value = mstate[i]->count;
2240            } else {
2241                /* the button is up */
2242	        mouse.u.event.value = 0;
2243            }
2244	    mouse.operation = MOUSE_BUTTON_EVENT;
2245	    mouse.u.event.id = button;
2246	    if (debug < 2)
2247	        ioctl(rodent.cfd, CONS_MOUSECTL, &mouse);
2248	    debug("button %d  count %d", i + 1, mouse.u.event.value);
2249        }
2250	button <<= 1;
2251	mask >>= 1;
2252    }
2253}
2254
2255/* $XConsortium: posix_tty.c,v 1.3 95/01/05 20:42:55 kaleb Exp $ */
2256/* $XFree86: xc/programs/Xserver/hw/xfree86/os-support/shared/posix_tty.c,v 3.4 1995/01/28 17:05:03 dawes Exp $ */
2257/*
2258 * Copyright 1993 by David Dawes <dawes@physics.su.oz.au>
2259 *
2260 * Permission to use, copy, modify, distribute, and sell this software and its
2261 * documentation for any purpose is hereby granted without fee, provided that
2262 * the above copyright notice appear in all copies and that both that
2263 * copyright notice and this permission notice appear in supporting
2264 * documentation, and that the name of David Dawes
2265 * not be used in advertising or publicity pertaining to distribution of
2266 * the software without specific, written prior permission.
2267 * David Dawes makes no representations about the suitability of this
2268 * software for any purpose.  It is provided "as is" without express or
2269 * implied warranty.
2270 *
2271 * DAVID DAWES DISCLAIMS ALL WARRANTIES WITH REGARD TO
2272 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
2273 * FITNESS, IN NO EVENT SHALL DAVID DAWES BE LIABLE FOR
2274 * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
2275 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
2276 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
2277 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
2278 *
2279 */
2280
2281
2282static void
2283setmousespeed(int old, int new, unsigned cflag)
2284{
2285	struct termios tty;
2286	char *c;
2287
2288	if (tcgetattr(rodent.mfd, &tty) < 0)
2289	{
2290		logwarn("unable to get status of mouse fd", 0);
2291		return;
2292	}
2293
2294	tty.c_iflag = IGNBRK | IGNPAR;
2295	tty.c_oflag = 0;
2296	tty.c_lflag = 0;
2297	tty.c_cflag = (tcflag_t)cflag;
2298	tty.c_cc[VTIME] = 0;
2299	tty.c_cc[VMIN] = 1;
2300
2301	switch (old)
2302	{
2303	case 9600:
2304		cfsetispeed(&tty, B9600);
2305		cfsetospeed(&tty, B9600);
2306		break;
2307	case 4800:
2308		cfsetispeed(&tty, B4800);
2309		cfsetospeed(&tty, B4800);
2310		break;
2311	case 2400:
2312		cfsetispeed(&tty, B2400);
2313		cfsetospeed(&tty, B2400);
2314		break;
2315	case 1200:
2316	default:
2317		cfsetispeed(&tty, B1200);
2318		cfsetospeed(&tty, B1200);
2319	}
2320
2321	if (tcsetattr(rodent.mfd, TCSADRAIN, &tty) < 0)
2322	{
2323		logwarn("unable to set status of mouse fd", 0);
2324		return;
2325	}
2326
2327	switch (new)
2328	{
2329	case 9600:
2330		c = "*q";
2331		cfsetispeed(&tty, B9600);
2332		cfsetospeed(&tty, B9600);
2333		break;
2334	case 4800:
2335		c = "*p";
2336		cfsetispeed(&tty, B4800);
2337		cfsetospeed(&tty, B4800);
2338		break;
2339	case 2400:
2340		c = "*o";
2341		cfsetispeed(&tty, B2400);
2342		cfsetospeed(&tty, B2400);
2343		break;
2344	case 1200:
2345	default:
2346		c = "*n";
2347		cfsetispeed(&tty, B1200);
2348		cfsetospeed(&tty, B1200);
2349	}
2350
2351	if (rodent.rtype == MOUSE_PROTO_LOGIMOUSEMAN
2352	    || rodent.rtype == MOUSE_PROTO_LOGI)
2353	{
2354		if (write(rodent.mfd, c, 2) != 2)
2355		{
2356			logwarn("unable to write to mouse fd", 0);
2357			return;
2358		}
2359	}
2360	usleep(100000);
2361
2362	if (tcsetattr(rodent.mfd, TCSADRAIN, &tty) < 0)
2363		logwarn("unable to set status of mouse fd", 0);
2364}
2365
2366/*
2367 * PnP COM device support
2368 *
2369 * It's a simplistic implementation, but it works :-)
2370 * KY, 31/7/97.
2371 */
2372
2373/*
2374 * Try to elicit a PnP ID as described in
2375 * Microsoft, Hayes: "Plug and Play External COM Device Specification,
2376 * rev 1.00", 1995.
2377 *
2378 * The routine does not fully implement the COM Enumerator as par Section
2379 * 2.1 of the document.  In particular, we don't have idle state in which
2380 * the driver software monitors the com port for dynamic connection or
2381 * removal of a device at the port, because `moused' simply quits if no
2382 * device is found.
2383 *
2384 * In addition, as PnP COM device enumeration procedure slightly has
2385 * changed since its first publication, devices which follow earlier
2386 * revisions of the above spec. may fail to respond if the rev 1.0
2387 * procedure is used. XXX
2388 */
2389static int
2390pnpwakeup1(void)
2391{
2392    struct timeval timeout;
2393    fd_set fds;
2394    int i;
2395
2396    /*
2397     * This is the procedure described in rev 1.0 of PnP COM device spec.
2398     * Unfortunately, some devices which comform to earlier revisions of
2399     * the spec gets confused and do not return the ID string...
2400     */
2401    debug("PnP COM device rev 1.0 probe...");
2402
2403    /* port initialization (2.1.2) */
2404    ioctl(rodent.mfd, TIOCMGET, &i);
2405    i |= TIOCM_DTR;		/* DTR = 1 */
2406    i &= ~TIOCM_RTS;		/* RTS = 0 */
2407    ioctl(rodent.mfd, TIOCMSET, &i);
2408    usleep(240000);
2409
2410    /*
2411     * The PnP COM device spec. dictates that the mouse must set DSR
2412     * in response to DTR (by hardware or by software) and that if DSR is
2413     * not asserted, the host computer should think that there is no device
2414     * at this serial port.  But some mice just don't do that...
2415     */
2416    ioctl(rodent.mfd, TIOCMGET, &i);
2417    debug("modem status 0%o", i);
2418    if ((i & TIOCM_DSR) == 0)
2419	return FALSE;
2420
2421    /* port setup, 1st phase (2.1.3) */
2422    setmousespeed(1200, 1200, (CS7 | CREAD | CLOCAL | HUPCL));
2423    i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 0, RTS = 0 */
2424    ioctl(rodent.mfd, TIOCMBIC, &i);
2425    usleep(240000);
2426    i = TIOCM_DTR;		/* DTR = 1, RTS = 0 */
2427    ioctl(rodent.mfd, TIOCMBIS, &i);
2428    usleep(240000);
2429
2430    /* wait for response, 1st phase (2.1.4) */
2431    i = FREAD;
2432    ioctl(rodent.mfd, TIOCFLUSH, &i);
2433    i = TIOCM_RTS;		/* DTR = 1, RTS = 1 */
2434    ioctl(rodent.mfd, TIOCMBIS, &i);
2435
2436    /* try to read something */
2437    FD_ZERO(&fds);
2438    FD_SET(rodent.mfd, &fds);
2439    timeout.tv_sec = 0;
2440    timeout.tv_usec = 240000;
2441    if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) > 0) {
2442	debug("pnpwakeup1(): valid response in first phase.");
2443	return TRUE;
2444    }
2445
2446    /* port setup, 2nd phase (2.1.5) */
2447    i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 0, RTS = 0 */
2448    ioctl(rodent.mfd, TIOCMBIC, &i);
2449    usleep(240000);
2450
2451    /* wait for respose, 2nd phase (2.1.6) */
2452    i = FREAD;
2453    ioctl(rodent.mfd, TIOCFLUSH, &i);
2454    i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 1, RTS = 1 */
2455    ioctl(rodent.mfd, TIOCMBIS, &i);
2456
2457    /* try to read something */
2458    FD_ZERO(&fds);
2459    FD_SET(rodent.mfd, &fds);
2460    timeout.tv_sec = 0;
2461    timeout.tv_usec = 240000;
2462    if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) > 0) {
2463	debug("pnpwakeup1(): valid response in second phase.");
2464	return TRUE;
2465    }
2466
2467    return FALSE;
2468}
2469
2470static int
2471pnpwakeup2(void)
2472{
2473    struct timeval timeout;
2474    fd_set fds;
2475    int i;
2476
2477    /*
2478     * This is a simplified procedure; it simply toggles RTS.
2479     */
2480    debug("alternate probe...");
2481
2482    ioctl(rodent.mfd, TIOCMGET, &i);
2483    i |= TIOCM_DTR;		/* DTR = 1 */
2484    i &= ~TIOCM_RTS;		/* RTS = 0 */
2485    ioctl(rodent.mfd, TIOCMSET, &i);
2486    usleep(240000);
2487
2488    setmousespeed(1200, 1200, (CS7 | CREAD | CLOCAL | HUPCL));
2489
2490    /* wait for respose */
2491    i = FREAD;
2492    ioctl(rodent.mfd, TIOCFLUSH, &i);
2493    i = TIOCM_DTR | TIOCM_RTS;	/* DTR = 1, RTS = 1 */
2494    ioctl(rodent.mfd, TIOCMBIS, &i);
2495
2496    /* try to read something */
2497    FD_ZERO(&fds);
2498    FD_SET(rodent.mfd, &fds);
2499    timeout.tv_sec = 0;
2500    timeout.tv_usec = 240000;
2501    if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) > 0) {
2502	debug("pnpwakeup2(): valid response.");
2503	return TRUE;
2504    }
2505
2506    return FALSE;
2507}
2508
2509static int
2510pnpgets(char *buf)
2511{
2512    struct timeval timeout;
2513    fd_set fds;
2514    int begin;
2515    int i;
2516    char c;
2517
2518    if (!pnpwakeup1() && !pnpwakeup2()) {
2519	/*
2520	 * According to PnP spec, we should set DTR = 1 and RTS = 0 while
2521	 * in idle state.  But, `moused' shall set DTR = RTS = 1 and proceed,
2522	 * assuming there is something at the port even if it didn't
2523	 * respond to the PnP enumeration procedure.
2524	 */
2525disconnect_idle:
2526	i = TIOCM_DTR | TIOCM_RTS;		/* DTR = 1, RTS = 1 */
2527	ioctl(rodent.mfd, TIOCMBIS, &i);
2528	return 0;
2529    }
2530
2531    /* collect PnP COM device ID (2.1.7) */
2532    begin = -1;
2533    i = 0;
2534    usleep(240000);	/* the mouse must send `Begin ID' within 200msec */
2535    while (read(rodent.mfd, &c, 1) == 1) {
2536	/* we may see "M", or "M3..." before `Begin ID' */
2537	buf[i++] = c;
2538        if ((c == 0x08) || (c == 0x28)) {	/* Begin ID */
2539	    debug("begin-id %02x", c);
2540	    begin = i - 1;
2541	    break;
2542        }
2543        debug("%c %02x", c, c);
2544	if (i >= 256)
2545	    break;
2546    }
2547    if (begin < 0) {
2548	/* we haven't seen `Begin ID' in time... */
2549	goto connect_idle;
2550    }
2551
2552    ++c;			/* make it `End ID' */
2553    for (;;) {
2554        FD_ZERO(&fds);
2555        FD_SET(rodent.mfd, &fds);
2556        timeout.tv_sec = 0;
2557        timeout.tv_usec = 240000;
2558        if (select(FD_SETSIZE, &fds, NULL, NULL, &timeout) <= 0)
2559	    break;
2560
2561	read(rodent.mfd, &buf[i], 1);
2562        if (buf[i++] == c)	/* End ID */
2563	    break;
2564	if (i >= 256)
2565	    break;
2566    }
2567    if (begin > 0) {
2568	i -= begin;
2569	bcopy(&buf[begin], &buf[0], i);
2570    }
2571    /* string may not be human readable... */
2572    debug("len:%d, '%-*.*s'", i, i, i, buf);
2573
2574    if (buf[i - 1] == c)
2575	return i;		/* a valid PnP string */
2576
2577    /*
2578     * According to PnP spec, we should set DTR = 1 and RTS = 0 while
2579     * in idle state.  But, `moused' shall leave the modem control lines
2580     * as they are. See above.
2581     */
2582connect_idle:
2583
2584    /* we may still have something in the buffer */
2585    return ((i > 0) ? i : 0);
2586}
2587
2588static int
2589pnpparse(pnpid_t *id, char *buf, int len)
2590{
2591    char s[3];
2592    int offset;
2593    int sum = 0;
2594    int i, j;
2595
2596    id->revision = 0;
2597    id->eisaid = NULL;
2598    id->serial = NULL;
2599    id->class = NULL;
2600    id->compat = NULL;
2601    id->description = NULL;
2602    id->neisaid = 0;
2603    id->nserial = 0;
2604    id->nclass = 0;
2605    id->ncompat = 0;
2606    id->ndescription = 0;
2607
2608    if ((buf[0] != 0x28) && (buf[0] != 0x08)) {
2609	/* non-PnP mice */
2610	switch(buf[0]) {
2611	default:
2612	    return FALSE;
2613	case 'M': /* Microsoft */
2614	    id->eisaid = "PNP0F01";
2615	    break;
2616	case 'H': /* MouseSystems */
2617	    id->eisaid = "PNP0F04";
2618	    break;
2619	}
2620	id->neisaid = strlen(id->eisaid);
2621	id->class = "MOUSE";
2622	id->nclass = strlen(id->class);
2623	debug("non-PnP mouse '%c'", buf[0]);
2624	return TRUE;
2625    }
2626
2627    /* PnP mice */
2628    offset = 0x28 - buf[0];
2629
2630    /* calculate checksum */
2631    for (i = 0; i < len - 3; ++i) {
2632	sum += buf[i];
2633	buf[i] += offset;
2634    }
2635    sum += buf[len - 1];
2636    for (; i < len; ++i)
2637	buf[i] += offset;
2638    debug("PnP ID string: '%*.*s'", len, len, buf);
2639
2640    /* revision */
2641    buf[1] -= offset;
2642    buf[2] -= offset;
2643    id->revision = ((buf[1] & 0x3f) << 6) | (buf[2] & 0x3f);
2644    debug("PnP rev %d.%02d", id->revision / 100, id->revision % 100);
2645
2646    /* EISA vender and product ID */
2647    id->eisaid = &buf[3];
2648    id->neisaid = 7;
2649
2650    /* option strings */
2651    i = 10;
2652    if (buf[i] == '\\') {
2653        /* device serial # */
2654        for (j = ++i; i < len; ++i) {
2655            if (buf[i] == '\\')
2656		break;
2657        }
2658	if (i >= len)
2659	    i -= 3;
2660	if (i - j == 8) {
2661            id->serial = &buf[j];
2662            id->nserial = 8;
2663	}
2664    }
2665    if (buf[i] == '\\') {
2666        /* PnP class */
2667        for (j = ++i; i < len; ++i) {
2668            if (buf[i] == '\\')
2669		break;
2670        }
2671	if (i >= len)
2672	    i -= 3;
2673	if (i > j + 1) {
2674            id->class = &buf[j];
2675            id->nclass = i - j;
2676        }
2677    }
2678    if (buf[i] == '\\') {
2679	/* compatible driver */
2680        for (j = ++i; i < len; ++i) {
2681            if (buf[i] == '\\')
2682		break;
2683        }
2684	/*
2685	 * PnP COM spec prior to v0.96 allowed '*' in this field,
2686	 * it's not allowed now; just igore it.
2687	 */
2688	if (buf[j] == '*')
2689	    ++j;
2690	if (i >= len)
2691	    i -= 3;
2692	if (i > j + 1) {
2693            id->compat = &buf[j];
2694            id->ncompat = i - j;
2695        }
2696    }
2697    if (buf[i] == '\\') {
2698	/* product description */
2699        for (j = ++i; i < len; ++i) {
2700            if (buf[i] == ';')
2701		break;
2702        }
2703	if (i >= len)
2704	    i -= 3;
2705	if (i > j + 1) {
2706            id->description = &buf[j];
2707            id->ndescription = i - j;
2708        }
2709    }
2710
2711    /* checksum exists if there are any optional fields */
2712    if ((id->nserial > 0) || (id->nclass > 0)
2713	|| (id->ncompat > 0) || (id->ndescription > 0)) {
2714        debug("PnP checksum: 0x%X", sum);
2715        sprintf(s, "%02X", sum & 0x0ff);
2716        if (strncmp(s, &buf[len - 3], 2) != 0) {
2717#if 0
2718            /*
2719	     * I found some mice do not comply with the PnP COM device
2720	     * spec regarding checksum... XXX
2721	     */
2722            logwarnx("PnP checksum error", 0);
2723	    return FALSE;
2724#endif
2725        }
2726    }
2727
2728    return TRUE;
2729}
2730
2731static symtab_t *
2732pnpproto(pnpid_t *id)
2733{
2734    symtab_t *t;
2735    int i, j;
2736
2737    if (id->nclass > 0)
2738	if ( strncmp(id->class, "MOUSE", id->nclass) != 0 &&
2739	     strncmp(id->class, "TABLET", id->nclass) != 0)
2740	    /* this is not a mouse! */
2741	    return NULL;
2742
2743    if (id->neisaid > 0) {
2744        t = gettoken(pnpprod, id->eisaid, id->neisaid);
2745	if (t->val != MOUSE_PROTO_UNKNOWN)
2746            return t;
2747    }
2748
2749    /*
2750     * The 'Compatible drivers' field may contain more than one
2751     * ID separated by ','.
2752     */
2753    if (id->ncompat <= 0)
2754	return NULL;
2755    for (i = 0; i < id->ncompat; ++i) {
2756        for (j = i; id->compat[i] != ','; ++i)
2757            if (i >= id->ncompat)
2758		break;
2759        if (i > j) {
2760            t = gettoken(pnpprod, id->compat + j, i - j);
2761	    if (t->val != MOUSE_PROTO_UNKNOWN)
2762                return t;
2763	}
2764    }
2765
2766    return NULL;
2767}
2768
2769/* name/val mapping */
2770
2771static symtab_t *
2772gettoken(symtab_t *tab, char *s, int len)
2773{
2774    int i;
2775
2776    for (i = 0; tab[i].name != NULL; ++i) {
2777	if (strncmp(tab[i].name, s, len) == 0)
2778	    break;
2779    }
2780    return &tab[i];
2781}
2782
2783static char *
2784gettokenname(symtab_t *tab, int val)
2785{
2786    int i;
2787
2788    for (i = 0; tab[i].name != NULL; ++i) {
2789	if (tab[i].val == val)
2790	    return tab[i].name;
2791    }
2792    return NULL;
2793}
2794
2795
2796/*
2797 * code to read from the Genius Kidspad tablet.
2798
2799The tablet responds to the COM PnP protocol 1.0 with EISA-ID KYE0005,
2800and to pre-pnp probes (RTS toggle) with 'T' (tablet ?)
28019600, 8 bit, parity odd.
2802
2803The tablet puts out 5 bytes. b0 (mask 0xb8, value 0xb8) contains
2804the proximity, tip and button info:
2805   (byte0 & 0x1)	true = tip pressed
2806   (byte0 & 0x2)	true = button pressed
2807   (byte0 & 0x40)	false = pen in proximity of tablet.
2808
2809The next 4 bytes are used for coordinates xl, xh, yl, yh (7 bits valid).
2810
2811Only absolute coordinates are returned, so we use the following approach:
2812we store the last coordinates sent when the pen went out of the tablet,
2813
2814
2815 *
2816 */
2817
2818typedef enum {
2819    S_IDLE, S_PROXY, S_FIRST, S_DOWN, S_UP
2820} k_status ;
2821
2822static int
2823kidspad(u_char rxc, mousestatus_t *act)
2824{
2825    static buf[5];
2826    static int buflen = 0, b_prev = 0 , x_prev = -1, y_prev = -1 ;
2827    static k_status status = S_IDLE ;
2828    static struct timeval old, now ;
2829
2830    int x, y ;
2831
2832    if (buflen > 0 && (rxc & 0x80) ) {
2833	fprintf(stderr, "invalid code %d 0x%x\n", buflen, rxc);
2834	buflen = 0 ;
2835    }
2836    if (buflen == 0 && (rxc & 0xb8) != 0xb8 ) {
2837	fprintf(stderr, "invalid code 0 0x%x\n", rxc);
2838	return 0 ; /* invalid code, no action */
2839    }
2840    buf[buflen++] = rxc ;
2841    if (buflen < 5)
2842	return 0 ;
2843
2844    buflen = 0 ; /* for next time... */
2845
2846    x = buf[1]+128*(buf[2] - 7) ;
2847    if (x < 0) x = 0 ;
2848    y = 28*128 - (buf[3] + 128* (buf[4] - 7)) ;
2849    if (y < 0) y = 0 ;
2850
2851    x /= 8 ;
2852    y /= 8 ;
2853
2854    act->flags = 0 ;
2855    act->obutton = act->button ;
2856    act->dx = act->dy = act->dz = 0 ;
2857    gettimeofday(&now, NULL);
2858    if ( buf[0] & 0x40 ) /* pen went out of reach */
2859	status = S_IDLE ;
2860    else if (status == S_IDLE) { /* pen is newly near the tablet */
2861	act->flags |= MOUSE_POSCHANGED ; /* force update */
2862	status = S_PROXY ;
2863	x_prev = x ;
2864	y_prev = y ;
2865    }
2866    old = now ;
2867    act->dx = x - x_prev ;
2868    act->dy = y - y_prev ;
2869    if (act->dx || act->dy)
2870	act->flags |= MOUSE_POSCHANGED ;
2871    x_prev = x ;
2872    y_prev = y ;
2873    if (b_prev != 0 && b_prev != buf[0]) { /* possibly record button change */
2874	act->button = 0 ;
2875	if ( buf[0] & 0x01 ) /* tip pressed */
2876	    act->button |= MOUSE_BUTTON1DOWN ;
2877	if ( buf[0] & 0x02 ) /* button pressed */
2878	    act->button |= MOUSE_BUTTON2DOWN ;
2879	act->flags |= MOUSE_BUTTONSCHANGED ;
2880    }
2881    b_prev = buf[0] ;
2882    return act->flags ;
2883}
2884
2885static void
2886mremote_serversetup()
2887{
2888    struct sockaddr_un ad;
2889
2890    /* Open a UNIX domain stream socket to listen for mouse remote clients */
2891    unlink(_PATH_MOUSEREMOTE);
2892
2893    if ( (rodent.mremsfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
2894	logerrx(1, "unable to create unix domain socket %s",_PATH_MOUSEREMOTE);
2895
2896    umask(0111);
2897
2898    bzero(&ad, sizeof(ad));
2899    ad.sun_family = AF_UNIX;
2900    strcpy(ad.sun_path, _PATH_MOUSEREMOTE);
2901#ifndef SUN_LEN
2902#define SUN_LEN(unp) ( ((char *)(unp)->sun_path - (char *)(unp)) + \
2903                       strlen((unp)->path) )
2904#endif
2905    if (bind(rodent.mremsfd, (struct sockaddr *) &ad, SUN_LEN(&ad)) < 0)
2906	logerrx(1, "unable to bind unix domain socket %s", _PATH_MOUSEREMOTE);
2907
2908    listen(rodent.mremsfd, 1);
2909}
2910
2911static void
2912mremote_clientchg(int add)
2913{
2914    struct sockaddr_un ad;
2915    int ad_len, fd;
2916
2917    if (rodent.rtype != MOUSE_PROTO_X10MOUSEREM)
2918	return;
2919
2920    if ( add ) {
2921	/*  Accept client connection, if we don't already have one  */
2922	ad_len = sizeof(ad);
2923	fd = accept(rodent.mremsfd, (struct sockaddr *) &ad, &ad_len);
2924	if (fd < 0)
2925	    logwarnx("failed accept on mouse remote socket");
2926
2927	if ( rodent.mremcfd < 0 ) {
2928	    rodent.mremcfd = fd;
2929	    debug("remote client connect...accepted");
2930	}
2931	else {
2932	    close(fd);
2933	    debug("another remote client connect...disconnected");
2934	}
2935    }
2936    else {
2937	/* Client disconnected */
2938	debug("remote client disconnected");
2939	close( rodent.mremcfd );
2940	rodent.mremcfd = -1;
2941    }
2942}
2943
2944
2945