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