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