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