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