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