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