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