1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 1997-2000 Kazutaka YOKOTA <yokota@FreeBSD.org>
5 * Copyright (c) 2004-2008 Philip Paeps <philip@FreeBSD.org>
6 * Copyright (c) 2008 Jean-Sebastien Pedron <dumbbell@FreeBSD.org>
7 * Copyright (c) 2021,2024 Vladimir Kondratyev <wulf@FreeBSD.org>
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * SUCH DAMAGE.
29 */
30
31 /*
32 * MOUSED.C
33 *
34 * Mouse daemon : listens to a evdev device node for mouse data stream,
35 * interprets data and passes ioctls off to the console driver.
36 *
37 */
38
39 #include <sys/param.h>
40 #include <sys/consio.h>
41 #include <sys/event.h>
42 #include <sys/mouse.h>
43 #include <sys/socket.h>
44 #include <sys/time.h>
45 #include <sys/un.h>
46
47 #include <dev/evdev/input.h>
48
49 #include <bitstring.h>
50 #include <ctype.h>
51 #include <dirent.h>
52 #include <err.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <fnmatch.h>
56 #include <libutil.h>
57 #include <math.h>
58 #include <setjmp.h>
59 #include <signal.h>
60 #include <stdarg.h>
61 #include <stdbool.h>
62 #include <stddef.h>
63 #include <stdint.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <syslog.h>
68 #include <unistd.h>
69
70 #include "util.h"
71 #include "quirks.h"
72
73 /*
74 * bitstr_t implementation must be identical to one found in EVIOCG*
75 * libevdev ioctls. Our bitstring(3) API is compatible since r299090.
76 */
77 _Static_assert(sizeof(bitstr_t) == sizeof(unsigned long),
78 "bitstr_t size mismatch");
79
80 #define MAX_CLICKTHRESHOLD 2000 /* 2 seconds */
81 #define MAX_BUTTON2TIMEOUT 2000 /* 2 seconds */
82 #define DFLT_CLICKTHRESHOLD 500 /* 0.5 second */
83 #define DFLT_BUTTON2TIMEOUT 100 /* 0.1 second */
84 #define DFLT_SCROLLTHRESHOLD 3 /* 3 pixels */
85 #define DFLT_SCROLLSPEED 2 /* 2 pixels */
86 #define DFLT_MOUSE_RESOLUTION 8 /* dpmm, == 200dpi */
87 #define DFLT_TPAD_RESOLUTION 40 /* dpmm, typical X res for Synaptics */
88 #define DFLT_LINEHEIGHT 10 /* pixels per line */
89
90 /* Abort 3-button emulation delay after this many movement events. */
91 #define BUTTON2_MAXMOVE 3
92
93 #define MOUSE_XAXIS (-1)
94 #define MOUSE_YAXIS (-2)
95
96 #define ZMAP_MAXBUTTON 4 /* Number of zmap items */
97 #define MAX_FINGERS 10
98
99 #define ID_NONE 0
100 #define ID_PORT 1
101 #define ID_IF 2
102 #define ID_TYPE 4
103 #define ID_MODEL 8
104 #define ID_ALL (ID_PORT | ID_IF | ID_TYPE | ID_MODEL)
105
106 /* Operations on timespecs */
107 #define tsclr(tvp) timespecclear(tvp)
108 #define tscmp(tvp, uvp, cmp) timespeccmp(tvp, uvp, cmp)
109 #define tssub(tvp, uvp, vvp) timespecsub(tvp, uvp, vvp)
110 #define msec2ts(msec) (struct timespec) { \
111 .tv_sec = (msec) / 1000, \
112 .tv_nsec = (msec) % 1000 * 1000000, \
113 }
114 static inline struct timespec
tsaddms(struct timespec * tsp,u_int ms)115 tsaddms(struct timespec* tsp, u_int ms)
116 {
117 struct timespec ret;
118
119 ret = msec2ts(ms);
120 timespecadd(tsp, &ret, &ret);
121
122 return (ret);
123 };
124
125 static inline struct timespec
tssubms(struct timespec * tsp,u_int ms)126 tssubms(struct timespec* tsp, u_int ms)
127 {
128 struct timespec ret;
129
130 ret = msec2ts(ms);
131 timespecsub(tsp, &ret, &ret);
132
133 return (ret);
134 };
135
136 #define debug(...) do { \
137 if (debug && nodaemon) \
138 warnx(__VA_ARGS__); \
139 } while (0)
140
141 #define logerr(e, ...) do { \
142 log_or_warn(LOG_DAEMON | LOG_ERR, errno, __VA_ARGS__); \
143 exit(e); \
144 } while (0)
145
146 #define logerrx(e, ...) do { \
147 log_or_warn(LOG_DAEMON | LOG_ERR, 0, __VA_ARGS__); \
148 exit(e); \
149 } while (0)
150
151 #define logwarn(...) \
152 log_or_warn(LOG_DAEMON | LOG_WARNING, errno, __VA_ARGS__)
153
154 #define logwarnx(...) \
155 log_or_warn(LOG_DAEMON | LOG_WARNING, 0, __VA_ARGS__)
156
157 /* structures */
158
159 enum gesture {
160 GEST_IGNORE,
161 GEST_ACCUMULATE,
162 GEST_MOVE,
163 GEST_VSCROLL,
164 GEST_HSCROLL,
165 };
166
167 /* interfaces (the table must be ordered by DEVICE_IF_XXX in util.h) */
168 static const struct {
169 const char *name;
170 size_t p_size;
171 } rifs[] = {
172 [DEVICE_IF_EVDEV] = { "evdev", sizeof(struct input_event) },
173 [DEVICE_IF_SYSMOUSE] = { "sysmouse", MOUSE_SYS_PACKETSIZE },
174 };
175
176 /* types (the table must be ordered by DEVICE_TYPE_XXX in util.h) */
177 static const char *rnames[] = {
178 [DEVICE_TYPE_MOUSE] = "mouse",
179 [DEVICE_TYPE_POINTINGSTICK] = "pointing stick",
180 [DEVICE_TYPE_TOUCHPAD] = "touchpad",
181 [DEVICE_TYPE_TOUCHSCREEN] = "touchscreen",
182 [DEVICE_TYPE_TABLET] = "tablet",
183 [DEVICE_TYPE_TABLET_PAD] = "tablet pad",
184 [DEVICE_TYPE_KEYBOARD] = "keyboard",
185 [DEVICE_TYPE_JOYSTICK] = "joystick",
186 };
187
188 /* Default phisical to logical button mapping */
189 static const u_int default_p2l[MOUSE_MAXBUTTON] = {
190 MOUSE_BUTTON1DOWN, MOUSE_BUTTON2DOWN, MOUSE_BUTTON3DOWN, MOUSE_BUTTON4DOWN,
191 MOUSE_BUTTON5DOWN, MOUSE_BUTTON6DOWN, MOUSE_BUTTON7DOWN, MOUSE_BUTTON8DOWN,
192 0x00000100, 0x00000200, 0x00000400, 0x00000800,
193 0x00001000, 0x00002000, 0x00004000, 0x00008000,
194 0x00010000, 0x00020000, 0x00040000, 0x00080000,
195 0x00100000, 0x00200000, 0x00400000, 0x00800000,
196 0x01000000, 0x02000000, 0x04000000, 0x08000000,
197 0x10000000, 0x20000000, 0x40000000,
198 };
199
200 struct tpcaps {
201 bool is_clickpad;
202 bool is_topbuttonpad;
203 bool is_mt;
204 bool cap_touch;
205 bool cap_pressure;
206 bool cap_width;
207 int min_x;
208 int max_x;
209 int min_y;
210 int max_y;
211 int res_x; /* dots per mm */
212 int res_y; /* dots per mm */
213 int min_p;
214 int max_p;
215 };
216
217 struct tpinfo {
218 bool two_finger_scroll; /* Enable two finger scrolling */
219 bool natural_scroll; /* Enable natural scrolling */
220 bool three_finger_drag; /* Enable dragging with three fingers */
221 u_int min_pressure_hi; /* Min pressure to start an action */
222 u_int min_pressure_lo; /* Min pressure to continue an action */
223 u_int max_pressure; /* Maximum pressure to detect palm */
224 u_int max_width; /* Max finger width to detect palm */
225 int margin_top; /* Top margin */
226 int margin_right; /* Right margin */
227 int margin_bottom; /* Bottom margin */
228 int margin_left; /* Left margin */
229 u_int tap_timeout; /* */
230 u_int tap_threshold; /* Minimum pressure to detect a tap */
231 double tap_max_delta; /* Length of segments above which a tap is ignored */
232 u_int taphold_timeout; /* Maximum elapsed time between two taps to consider a tap-hold action */
233 double vscroll_ver_area; /* Area reserved for vertical virtual scrolling */
234 double vscroll_hor_area; /* Area reserved for horizontal virtual scrolling */
235 double vscroll_min_delta; /* Minimum movement to consider virtual scrolling */
236 int softbuttons_y; /* Vertical size of softbuttons area */
237 int softbutton2_x; /* Horizontal offset of 2-nd softbutton left edge */
238 int softbutton3_x; /* Horizontal offset of 3-rd softbutton left edge */
239 };
240
241 struct tpstate {
242 int start_x;
243 int start_y;
244 int prev_x;
245 int prev_y;
246 int prev_nfingers;
247 int fingers_nb;
248 int tap_button;
249 bool fingerdown;
250 bool in_taphold;
251 int in_vscroll;
252 u_int zmax; /* maximum pressure value */
253 struct timespec taptimeout; /* tap timeout for touchpads */
254 int idletimeout;
255 bool timer_armed;
256 };
257
258 struct tpad {
259 struct tpcaps hw; /* touchpad capabilities */
260 struct tpinfo info; /* touchpad gesture parameters */
261 struct tpstate gest; /* touchpad gesture state */
262 };
263
264 struct finger {
265 int x;
266 int y;
267 int p;
268 int w;
269 int id; /* id=0 - no touch, id>1 - touch id */
270 };
271
272 struct evstate {
273 int buttons;
274 /* Relative */
275 int dx;
276 int dy;
277 int dz;
278 int dw;
279 int acc_dx;
280 int acc_dy;
281 /* Absolute single-touch */
282 int nfingers;
283 struct finger st;
284 /* Absolute multi-touch */
285 int slot;
286 struct finger mt[MAX_FINGERS];
287 bitstr_t bit_decl(key_ignore, KEY_CNT);
288 bitstr_t bit_decl(rel_ignore, REL_CNT);
289 bitstr_t bit_decl(abs_ignore, ABS_CNT);
290 bitstr_t bit_decl(prop_ignore, INPUT_PROP_CNT);
291 };
292
293 /* button status */
294 struct button_state {
295 int count; /* 0: up, 1: single click, 2: double click,... */
296 struct timespec ts; /* timestamp on the last button event */
297 };
298
299 struct btstate {
300 u_int wmode; /* wheel mode button number */
301 u_int clickthreshold; /* double click speed in msec */
302 struct button_state bstate[MOUSE_MAXBUTTON]; /* button state */
303 struct button_state *mstate[MOUSE_MAXBUTTON];/* mapped button st.*/
304 u_int p2l[MOUSE_MAXBUTTON];/* phisical to logical button mapping */
305 int zmap[ZMAP_MAXBUTTON];/* MOUSE_{X|Y}AXIS or a button number */
306 struct button_state zstate[ZMAP_MAXBUTTON]; /* Z/W axis state */
307 };
308
309 /* state machine for 3 button emulation */
310
311 enum bt3_emul_state {
312 S0, /* start */
313 S1, /* button 1 delayed down */
314 S2, /* button 3 delayed down */
315 S3, /* both buttons down -> button 2 down */
316 S4, /* button 1 delayed up */
317 S5, /* button 1 down */
318 S6, /* button 3 down */
319 S7, /* both buttons down */
320 S8, /* button 3 delayed up */
321 S9, /* button 1 or 3 up after S3 */
322 };
323
324 #define A(b1, b3) (((b1) ? 2 : 0) | ((b3) ? 1 : 0))
325 #define A_TIMEOUT 4
326 #define S_DELAYED(st) (states[st].s[A_TIMEOUT] != (st))
327
328 static const struct {
329 enum bt3_emul_state s[A_TIMEOUT + 1];
330 int buttons;
331 int mask;
332 bool timeout;
333 } states[10] = {
334 /* S0 */
335 { { S0, S2, S1, S3, S0 }, 0, ~(MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN), false },
336 /* S1 */
337 { { S4, S2, S1, S3, S5 }, 0, ~MOUSE_BUTTON1DOWN, false },
338 /* S2 */
339 { { S8, S2, S1, S3, S6 }, 0, ~MOUSE_BUTTON3DOWN, false },
340 /* S3 */
341 { { S0, S9, S9, S3, S3 }, MOUSE_BUTTON2DOWN, ~0, false },
342 /* S4 */
343 { { S0, S2, S1, S3, S0 }, MOUSE_BUTTON1DOWN, ~0, true },
344 /* S5 */
345 { { S0, S2, S5, S7, S5 }, MOUSE_BUTTON1DOWN, ~0, false },
346 /* S6 */
347 { { S0, S6, S1, S7, S6 }, MOUSE_BUTTON3DOWN, ~0, false },
348 /* S7 */
349 { { S0, S6, S5, S7, S7 }, MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN, ~0, false },
350 /* S8 */
351 { { S0, S2, S1, S3, S0 }, MOUSE_BUTTON3DOWN, ~0, true },
352 /* S9 */
353 { { S0, S9, S9, S3, S9 }, 0, ~(MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN), false },
354 };
355
356 struct e3bstate {
357 bool enabled;
358 u_int button2timeout; /* 3 button emulation timeout */
359 enum bt3_emul_state mouse_button_state;
360 struct timespec mouse_button_state_ts;
361 int mouse_move_delayed;
362 bool timer_armed;
363 };
364
365 enum scroll_state {
366 SCROLL_NOTSCROLLING,
367 SCROLL_PREPARE,
368 SCROLL_SCROLLING,
369 };
370
371 struct scroll {
372 bool enable_vert;
373 bool enable_hor;
374 u_int threshold; /* Movement distance before virtual scrolling */
375 u_int speed; /* Movement distance to rate of scrolling */
376 enum scroll_state state;
377 int movement;
378 int hmovement;
379 };
380
381 struct drift_xy {
382 int x;
383 int y;
384 };
385 struct drift {
386 u_int distance; /* max steps X+Y */
387 u_int time; /* ms */
388 struct timespec time_ts;
389 struct timespec twotime_ts; /* 2*drift_time */
390 u_int after; /* ms */
391 struct timespec after_ts;
392 bool terminate;
393 struct timespec current_ts;
394 struct timespec last_activity;
395 struct timespec since;
396 struct drift_xy last; /* steps in last drift_time */
397 struct drift_xy previous; /* steps in prev. drift_time */
398 };
399
400 struct accel {
401 bool is_exponential; /* Exponential acceleration is enabled */
402 double accelx; /* Acceleration in the X axis */
403 double accely; /* Acceleration in the Y axis */
404 double accelz; /* Acceleration in the wheel axis */
405 double expoaccel; /* Exponential acceleration */
406 double expoffset; /* Movement offset for exponential accel. */
407 double remainx; /* Remainder on X, Y and wheel axis, ... */
408 double remainy; /* ... respectively to compensate */
409 double remainz; /* ... for rounding errors. */
410 double lastlength[3];
411 };
412
413 struct rodent {
414 struct device dev; /* Device */
415 int mfd; /* mouse file descriptor */
416 struct btstate btstate; /* button status */
417 struct e3bstate e3b; /* 3 button emulation state */
418 struct drift drift;
419 struct accel accel; /* cursor acceleration state */
420 struct scroll scroll; /* virtual scroll state */
421 struct tpad tp; /* touchpad info and gesture state */
422 struct evstate ev; /* event device state */
423 SLIST_ENTRY(rodent) next;
424 };
425
426 /* global variables */
427
428 static SLIST_HEAD(rodent_list, rodent) rodents = SLIST_HEAD_INITIALIZER();
429
430 static int debug = 0;
431 static bool nodaemon = false;
432 static bool background = false;
433 static bool paused = false;
434 static bool opt_grab = false;
435 static int identify = ID_NONE;
436 static int cfd = -1; /* /dev/consolectl file descriptor */
437 static int kfd = -1; /* kqueue file descriptor */
438 static int dfd = -1; /* devd socket descriptor */
439 static const char *portname = NULL;
440 static const char *pidfile = "/var/run/moused.pid";
441 static struct pidfh *pfh;
442 #ifndef CONFDIR
443 #define CONFDIR "/etc"
444 #endif
445 static const char *config_file = CONFDIR "/moused.conf";
446 #ifndef QUIRKSDIR
447 #define QUIRKSDIR "/usr/share/moused"
448 #endif
449 static const char *quirks_path = QUIRKSDIR;
450 static struct quirks_context *quirks;
451 static enum device_if force_if = DEVICE_IF_UNKNOWN;
452
453 static int opt_rate = 0;
454 static int opt_resolution = MOUSE_RES_UNKNOWN;
455
456 static u_int opt_wmode = 0;
457 static int opt_clickthreshold = -1;
458 static bool opt_e3b_enabled = false;
459 static int opt_e3b_button2timeout = -1;
460 static struct btstate opt_btstate;
461
462 static bool opt_drift_terminate = false;
463 static u_int opt_drift_distance = 4; /* max steps X+Y */
464 static u_int opt_drift_time = 500; /* ms */
465 static u_int opt_drift_after = 4000; /* ms */
466
467 static double opt_accelx = 1.0;
468 static double opt_accely = 1.0;
469 static bool opt_exp_accel = false;
470 static double opt_expoaccel = 1.0;
471 static double opt_expoffset = 1.0;
472
473 static bool opt_virtual_scroll = false;
474 static bool opt_hvirtual_scroll = false;
475 static int opt_scroll_speed = -1;
476 static int opt_scroll_threshold = -1;
477
478 static jmp_buf env;
479
480 /* function prototypes */
481
482 static moused_log_handler log_or_warn_va;
483
484 static void linacc(struct accel *, int, int, int, int*, int*, int*);
485 static void expoacc(struct accel *, int, int, int, int*, int*, int*);
486 static void moused(void);
487 static void reset(int sig);
488 static void pause_mouse(int sig);
489 static int connect_devd(void);
490 static void fetch_and_parse_devd(void);
491 static void usage(void);
492 static void log_or_warn(int log_pri, int errnum, const char *fmt, ...)
493 __printflike(3, 4);
494
495 static enum device_if r_identify_if(int fd);
496 static enum device_type r_identify_evdev(int fd);
497 static enum device_type r_identify_sysmouse(int fd);
498 static const char *r_if(enum device_if type);
499 static const char *r_name(enum device_type type);
500 static struct rodent *r_init(const char *path);
501 static void r_init_all(void);
502 static void r_deinit(struct rodent *r);
503 static void r_deinit_all(void);
504 static int r_protocol_evdev(enum device_type type, struct tpad *tp,
505 struct evstate *ev, struct input_event *ie,
506 mousestatus_t *act);
507 static int r_protocol_sysmouse(uint8_t *pBuf, mousestatus_t *act);
508 static void r_vscroll_detect(struct rodent *r, struct scroll *sc,
509 mousestatus_t *act);
510 static void r_vscroll(struct scroll *sc, mousestatus_t *act);
511 static int r_statetrans(struct rodent *r, mousestatus_t *a1,
512 mousestatus_t *a2, int trans);
513 static bool r_installmap(char *arg, struct btstate *bt);
514 static char * r_installzmap(char **argv, int argc, int* idx, struct btstate *bt);
515 static void r_map(mousestatus_t *act1, mousestatus_t *act2,
516 struct btstate *bt);
517 static void r_timestamp(mousestatus_t *act, struct btstate *bt,
518 struct e3bstate *e3b, struct drift *drift);
519 static bool r_timeout(struct e3bstate *e3b);
520 static void r_move(mousestatus_t *act, struct accel *acc);
521 static void r_click(mousestatus_t *act, struct btstate *bt);
522 static bool r_drift(struct drift *, mousestatus_t *);
523 static enum gesture r_gestures(struct tpad *tp, int x0, int y0, u_int z, int w,
524 int nfingers, struct timespec *time, mousestatus_t *ms);
525
526 int
main(int argc,char * argv[])527 main(int argc, char *argv[])
528 {
529 struct rodent *r;
530 pid_t mpid;
531 int c;
532 u_int i;
533 int n;
534 u_long ul;
535 char *errstr;
536
537 while ((c = getopt(argc, argv, "3A:C:E:F:HI:L:T:VU:a:dfghi:l:m:p:r:t:q:w:z:")) != -1) {
538 switch(c) {
539
540 case '3':
541 opt_e3b_enabled = true;
542 break;
543
544 case 'E':
545 errno = 0;
546 ul = strtoul(optarg, NULL, 10);
547 if ((ul == 0 && errno != 0) ||
548 ul > MAX_BUTTON2TIMEOUT) {
549 warnx("invalid argument `%s'", optarg);
550 usage();
551 }
552 opt_e3b_button2timeout = ul;
553 break;
554
555 case 'a':
556 n = sscanf(optarg, "%lf,%lf", &opt_accelx, &opt_accely);
557 if (n == 0) {
558 warnx("invalid linear acceleration argument "
559 "'%s'", optarg);
560 usage();
561 }
562 if (n == 1)
563 opt_accely = opt_accelx;
564 break;
565
566 case 'A':
567 opt_exp_accel = true;
568 n = sscanf(optarg, "%lf,%lf", &opt_expoaccel,
569 &opt_expoffset);
570 if (n == 0) {
571 warnx("invalid exponential acceleration "
572 "argument '%s'", optarg);
573 usage();
574 }
575 if (n == 1)
576 opt_expoffset = 1.0;
577 break;
578
579 case 'd':
580 ++debug;
581 break;
582
583 case 'f':
584 nodaemon = true;
585 break;
586
587 case 'g':
588 opt_grab = true;
589 break;
590
591 case 'i':
592 if (strcmp(optarg, "all") == 0)
593 identify = ID_ALL;
594 else if (strcmp(optarg, "port") == 0)
595 identify = ID_PORT;
596 else if (strcmp(optarg, "if") == 0)
597 identify = ID_IF;
598 else if (strcmp(optarg, "type") == 0)
599 identify = ID_TYPE;
600 else if (strcmp(optarg, "model") == 0)
601 identify = ID_MODEL;
602 else {
603 warnx("invalid argument `%s'", optarg);
604 usage();
605 }
606 nodaemon = true;
607 break;
608
609 case 'l':
610 ul = strtoul(optarg, NULL, 10);
611 if (ul != 1)
612 warnx("ignore mouse level `%s'", optarg);
613 break;
614
615 case 'm':
616 if (!r_installmap(optarg, &opt_btstate)) {
617 warnx("invalid argument `%s'", optarg);
618 usage();
619 }
620 break;
621
622 case 'p':
623 /* "auto" is an alias to no portname */
624 if (strcmp(optarg, "auto") != 0)
625 portname = optarg;
626 break;
627
628 case 'r':
629 if (strcmp(optarg, "high") == 0)
630 opt_resolution = MOUSE_RES_HIGH;
631 else if (strcmp(optarg, "medium-high") == 0)
632 opt_resolution = MOUSE_RES_HIGH;
633 else if (strcmp(optarg, "medium-low") == 0)
634 opt_resolution = MOUSE_RES_MEDIUMLOW;
635 else if (strcmp(optarg, "low") == 0)
636 opt_resolution = MOUSE_RES_LOW;
637 else if (strcmp(optarg, "default") == 0)
638 opt_resolution = MOUSE_RES_DEFAULT;
639 else {
640 ul= strtoul(optarg, NULL, 10);
641 if (ul == 0) {
642 warnx("invalid argument `%s'", optarg);
643 usage();
644 }
645 opt_resolution = ul;
646 }
647 break;
648
649 case 't':
650 if (strcmp(optarg, "auto") == 0) {
651 force_if = DEVICE_IF_UNKNOWN;
652 break;
653 }
654 for (i = 0; i < nitems(rifs); i++)
655 if (strcmp(optarg, rifs[i].name) == 0) {
656 force_if = i;
657 break;
658 }
659 if (i == nitems(rifs)) {
660 warnx("no such interface type `%s'", optarg);
661 usage();
662 }
663 break;
664
665 case 'w':
666 ul = strtoul(optarg, NULL, 10);
667 if (ul == 0 || ul > MOUSE_MAXBUTTON) {
668 warnx("invalid argument `%s'", optarg);
669 usage();
670 }
671 opt_wmode = ul;
672 break;
673
674 case 'z':
675 --optind;
676 errstr = r_installzmap(argv, argc, &optind, &opt_btstate);
677 if (errstr != NULL) {
678 warnx("%s", errstr);
679 free(errstr);
680 usage();
681 }
682 break;
683
684 case 'C':
685 ul = strtoul(optarg, NULL, 10);
686 if (ul > MAX_CLICKTHRESHOLD) {
687 warnx("invalid argument `%s'", optarg);
688 usage();
689 }
690 opt_clickthreshold = ul;
691 break;
692
693 case 'F':
694 ul = strtoul(optarg, NULL, 10);
695 if (ul == 0) {
696 warnx("invalid argument `%s'", optarg);
697 usage();
698 }
699 opt_rate = ul;
700 break;
701
702 case 'H':
703 opt_hvirtual_scroll = true;
704 break;
705
706 case 'I':
707 pidfile = optarg;
708 break;
709
710 case 'L':
711 errno = 0;
712 ul = strtoul(optarg, NULL, 10);
713 if ((ul == 0 && errno != 0) || ul > INT_MAX) {
714 warnx("invalid argument `%s'", optarg);
715 usage();
716 }
717 opt_scroll_speed = ul;
718 break;
719
720 case 'q':
721 config_file = optarg;
722 break;
723
724 case 'Q':
725 quirks_path = optarg;
726 break;
727
728 case 'T':
729 opt_drift_terminate = true;
730 sscanf(optarg, "%u,%u,%u", &opt_drift_distance,
731 &opt_drift_time, &opt_drift_after);
732 if (opt_drift_distance == 0 ||
733 opt_drift_time == 0 ||
734 opt_drift_after == 0) {
735 warnx("invalid argument `%s'", optarg);
736 usage();
737 }
738 break;
739
740 case 'V':
741 opt_virtual_scroll = true;
742 break;
743
744 case 'U':
745 errno = 0;
746 ul = strtoul(optarg, NULL, 10);
747 if ((ul == 0 && errno != 0) || ul > INT_MAX) {
748 warnx("invalid argument `%s'", optarg);
749 usage();
750 }
751 opt_scroll_threshold = ul;
752 break;
753
754 case 'h':
755 case '?':
756 default:
757 usage();
758 }
759 }
760
761 if ((cfd = open("/dev/consolectl", O_RDWR, 0)) == -1)
762 logerr(1, "cannot open /dev/consolectl");
763 if ((kfd = kqueuex(KQUEUE_CPONFORK)) == -1)
764 logerr(1, "cannot create kqueue");
765 if (portname == NULL && (dfd = connect_devd()) == -1)
766 logwarnx("cannot open devd socket");
767
768 switch (setjmp(env)) {
769 case SIGHUP:
770 quirks_context_unref(quirks);
771 r_deinit_all();
772 /* FALLTHROUGH */
773 case 0:
774 break;
775 case SIGINT:
776 case SIGQUIT:
777 case SIGTERM:
778 exit(0);
779 /* NOT REACHED */
780 default:
781 goto out;
782 }
783
784 signal(SIGHUP , reset);
785 signal(SIGINT , reset);
786 signal(SIGQUIT, reset);
787 signal(SIGTERM, reset);
788 signal(SIGUSR1, pause_mouse);
789
790 quirks = quirks_init_subsystem(quirks_path, config_file,
791 log_or_warn_va,
792 background ? QLOG_MOUSED_LOGGING : QLOG_CUSTOM_LOG_PRIORITIES);
793 if (quirks == NULL)
794 logwarnx("cannot open configuration file %s", config_file);
795
796 if (portname == NULL) {
797 r_init_all();
798 } else {
799 if ((r = r_init(portname)) == NULL)
800 logerrx(1, "Can not initialize device");
801 }
802
803 /* print some information */
804 if (identify != ID_NONE) {
805 SLIST_FOREACH(r, &rodents, next) {
806 if (identify == ID_ALL)
807 printf("%s %s %s %s\n",
808 r->dev.path, r_if(r->dev.iftype),
809 r_name(r->dev.type), r->dev.name);
810 else if (identify & ID_PORT)
811 printf("%s\n", r->dev.path);
812 else if (identify & ID_IF)
813 printf("%s\n", r_if(r->dev.iftype));
814 else if (identify & ID_TYPE)
815 printf("%s\n", r_name(r->dev.type));
816 else if (identify & ID_MODEL)
817 printf("%s\n", r->dev.name);
818 }
819 exit(0);
820 }
821
822 if (!nodaemon && !background) {
823 pfh = pidfile_open(pidfile, 0600, &mpid);
824 if (pfh == NULL) {
825 if (errno == EEXIST)
826 logerrx(1, "moused already running, pid: %d", mpid);
827 logwarn("cannot open pid file");
828 }
829 if (daemon(0, 0)) {
830 int saved_errno = errno;
831 pidfile_remove(pfh);
832 errno = saved_errno;
833 logerr(1, "failed to become a daemon");
834 } else {
835 background = true;
836 pidfile_write(pfh);
837 }
838 }
839
840 moused();
841
842 out:
843 quirks_context_unref(quirks);
844
845 r_deinit_all();
846 if (dfd != -1)
847 close(dfd);
848 if (kfd != -1)
849 close(kfd);
850 if (cfd != -1)
851 close(cfd);
852
853 exit(0);
854 }
855
856 /*
857 * Function to calculate linear acceleration.
858 *
859 * If there are any rounding errors, the remainder
860 * is stored in the remainx and remainy variables
861 * and taken into account upon the next movement.
862 */
863
864 static void
linacc(struct accel * acc,int dx,int dy,int dz,int * movex,int * movey,int * movez)865 linacc(struct accel *acc, int dx, int dy, int dz,
866 int *movex, int *movey, int *movez)
867 {
868 double fdx, fdy, fdz;
869
870 if (dx == 0 && dy == 0 && dz == 0) {
871 *movex = *movey = *movez = 0;
872 return;
873 }
874 fdx = dx * acc->accelx + acc->remainx;
875 fdy = dy * acc->accely + acc->remainy;
876 fdz = dz * acc->accelz + acc->remainz;
877 *movex = lround(fdx);
878 *movey = lround(fdy);
879 *movez = lround(fdz);
880 acc->remainx = fdx - *movex;
881 acc->remainy = fdy - *movey;
882 acc->remainz = fdz - *movez;
883 }
884
885 /*
886 * Function to calculate exponential acceleration.
887 * (Also includes linear acceleration if enabled.)
888 *
889 * In order to give a smoother behaviour, we record the four
890 * most recent non-zero movements and use their average value
891 * to calculate the acceleration.
892 */
893
894 static void
expoacc(struct accel * acc,int dx,int dy,int dz,int * movex,int * movey,int * movez)895 expoacc(struct accel *acc, int dx, int dy, int dz,
896 int *movex, int *movey, int *movez)
897 {
898 double fdx, fdy, fdz, length, lbase, accel;
899
900 if (dx == 0 && dy == 0 && dz == 0) {
901 *movex = *movey = *movez = 0;
902 return;
903 }
904 fdx = dx * acc->accelx;
905 fdy = dy * acc->accely;
906 fdz = dz * acc->accelz;
907 length = sqrt((fdx * fdx) + (fdy * fdy)); /* Pythagoras */
908 length = (length + acc->lastlength[0] + acc->lastlength[1] +
909 acc->lastlength[2]) / 4;
910 lbase = length / acc->expoffset;
911 accel = pow(lbase, acc->expoaccel) / lbase;
912 fdx = fdx * accel + acc->remainx;
913 fdy = fdy * accel + acc->remainy;
914 *movex = lround(fdx);
915 *movey = lround(fdy);
916 *movez = lround(fdz);
917 acc->remainx = fdx - *movex;
918 acc->remainy = fdy - *movey;
919 acc->remainz = fdz - *movez;
920 acc->lastlength[2] = acc->lastlength[1];
921 acc->lastlength[1] = acc->lastlength[0];
922 /* Insert new average, not original length! */
923 acc->lastlength[0] = length;
924 }
925
926 static void
moused(void)927 moused(void)
928 {
929 struct rodent *r = NULL;
930 mousestatus_t action0; /* original mouse action */
931 mousestatus_t action; /* interim buffer */
932 mousestatus_t action2; /* mapped action */
933 struct kevent ke[3];
934 int nchanges;
935 union {
936 struct input_event ie;
937 uint8_t se[MOUSE_SYS_PACKETSIZE];
938 } b;
939 size_t b_size;
940 ssize_t r_size;
941 int flags;
942 int c;
943
944 /* clear mouse data */
945 bzero(&action0, sizeof(action0));
946 bzero(&action, sizeof(action));
947 bzero(&action2, sizeof(action2));
948 /* process mouse data */
949 for (;;) {
950
951 if (dfd == -1 && portname == NULL)
952 dfd = connect_devd();
953 nchanges = 0;
954 if (r != NULL && r->e3b.enabled &&
955 S_DELAYED(r->e3b.mouse_button_state)) {
956 EV_SET(ke + nchanges, r->mfd << 1, EVFILT_TIMER,
957 EV_ADD | EV_ENABLE | EV_DISPATCH, 0, 20, r);
958 nchanges++;
959 r->e3b.timer_armed = true;
960 }
961 if (r != NULL && r->tp.gest.idletimeout > 0) {
962 EV_SET(ke + nchanges, r->mfd << 1 | 1, EVFILT_TIMER,
963 EV_ADD | EV_ENABLE | EV_DISPATCH,
964 0, r->tp.gest.idletimeout, r);
965 nchanges++;
966 r->tp.gest.timer_armed = true;
967 }
968 if (dfd == -1 && nchanges == 0 && portname == NULL) {
969 EV_SET(ke + nchanges, UINTPTR_MAX, EVFILT_TIMER,
970 EV_ADD | EV_ENABLE | EV_ONESHOT, 0, 1000, NULL);
971 nchanges++;
972 }
973
974 if (!(r != NULL && r->tp.gest.idletimeout == 0)) {
975 c = kevent(kfd, ke, nchanges, ke, 1, NULL);
976 if (c <= 0) { /* error */
977 logwarn("failed to read from mouse");
978 continue;
979 }
980 } else
981 c = 0;
982 /* Devd event */
983 if (c > 0 && ke[0].udata == NULL) {
984 if (ke[0].filter == EVFILT_READ) {
985 if ((ke[0].flags & EV_EOF) != 0) {
986 logwarn("devd connection is closed");
987 close(dfd);
988 dfd = -1;
989 } else
990 fetch_and_parse_devd();
991 } else if (ke[0].filter == EVFILT_TIMER) {
992 /* DO NOTHING */
993 }
994 continue;
995 }
996 if (c > 0)
997 r = ke[0].udata;
998 /* E3B timeout */
999 if (c > 0 && ke[0].filter == EVFILT_TIMER &&
1000 (ke[0].ident & 1) == 0) {
1001 /* assert(rodent.flags & Emulate3Button) */
1002 action0.button = action0.obutton;
1003 action0.dx = action0.dy = action0.dz = 0;
1004 action0.flags = flags = 0;
1005 r->e3b.timer_armed = false;
1006 if (r_timeout(&r->e3b) &&
1007 r_statetrans(r, &action0, &action, A_TIMEOUT)) {
1008 if (debug > 2)
1009 debug("flags:%08x buttons:%08x obuttons:%08x",
1010 action.flags, action.button, action.obutton);
1011 } else {
1012 action0.obutton = action0.button;
1013 continue;
1014 }
1015 } else {
1016 /* mouse movement */
1017 if (c > 0 && ke[0].filter == EVFILT_READ) {
1018 b_size = rifs[r->dev.iftype].p_size;
1019 r_size = read(r->mfd, &b, b_size);
1020 if (r_size == -1) {
1021 if (errno == EWOULDBLOCK)
1022 continue;
1023 else if (portname == NULL) {
1024 r_deinit(r);
1025 r = NULL;
1026 continue;
1027 } else
1028 return;
1029 }
1030 if (r_size != (ssize_t)b_size) {
1031 logwarn("Short read from mouse: "
1032 "%zd bytes", r_size);
1033 continue;
1034 }
1035 /* Disarm nonexpired timers */
1036 nchanges = 0;
1037 if (r->e3b.timer_armed) {
1038 EV_SET(ke + nchanges, r->mfd << 1,
1039 EVFILT_TIMER, EV_DISABLE, 0, 0, r);
1040 nchanges++;
1041 r->e3b.timer_armed = false;
1042 }
1043 if (r->tp.gest.timer_armed) {
1044 EV_SET(ke + nchanges, r->mfd << 1 | 1,
1045 EVFILT_TIMER, EV_DISABLE, 0, 0, r);
1046 nchanges++;
1047 r->tp.gest.timer_armed = false;
1048 }
1049 if (nchanges != 0)
1050 kevent(kfd, ke, nchanges, NULL, 0, NULL);
1051 } else {
1052 /*
1053 * Gesture timeout expired.
1054 * Notify r_gestures by empty packet.
1055 */
1056 #ifdef DONE_RIGHT
1057 struct timespec ts;
1058 clock_gettime(CLOCK_REALTIME, &ts);
1059 b.ie.time.tv_sec = ts.tv_sec;
1060 b.ie.time.tv_usec = ts.tv_nsec / 1000;
1061 #else
1062 /* Hacky but cheap */
1063 b.ie.time.tv_sec =
1064 r->tp.gest.idletimeout == 0 ? 0 : LONG_MAX;
1065 b.ie.time.tv_usec = 0;
1066 #endif
1067 b.ie.type = EV_SYN;
1068 b.ie.code = SYN_REPORT;
1069 b.ie.value = 1;
1070 if (c > 0)
1071 r->tp.gest.timer_armed = false;
1072 }
1073 r->tp.gest.idletimeout = -1;
1074 flags = r->dev.iftype == DEVICE_IF_EVDEV ?
1075 r_protocol_evdev(r->dev.type,
1076 &r->tp, &r->ev, &b.ie, &action0) :
1077 r_protocol_sysmouse(b.se, &action0);
1078 if (flags == 0)
1079 continue;
1080
1081 if (r->scroll.enable_vert || r->scroll.enable_hor) {
1082 if (action0.button == MOUSE_BUTTON2DOWN) {
1083 debug("[BUTTON2] flags:%08x buttons:%08x obuttons:%08x",
1084 action.flags, action.button, action.obutton);
1085 } else {
1086 debug("[NOTBUTTON2] flags:%08x buttons:%08x obuttons:%08x",
1087 action.flags, action.button, action.obutton);
1088 }
1089 r_vscroll_detect(r, &r->scroll, &action0);
1090 }
1091
1092 r_timestamp(&action0, &r->btstate, &r->e3b, &r->drift);
1093 r_statetrans(r, &action0, &action,
1094 A(action0.button & MOUSE_BUTTON1DOWN,
1095 action0.button & MOUSE_BUTTON3DOWN));
1096 debug("flags:%08x buttons:%08x obuttons:%08x", action.flags,
1097 action.button, action.obutton);
1098 }
1099 action0.obutton = action0.button;
1100 flags &= MOUSE_POSCHANGED;
1101 flags |= action.obutton ^ action.button;
1102 action.flags = flags;
1103
1104 if (flags == 0)
1105 continue;
1106
1107 /* handler detected action */
1108 r_map(&action, &action2, &r->btstate);
1109 debug("activity : buttons 0x%08x dx %d dy %d dz %d",
1110 action2.button, action2.dx, action2.dy, action2.dz);
1111
1112 if (r->scroll.enable_vert || r->scroll.enable_hor) {
1113 /*
1114 * If *only* the middle button is pressed AND we are moving
1115 * the stick/trackpoint/nipple, scroll!
1116 */
1117 r_vscroll(&r->scroll, &action2);
1118 }
1119
1120 if (r->drift.terminate) {
1121 if ((flags & MOUSE_POSCHANGED) == 0 ||
1122 action.dz || action2.dz)
1123 r->drift.last_activity = r->drift.current_ts;
1124 else {
1125 if (r_drift (&r->drift, &action2))
1126 continue;
1127 }
1128 }
1129
1130 /* Defer clicks until we aren't VirtualScroll'ing. */
1131 if (r->scroll.state == SCROLL_NOTSCROLLING)
1132 r_click(&action2, &r->btstate);
1133
1134 if (action2.flags & MOUSE_POSCHANGED)
1135 r_move(&action2, &r->accel);
1136
1137 /*
1138 * If the Z axis movement is mapped to an imaginary physical
1139 * button, we need to cook up a corresponding button `up' event
1140 * after sending a button `down' event.
1141 */
1142 if ((r->btstate.zmap[0] > 0) && (action.dz != 0)) {
1143 action.obutton = action.button;
1144 action.dx = action.dy = action.dz = 0;
1145 r_map(&action, &action2, &r->btstate);
1146 debug("activity : buttons 0x%08x dx %d dy %d dz %d",
1147 action2.button, action2.dx, action2.dy, action2.dz);
1148
1149 r_click(&action2, &r->btstate);
1150 }
1151 }
1152 /* NOT REACHED */
1153 }
1154
1155 static void
reset(int sig)1156 reset(int sig)
1157 {
1158 longjmp(env, sig);
1159 }
1160
1161 static void
pause_mouse(__unused int sig)1162 pause_mouse(__unused int sig)
1163 {
1164 paused = !paused;
1165 }
1166
1167 static int
connect_devd(void)1168 connect_devd(void)
1169 {
1170 static const struct sockaddr_un sa = {
1171 .sun_family = AF_UNIX,
1172 .sun_path = "/var/run/devd.seqpacket.pipe",
1173 };
1174 struct kevent kev;
1175 int fd;
1176
1177 fd = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
1178 if (fd < 0)
1179 return (-1);
1180 if (connect(fd, (const struct sockaddr *) &sa, sizeof(sa)) < 0) {
1181 close(fd);
1182 return (-1);
1183 }
1184 EV_SET(&kev, fd, EVFILT_READ, EV_ADD, 0, 0, 0);
1185 if (kevent(kfd, &kev, 1, NULL, 0, NULL) < 0) {
1186 close(fd);
1187 return (-1);
1188 }
1189
1190 return (fd);
1191 }
1192
1193 static void
fetch_and_parse_devd(void)1194 fetch_and_parse_devd(void)
1195 {
1196 char ev[1024];
1197 char path[22] = "/dev/";
1198 char *cdev, *cr;
1199 ssize_t len;
1200
1201 if ((len = recv(dfd, ev, sizeof(ev), MSG_WAITALL)) <= 0) {
1202 close(dfd);
1203 dfd = -1;
1204 return;
1205 }
1206
1207 if (ev[0] != '!')
1208 return;
1209 if (strnstr(ev, "system=DEVFS", len) == NULL)
1210 return;
1211 if (strnstr(ev, "subsystem=CDEV", len) == NULL)
1212 return;
1213 if (strnstr(ev, "type=CREATE", len) == NULL)
1214 return;
1215 if ((cdev = strnstr(ev, "cdev=input/event", len)) == NULL)
1216 return;
1217 cr = strchr(cdev, '\n');
1218 if (cr != NULL)
1219 *cr = '\0';
1220 cr = strchr(cdev, ' ');
1221 if (cr != NULL)
1222 *cr = '\0';
1223 strncpy(path + 5, cdev + 5, 17);
1224 (void)r_init(path);
1225 return;
1226 }
1227
1228 /*
1229 * usage
1230 *
1231 * Complain, and free the CPU for more worthy tasks
1232 */
1233 static void
usage(void)1234 usage(void)
1235 {
1236 fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n",
1237 "usage: moused [-dfg] [-I file] [-F rate] [-r resolution]",
1238 " [-VH [-U threshold]] [-a X[,Y]] [-C threshold] [-m N=M] [-w N]",
1239 " [-z N] [-t <interfacetype>] [-l level] [-3 [-E timeout]]",
1240 " [-T distance[,time[,after]]] -p <port> [-q config] [-Q quirks]",
1241 " moused [-d] -i <port|if|type|model|all> -p <port>");
1242 exit(1);
1243 }
1244
1245 /*
1246 * Output an error message to syslog or stderr as appropriate. If
1247 * `errnum' is non-zero, append its string form to the message.
1248 */
1249 static void
log_or_warn_va(int log_pri,int errnum,const char * fmt,va_list ap)1250 log_or_warn_va(int log_pri, int errnum, const char *fmt, va_list ap)
1251 {
1252 char buf[256];
1253 size_t len;
1254
1255 if (debug == 0 && log_pri > LOG_ERR)
1256 return;
1257
1258 vsnprintf(buf, sizeof(buf), fmt, ap);
1259
1260 /* Strip trailing line-feed appended by quirk subsystem */
1261 len = strlen(buf);
1262 if (len != 0 && buf[len - 1] == '\n')
1263 buf[len - 1] = '\0';
1264
1265 if (errnum) {
1266 strlcat(buf, ": ", sizeof(buf));
1267 strlcat(buf, strerror(errnum), sizeof(buf));
1268 }
1269
1270 if (background)
1271 syslog(log_pri, "%s", buf);
1272 else
1273 warnx("%s", buf);
1274 }
1275
1276 static void
log_or_warn(int log_pri,int errnum,const char * fmt,...)1277 log_or_warn(int log_pri, int errnum, const char *fmt, ...)
1278 {
1279 va_list ap;
1280
1281 va_start(ap, fmt);
1282 log_or_warn_va(log_pri, errnum, fmt, ap);
1283 va_end(ap);
1284 }
1285
1286 static inline int
bit_find(bitstr_t * array,int start,int stop)1287 bit_find(bitstr_t *array, int start, int stop)
1288 {
1289 int res;
1290
1291 bit_ffs_at(array, start, stop + 1, &res);
1292 return (res != -1);
1293 }
1294
1295 static enum device_if
r_identify_if(int fd)1296 r_identify_if(int fd)
1297 {
1298 int dummy;
1299
1300 if ((force_if == DEVICE_IF_UNKNOWN || force_if == DEVICE_IF_EVDEV) &&
1301 ioctl(fd, EVIOCGVERSION, &dummy) >= 0)
1302 return (DEVICE_IF_EVDEV);
1303 if ((force_if == DEVICE_IF_UNKNOWN || force_if == DEVICE_IF_SYSMOUSE) &&
1304 ioctl(fd, MOUSE_GETLEVEL, &dummy) >= 0)
1305 return (DEVICE_IF_SYSMOUSE);
1306 return (DEVICE_IF_UNKNOWN);
1307 }
1308
1309 /* Derived from EvdevProbe() function of xf86-input-evdev driver */
1310 static enum device_type
r_identify_evdev(int fd)1311 r_identify_evdev(int fd)
1312 {
1313 enum device_type type;
1314 bitstr_t bit_decl(key_bits, KEY_CNT); /* */
1315 bitstr_t bit_decl(rel_bits, REL_CNT); /* Evdev capabilities */
1316 bitstr_t bit_decl(abs_bits, ABS_CNT); /* */
1317 bitstr_t bit_decl(prop_bits, INPUT_PROP_CNT);
1318 bool has_keys, has_buttons, has_lmr, has_rel_axes, has_abs_axes;
1319 bool has_mt;
1320
1321 /* maybe this is a evdev mouse... */
1322 if (ioctl(fd, EVIOCGBIT(EV_REL, sizeof(rel_bits)), rel_bits) < 0 ||
1323 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(abs_bits)), abs_bits) < 0 ||
1324 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(key_bits)), key_bits) < 0 ||
1325 ioctl(fd, EVIOCGPROP(sizeof(prop_bits)), prop_bits) < 0) {
1326 return (DEVICE_TYPE_UNKNOWN);
1327 }
1328
1329 has_keys = bit_find(key_bits, 0, BTN_MISC - 1);
1330 has_buttons = bit_find(key_bits, BTN_MISC, BTN_JOYSTICK - 1);
1331 has_lmr = bit_find(key_bits, BTN_LEFT, BTN_MIDDLE);
1332 has_rel_axes = bit_find(rel_bits, 0, REL_MAX);
1333 has_abs_axes = bit_find(abs_bits, 0, ABS_MAX);
1334 has_mt = bit_find(abs_bits, ABS_MT_SLOT, ABS_MAX);
1335 type = DEVICE_TYPE_UNKNOWN;
1336
1337 if (has_abs_axes) {
1338 if (has_mt && !has_buttons) {
1339 /* TBD:Improve joystick detection */
1340 if (bit_test(key_bits, BTN_JOYSTICK)) {
1341 return (DEVICE_TYPE_JOYSTICK);
1342 } else {
1343 has_buttons = true;
1344 }
1345 }
1346
1347 if (bit_test(abs_bits, ABS_X) &&
1348 bit_test(abs_bits, ABS_Y)) {
1349 if (bit_test(key_bits, BTN_TOOL_PEN) ||
1350 bit_test(key_bits, BTN_STYLUS) ||
1351 bit_test(key_bits, BTN_STYLUS2)) {
1352 type = DEVICE_TYPE_TABLET;
1353 } else if (bit_test(abs_bits, ABS_PRESSURE) ||
1354 bit_test(key_bits, BTN_TOUCH)) {
1355 if (has_lmr ||
1356 bit_test(key_bits, BTN_TOOL_FINGER)) {
1357 type = DEVICE_TYPE_TOUCHPAD;
1358 } else {
1359 type = DEVICE_TYPE_TOUCHSCREEN;
1360 }
1361 /* some touchscreens use BTN_LEFT rather than BTN_TOUCH */
1362 } else if (!(bit_test(rel_bits, REL_X) &&
1363 bit_test(rel_bits, REL_Y)) &&
1364 has_lmr) {
1365 type = DEVICE_TYPE_TOUCHSCREEN;
1366 }
1367 }
1368 }
1369
1370 if (type == DEVICE_TYPE_UNKNOWN) {
1371 if (has_keys)
1372 type = DEVICE_TYPE_KEYBOARD;
1373 else if (has_rel_axes || has_buttons)
1374 type = DEVICE_TYPE_MOUSE;
1375 }
1376
1377 return (type);
1378 }
1379
1380 static enum device_type
r_identify_sysmouse(int fd __unused)1381 r_identify_sysmouse(int fd __unused)
1382 {
1383 /* All sysmouse devices act like mices */
1384 return (DEVICE_TYPE_MOUSE);
1385 }
1386
1387 static const char *
r_if(enum device_if type)1388 r_if(enum device_if type)
1389 {
1390 const char *unknown = "unknown";
1391
1392 return (type == DEVICE_IF_UNKNOWN || type >= (int)nitems(rifs) ?
1393 unknown : rifs[type].name);
1394 }
1395
1396 static const char *
r_name(enum device_type type)1397 r_name(enum device_type type)
1398 {
1399 const char *unknown = "unknown";
1400
1401 return (type == DEVICE_TYPE_UNKNOWN || type >= (int)nitems(rnames) ?
1402 unknown : rnames[type]);
1403 }
1404
1405 static int
r_init_dev_evdev(int fd,struct device * dev)1406 r_init_dev_evdev(int fd, struct device *dev)
1407 {
1408 if (ioctl(fd, EVIOCGNAME(sizeof(dev->name) - 1), dev->name) < 0) {
1409 logwarnx("unable to get device %s name", dev->path);
1410 return (errno);
1411 }
1412 /* Do not loop events */
1413 if (strncmp(dev->name, "System mouse", sizeof(dev->name)) == 0) {
1414 return (ENOTSUP);
1415 }
1416 if (ioctl(fd, EVIOCGID, &dev->id) < 0) {
1417 logwarnx("unable to get device %s ID", dev->path);
1418 return (errno);
1419 }
1420 (void)ioctl(fd, EVIOCGUNIQ(sizeof(dev->uniq) - 1), dev->uniq);
1421
1422 return (0);
1423 }
1424
1425 static int
r_init_dev_sysmouse(int fd,struct device * dev)1426 r_init_dev_sysmouse(int fd, struct device *dev)
1427 {
1428 mousemode_t *mode = &dev->mode;
1429 int level;
1430
1431 level = 1;
1432 if (ioctl(fd, MOUSE_SETLEVEL, &level) < 0) {
1433 logwarnx("unable to MOUSE_SETLEVEL for device %s", dev->path);
1434 return (errno);
1435 }
1436 if (ioctl(fd, MOUSE_GETLEVEL, &level) < 0) {
1437 logwarnx("unable to MOUSE_GETLEVEL for device %s", dev->path);
1438 return (errno);
1439 }
1440 if (level != 1) {
1441 logwarnx("unable to set level to 1 for device %s", dev->path);
1442 return (ENOTSUP);
1443 }
1444 memset(mode, 0, sizeof(*mode));
1445 if (ioctl(fd, MOUSE_GETMODE, mode) < 0) {
1446 logwarnx("unable to MOUSE_GETMODE for device %s", dev->path);
1447 return (errno);
1448 }
1449 if (mode->protocol != MOUSE_PROTO_SYSMOUSE) {
1450 logwarnx("unable to set sysmouse protocol for device %s",
1451 dev->path);
1452 return (ENOTSUP);
1453 }
1454 if (mode->packetsize != MOUSE_SYS_PACKETSIZE) {
1455 logwarnx("unable to set sysmouse packet size for device %s",
1456 dev->path);
1457 return (ENOTSUP);
1458 }
1459
1460 /* TODO: Fill name, id and uniq from dev.* sysctls */
1461 strlcpy(dev->name, dev->path, sizeof(dev->name));
1462
1463 return (0);
1464 }
1465
1466 static void
r_init_evstate(struct quirks * q,struct evstate * ev)1467 r_init_evstate(struct quirks *q, struct evstate *ev)
1468 {
1469 const struct quirk_tuples *t;
1470 bitstr_t *bitstr;
1471 int maxbit;
1472
1473 if (quirks_get_tuples(q, QUIRK_ATTR_EVENT_CODE, &t)) {
1474 for (size_t i = 0; i < t->ntuples; i++) {
1475 int type = t->tuples[i].first;
1476 int code = t->tuples[i].second;
1477 bool enable = t->tuples[i].third;
1478
1479 switch (type) {
1480 case EV_KEY:
1481 bitstr = (bitstr_t *)&ev->key_ignore;
1482 maxbit = KEY_MAX;
1483 break;
1484 case EV_REL:
1485 bitstr = (bitstr_t *)&ev->rel_ignore;
1486 maxbit = REL_MAX;
1487 break;
1488 case EV_ABS:
1489 bitstr = (bitstr_t *)&ev->abs_ignore;
1490 maxbit = ABS_MAX;
1491 break;
1492 default:
1493 continue;
1494 }
1495
1496 if (code == EVENT_CODE_UNDEFINED) {
1497 if (enable)
1498 bit_nclear(bitstr, 0, maxbit);
1499 else
1500 bit_nset(bitstr, 0, maxbit);
1501 } else {
1502 if (code > maxbit)
1503 continue;
1504 if (enable)
1505 bit_clear(bitstr, code);
1506 else
1507 bit_set(bitstr, code);
1508 }
1509 }
1510 }
1511
1512 if (quirks_get_tuples(q, QUIRK_ATTR_INPUT_PROP, &t)) {
1513 for (size_t idx = 0; idx < t->ntuples; idx++) {
1514 unsigned int p = t->tuples[idx].first;
1515 bool enable = t->tuples[idx].second;
1516
1517 if (p > INPUT_PROP_MAX)
1518 continue;
1519 if (enable)
1520 bit_clear(ev->prop_ignore, p);
1521 else
1522 bit_set(ev->prop_ignore, p);
1523 }
1524 }
1525 }
1526
1527 static void
r_init_buttons(struct quirks * q,struct btstate * bt,struct e3bstate * e3b)1528 r_init_buttons(struct quirks *q, struct btstate *bt, struct e3bstate *e3b)
1529 {
1530 struct timespec ts;
1531 int i, j;
1532
1533 *bt = (struct btstate) {
1534 .clickthreshold = DFLT_CLICKTHRESHOLD,
1535 .zmap = { 0, 0, 0, 0 },
1536 };
1537
1538 memcpy(bt->p2l, default_p2l, sizeof(bt->p2l));
1539 for (i = 0; i < MOUSE_MAXBUTTON; ++i) {
1540 j = i;
1541 if (opt_btstate.p2l[i] != 0)
1542 bt->p2l[i] = opt_btstate.p2l[i];
1543 if (opt_btstate.mstate[i] != NULL)
1544 j = opt_btstate.mstate[i] - opt_btstate.bstate;
1545 bt->mstate[i] = bt->bstate + j;
1546 }
1547
1548 if (opt_btstate.zmap[0] != 0)
1549 memcpy(bt->zmap, opt_btstate.zmap, sizeof(bt->zmap));
1550 if (opt_clickthreshold >= 0)
1551 bt->clickthreshold = opt_clickthreshold;
1552 else
1553 quirks_get_uint32(q, MOUSED_CLICK_THRESHOLD, &bt->clickthreshold);
1554 if (opt_wmode != 0)
1555 bt->wmode = opt_wmode;
1556 else
1557 quirks_get_uint32(q, MOUSED_WMODE, &bt->wmode);
1558 if (bt->wmode != 0)
1559 bt->wmode = 1 << (bt->wmode - 1);
1560
1561 /* fix Z axis mapping */
1562 for (i = 0; i < ZMAP_MAXBUTTON; ++i) {
1563 if (bt->zmap[i] <= 0)
1564 continue;
1565 for (j = 0; j < MOUSE_MAXBUTTON; ++j) {
1566 if (bt->mstate[j] == &bt->bstate[bt->zmap[i] - 1])
1567 bt->mstate[j] = &bt->zstate[i];
1568 }
1569 bt->zmap[i] = 1 << (bt->zmap[i] - 1);
1570 }
1571
1572 clock_gettime(CLOCK_MONOTONIC_FAST, &ts);
1573
1574 *e3b = (struct e3bstate) {
1575 .enabled = false,
1576 .button2timeout = DFLT_BUTTON2TIMEOUT,
1577 };
1578 e3b->enabled = opt_e3b_enabled;
1579 if (!e3b->enabled)
1580 quirks_get_bool(q, MOUSED_EMULATE_THIRD_BUTTON, &e3b->enabled);
1581 if (opt_e3b_button2timeout >= 0)
1582 e3b->button2timeout = opt_e3b_button2timeout;
1583 else
1584 quirks_get_uint32(q, MOUSED_EMULATE_THIRD_BUTTON_TIMEOUT,
1585 &e3b->button2timeout);
1586 e3b->mouse_button_state = S0;
1587 e3b->mouse_button_state_ts = ts;
1588 e3b->mouse_move_delayed = 0;
1589
1590 for (i = 0; i < MOUSE_MAXBUTTON; ++i) {
1591 bt->bstate[i].count = 0;
1592 bt->bstate[i].ts = ts;
1593 }
1594 for (i = 0; i < ZMAP_MAXBUTTON; ++i) {
1595 bt->zstate[i].count = 0;
1596 bt->zstate[i].ts = ts;
1597 }
1598 }
1599
1600 static void
r_init_touchpad_hw(int fd,struct quirks * q,struct tpcaps * tphw,struct evstate * ev)1601 r_init_touchpad_hw(int fd, struct quirks *q, struct tpcaps *tphw,
1602 struct evstate *ev)
1603 {
1604 struct input_absinfo ai;
1605 bitstr_t bit_decl(key_bits, KEY_CNT);
1606 bitstr_t bit_decl(abs_bits, ABS_CNT);
1607 bitstr_t bit_decl(prop_bits, INPUT_PROP_CNT);
1608 struct quirk_range r;
1609 struct quirk_dimensions dim;
1610 u_int u;
1611
1612 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(abs_bits)), abs_bits);
1613 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(key_bits)), key_bits);
1614
1615 if (!bit_test(ev->abs_ignore, ABS_X) &&
1616 ioctl(fd, EVIOCGABS(ABS_X), &ai) >= 0) {
1617 tphw->min_x = (ai.maximum > ai.minimum) ? ai.minimum : INT_MIN;
1618 tphw->max_x = (ai.maximum > ai.minimum) ? ai.maximum : INT_MAX;
1619 tphw->res_x = ai.resolution == 0 ?
1620 DFLT_TPAD_RESOLUTION : ai.resolution;
1621 }
1622 if (!bit_test(ev->abs_ignore, ABS_Y) &&
1623 ioctl(fd, EVIOCGABS(ABS_Y), &ai) >= 0) {
1624 tphw->min_y = (ai.maximum > ai.minimum) ? ai.minimum : INT_MIN;
1625 tphw->max_y = (ai.maximum > ai.minimum) ? ai.maximum : INT_MAX;
1626 tphw->res_y = ai.resolution == 0 ?
1627 DFLT_TPAD_RESOLUTION : ai.resolution;
1628 }
1629 if (quirks_get_dimensions(q, QUIRK_ATTR_RESOLUTION_HINT, &dim)) {
1630 tphw->res_x = dim.x;
1631 tphw->res_y = dim.y;
1632 } else if (tphw->max_x != INT_MAX && tphw->max_y != INT_MAX &&
1633 quirks_get_dimensions(q, QUIRK_ATTR_SIZE_HINT, &dim)) {
1634 tphw->res_x = (tphw->max_x - tphw->min_x) / dim.x;
1635 tphw->res_y = (tphw->max_y - tphw->min_y) / dim.y;
1636 }
1637 if (!bit_test(ev->key_ignore, BTN_TOUCH) &&
1638 bit_test(key_bits, BTN_TOUCH))
1639 tphw->cap_touch = true;
1640 /* XXX: libinput uses ABS_MT_PRESSURE where available */
1641 if (!bit_test(ev->abs_ignore, ABS_PRESSURE) &&
1642 bit_test(abs_bits, ABS_PRESSURE) &&
1643 ioctl(fd, EVIOCGABS(ABS_PRESSURE), &ai) >= 0) {
1644 tphw->cap_pressure = true;
1645 tphw->min_p = ai.minimum;
1646 tphw->max_p = ai.maximum;
1647 }
1648 if (tphw->cap_pressure &&
1649 quirks_get_range(q, QUIRK_ATTR_PRESSURE_RANGE, &r)) {
1650 if (r.upper == 0 && r.lower == 0) {
1651 debug("pressure-based touch detection disabled");
1652 tphw->cap_pressure = false;
1653 } else if (r.upper > tphw->max_p || r.upper < tphw->min_p ||
1654 r.lower > tphw->max_p || r.lower < tphw->min_p) {
1655 debug("discarding out-of-bounds pressure range %d:%d",
1656 r.lower, r.upper);
1657 tphw->cap_pressure = false;
1658 }
1659 }
1660 /* XXX: libinput uses ABS_MT_TOUCH_MAJOR where available */
1661 if (!bit_test(ev->abs_ignore, ABS_TOOL_WIDTH) &&
1662 bit_test(abs_bits, ABS_TOOL_WIDTH) &&
1663 quirks_get_uint32(q, QUIRK_ATTR_PALM_SIZE_THRESHOLD, &u) &&
1664 u != 0)
1665 tphw->cap_width = true;
1666 if (!bit_test(ev->abs_ignore, ABS_MT_SLOT) &&
1667 bit_test(abs_bits, ABS_MT_SLOT) &&
1668 !bit_test(ev->abs_ignore, ABS_MT_TRACKING_ID) &&
1669 bit_test(abs_bits, ABS_MT_TRACKING_ID) &&
1670 !bit_test(ev->abs_ignore, ABS_MT_POSITION_X) &&
1671 bit_test(abs_bits, ABS_MT_POSITION_X) &&
1672 !bit_test(ev->abs_ignore, ABS_MT_POSITION_Y) &&
1673 bit_test(abs_bits, ABS_MT_POSITION_Y))
1674 tphw->is_mt = true;
1675 if ( ioctl(fd, EVIOCGPROP(sizeof(prop_bits)), prop_bits) >= 0 &&
1676 !bit_test(ev->prop_ignore, INPUT_PROP_BUTTONPAD) &&
1677 bit_test(prop_bits, INPUT_PROP_BUTTONPAD))
1678 tphw->is_clickpad = true;
1679 if ( tphw->is_clickpad &&
1680 !bit_test(ev->prop_ignore, INPUT_PROP_TOPBUTTONPAD) &&
1681 bit_test(prop_bits, INPUT_PROP_TOPBUTTONPAD))
1682 tphw->is_topbuttonpad = true;
1683 }
1684
1685 static void
r_init_touchpad_info(struct quirks * q,struct tpcaps * tphw,struct tpinfo * tpinfo)1686 r_init_touchpad_info(struct quirks *q, struct tpcaps *tphw,
1687 struct tpinfo *tpinfo)
1688 {
1689 struct quirk_range r;
1690 int i;
1691 u_int u;
1692 int sz_x, sz_y;
1693
1694 *tpinfo = (struct tpinfo) {
1695 .two_finger_scroll = true,
1696 .natural_scroll = false,
1697 .three_finger_drag = false,
1698 .min_pressure_hi = 1,
1699 .min_pressure_lo = 1,
1700 .max_pressure = 130,
1701 .max_width = 16,
1702 .tap_timeout = 180, /* ms */
1703 .tap_threshold = 0,
1704 .tap_max_delta = 1.3, /* mm */
1705 .taphold_timeout = 300, /* ms */
1706 .vscroll_min_delta = 1.25, /* mm */
1707 .vscroll_hor_area = 0.0, /* mm */
1708 .vscroll_ver_area = -15.0, /* mm */
1709 };
1710
1711 quirks_get_bool(q, MOUSED_TWO_FINGER_SCROLL, &tpinfo->two_finger_scroll);
1712 quirks_get_bool(q, MOUSED_NATURAL_SCROLL, &tpinfo->natural_scroll);
1713 quirks_get_bool(q, MOUSED_THREE_FINGER_DRAG, &tpinfo->three_finger_drag);
1714 quirks_get_uint32(q, MOUSED_TAP_TIMEOUT, &tpinfo->tap_timeout);
1715 quirks_get_double(q, MOUSED_TAP_MAX_DELTA, &tpinfo->tap_max_delta);
1716 quirks_get_uint32(q, MOUSED_TAPHOLD_TIMEOUT, &tpinfo->taphold_timeout);
1717 quirks_get_double(q, MOUSED_VSCROLL_MIN_DELTA, &tpinfo->vscroll_min_delta);
1718 quirks_get_double(q, MOUSED_VSCROLL_HOR_AREA, &tpinfo->vscroll_hor_area);
1719 quirks_get_double(q, MOUSED_VSCROLL_VER_AREA, &tpinfo->vscroll_ver_area);
1720
1721 if (tphw->cap_pressure &&
1722 quirks_get_range(q, QUIRK_ATTR_PRESSURE_RANGE, &r)) {
1723 tpinfo->min_pressure_lo = r.lower;
1724 tpinfo->min_pressure_hi = r.upper;
1725 quirks_get_uint32(q, QUIRK_ATTR_PALM_PRESSURE_THRESHOLD,
1726 &tpinfo->max_pressure);
1727 quirks_get_uint32(q, MOUSED_TAP_PRESSURE_THRESHOLD,
1728 &tpinfo->tap_threshold);
1729 }
1730 if (tphw->cap_width)
1731 quirks_get_uint32(q, QUIRK_ATTR_PALM_SIZE_THRESHOLD,
1732 &tpinfo->max_width);
1733 /* Set bottom quarter as 42% - 16% - 42% sized softbuttons */
1734 if (tphw->is_clickpad) {
1735 sz_x = tphw->max_x - tphw->min_x;
1736 sz_y = tphw->max_y - tphw->min_y;
1737 i = 25;
1738 if (tphw->is_topbuttonpad)
1739 i = -i;
1740 quirks_get_int32(q, MOUSED_SOFTBUTTONS_Y, &i);
1741 tpinfo->softbuttons_y = sz_y * i / 100;
1742 u = 42;
1743 quirks_get_uint32(q, MOUSED_SOFTBUTTON2_X, &u);
1744 tpinfo->softbutton2_x = sz_x * u / 100;
1745 u = 58;
1746 quirks_get_uint32(q, MOUSED_SOFTBUTTON3_X, &u);
1747 tpinfo->softbutton3_x = sz_x * u / 100;
1748 }
1749 }
1750
1751 static void
r_init_touchpad_accel(struct tpcaps * tphw,struct accel * accel)1752 r_init_touchpad_accel(struct tpcaps *tphw, struct accel *accel)
1753 {
1754 /* Normalize pointer movement to match 200dpi mouse */
1755 accel->accelx *= DFLT_MOUSE_RESOLUTION;
1756 accel->accelx /= tphw->res_x;
1757 accel->accely *= DFLT_MOUSE_RESOLUTION;
1758 accel->accely /= tphw->res_y;
1759 accel->accelz *= DFLT_MOUSE_RESOLUTION;
1760 accel->accelz /= (tphw->res_x * DFLT_LINEHEIGHT);
1761 }
1762
1763 static void
r_init_touchpad_gesture(struct tpstate * gest)1764 r_init_touchpad_gesture(struct tpstate *gest)
1765 {
1766 gest->idletimeout = -1;
1767 }
1768
1769 static void
r_init_drift(struct quirks * q,struct drift * d)1770 r_init_drift(struct quirks *q, struct drift *d)
1771 {
1772 if (opt_drift_terminate) {
1773 d->terminate = true;
1774 d->distance = opt_drift_distance;
1775 d->time = opt_drift_time;
1776 d->after = opt_drift_after;
1777 } else if (quirks_get_bool(q, MOUSED_DRIFT_TERMINATE, &d->terminate) &&
1778 d->terminate) {
1779 quirks_get_uint32(q, MOUSED_DRIFT_DISTANCE, &d->distance);
1780 quirks_get_uint32(q, MOUSED_DRIFT_TIME, &d->time);
1781 quirks_get_uint32(q, MOUSED_DRIFT_AFTER, &d->after);
1782 } else
1783 return;
1784
1785 if (d->distance == 0 || d->time == 0 || d->after == 0) {
1786 warnx("invalid drift parameter");
1787 exit(1);
1788 }
1789
1790 debug("terminate drift: distance %d, time %d, after %d",
1791 d->distance, d->time, d->after);
1792
1793 d->time_ts = msec2ts(d->time);
1794 d->twotime_ts = msec2ts(d->time * 2);
1795 d->after_ts = msec2ts(d->after);
1796 }
1797
1798 static void
r_init_accel(struct quirks * q,struct accel * acc)1799 r_init_accel(struct quirks *q, struct accel *acc)
1800 {
1801 bool r1, r2;
1802
1803 acc->accelx = opt_accelx;
1804 if (opt_accelx == 1.0)
1805 quirks_get_double(q, MOUSED_LINEAR_ACCEL_X, &acc->accelx);
1806 acc->accely = opt_accely;
1807 if (opt_accely == 1.0)
1808 quirks_get_double(q, MOUSED_LINEAR_ACCEL_Y, &acc->accely);
1809 if (!quirks_get_double(q, MOUSED_LINEAR_ACCEL_Z, &acc->accelz))
1810 acc->accelz = 1.0;
1811 acc->lastlength[0] = acc->lastlength[1] = acc->lastlength[2] = 0.0;
1812 if (opt_exp_accel) {
1813 acc->is_exponential = true;
1814 acc->expoaccel = opt_expoaccel;
1815 acc->expoffset = opt_expoffset;
1816 return;
1817 }
1818 acc->expoaccel = acc->expoffset = 1.0;
1819 r1 = quirks_get_double(q, MOUSED_EXPONENTIAL_ACCEL, &acc->expoaccel);
1820 r2 = quirks_get_double(q, MOUSED_EXPONENTIAL_OFFSET, &acc->expoffset);
1821 if (r1 || r2)
1822 acc->is_exponential = true;
1823 }
1824
1825 static void
r_init_scroll(struct quirks * q,struct scroll * scroll)1826 r_init_scroll(struct quirks *q, struct scroll *scroll)
1827 {
1828 *scroll = (struct scroll) {
1829 .threshold = DFLT_SCROLLTHRESHOLD,
1830 .speed = DFLT_SCROLLSPEED,
1831 .state = SCROLL_NOTSCROLLING,
1832 };
1833 scroll->enable_vert = opt_virtual_scroll;
1834 if (!opt_virtual_scroll)
1835 quirks_get_bool(q, MOUSED_VIRTUAL_SCROLL_ENABLE, &scroll->enable_vert);
1836 scroll->enable_hor = opt_hvirtual_scroll;
1837 if (!opt_hvirtual_scroll)
1838 quirks_get_bool(q, MOUSED_HOR_VIRTUAL_SCROLL_ENABLE, &scroll->enable_hor);
1839 if (opt_scroll_speed >= 0)
1840 scroll->speed = opt_scroll_speed;
1841 else
1842 quirks_get_uint32(q, MOUSED_VIRTUAL_SCROLL_SPEED, &scroll->speed);
1843 if (opt_scroll_threshold >= 0)
1844 scroll->threshold = opt_scroll_threshold;
1845 else
1846 quirks_get_uint32(q, MOUSED_VIRTUAL_SCROLL_THRESHOLD, &scroll->threshold);
1847 }
1848
1849 static struct rodent *
r_init(const char * path)1850 r_init(const char *path)
1851 {
1852 struct rodent *r;
1853 struct device dev;
1854 struct quirks *q;
1855 struct kevent kev;
1856 enum device_if iftype;
1857 enum device_type type;
1858 int fd, err;
1859 bool grab;
1860 bool ignore;
1861 bool qvalid;
1862
1863 fd = open(path, O_RDWR | O_NONBLOCK);
1864 if (fd == -1) {
1865 logwarnx("unable to open %s", path);
1866 return (NULL);
1867 }
1868
1869 iftype = r_identify_if(fd);
1870 switch (iftype) {
1871 case DEVICE_IF_UNKNOWN:
1872 debug("cannot determine interface type on %s", path);
1873 close(fd);
1874 errno = ENOTSUP;
1875 return (NULL);
1876 case DEVICE_IF_EVDEV:
1877 type = r_identify_evdev(fd);
1878 break;
1879 case DEVICE_IF_SYSMOUSE:
1880 type = r_identify_sysmouse(fd);
1881 break;
1882 default:
1883 debug("unsupported interface type: %s on %s",
1884 r_if(iftype), path);
1885 close(fd);
1886 errno = ENXIO;
1887 return (NULL);
1888 }
1889
1890 switch (type) {
1891 case DEVICE_TYPE_UNKNOWN:
1892 debug("cannot determine device type on %s", path);
1893 close(fd);
1894 errno = ENOTSUP;
1895 return (NULL);
1896 case DEVICE_TYPE_MOUSE:
1897 case DEVICE_TYPE_TOUCHPAD:
1898 break;
1899 default:
1900 debug("unsupported device type: %s on %s",
1901 r_name(type), path);
1902 close(fd);
1903 errno = ENXIO;
1904 return (NULL);
1905 }
1906
1907 memset(&dev, 0, sizeof(struct device));
1908 strlcpy(dev.path, path, sizeof(dev.path));
1909 dev.iftype = iftype;
1910 dev.type = type;
1911 switch (iftype) {
1912 case DEVICE_IF_EVDEV:
1913 err = r_init_dev_evdev(fd, &dev);
1914 break;
1915 case DEVICE_IF_SYSMOUSE:
1916 err = r_init_dev_sysmouse(fd, &dev);
1917 break;
1918 default:
1919 debug("unsupported interface type: %s on %s",
1920 r_if(iftype), path);
1921 err = ENXIO;
1922 }
1923 if (err != 0) {
1924 debug("failed to initialize device: %s %s on %s",
1925 r_if(iftype), r_name(type), path);
1926 close(fd);
1927 errno = err;
1928 return (NULL);
1929 }
1930
1931 debug("port: %s interface: %s type: %s model: %s",
1932 path, r_if(iftype), r_name(type), dev.name);
1933
1934 q = quirks_fetch_for_device(quirks, &dev);
1935
1936 qvalid = quirks_get_bool(q, MOUSED_IGNORE_DEVICE, &ignore);
1937 if (qvalid && ignore) {
1938 debug("%s: device ignored", path);
1939 close(fd);
1940 quirks_unref(q);
1941 errno = EPERM;
1942 return (NULL);
1943 }
1944
1945 switch (iftype) {
1946 case DEVICE_IF_EVDEV:
1947 grab = opt_grab;
1948 if (!grab)
1949 qvalid = quirks_get_bool(q, MOUSED_GRAB_DEVICE, &grab);
1950 if (qvalid && grab && ioctl(fd, EVIOCGRAB, 1) == -1) {
1951 logwarnx("failed to grab %s", path);
1952 err = errno;
1953 }
1954 break;
1955 case DEVICE_IF_SYSMOUSE:
1956 if (opt_resolution == MOUSE_RES_UNKNOWN && opt_rate == 0)
1957 break;
1958 if (opt_resolution != MOUSE_RES_UNKNOWN)
1959 dev.mode.resolution = opt_resolution;
1960 if (opt_resolution != 0)
1961 dev.mode.rate = opt_rate;
1962 if (ioctl(fd, MOUSE_SETMODE, &dev.mode) < 0)
1963 debug("failed to MOUSE_SETMODE for device %s", path);
1964 break;
1965 default:
1966 debug("unsupported interface type: %s on %s",
1967 r_if(iftype), path);
1968 err = ENXIO;
1969 }
1970 if (err != 0) {
1971 debug("failed to initialize device: %s %s on %s",
1972 r_if(iftype), r_name(type), path);
1973 close(fd);
1974 quirks_unref(q);
1975 errno = err;
1976 return (NULL);
1977 }
1978
1979 r = calloc(1, sizeof(struct rodent));
1980 memcpy(&r->dev, &dev, sizeof(struct device));
1981 r->mfd = fd;
1982
1983 EV_SET(&kev, fd, EVFILT_READ, EV_ADD, 0, 0, r);
1984 err = kevent(kfd, &kev, 1, NULL, 0, NULL);
1985 if (err == -1) {
1986 logwarnx("failed to register kevent on %s", path);
1987 close(fd);
1988 free(r);
1989 quirks_unref(q);
1990 return (NULL);
1991 }
1992
1993 if (iftype == DEVICE_IF_EVDEV)
1994 r_init_evstate(q, &r->ev);
1995 r_init_buttons(q, &r->btstate, &r->e3b);
1996 r_init_scroll(q, &r->scroll);
1997 r_init_accel(q, &r->accel);
1998 switch (type) {
1999 case DEVICE_TYPE_TOUCHPAD:
2000 r_init_touchpad_hw(fd, q, &r->tp.hw, &r->ev);
2001 r_init_touchpad_info(q, &r->tp.hw, &r->tp.info);
2002 r_init_touchpad_accel(&r->tp.hw, &r->accel);
2003 r_init_touchpad_gesture(&r->tp.gest);
2004 break;
2005
2006 case DEVICE_TYPE_MOUSE:
2007 r_init_drift(q, &r->drift);
2008 break;
2009
2010 default:
2011 debug("unsupported device type: %s", r_name(type));
2012 break;
2013 }
2014
2015 quirks_unref(q);
2016
2017 SLIST_INSERT_HEAD(&rodents, r, next);
2018
2019 return (r);
2020 }
2021
2022 static void
r_init_all(void)2023 r_init_all(void)
2024 {
2025 char path[22] = "/dev/input/";
2026 DIR *dirp;
2027 struct dirent *dp;
2028
2029 dirp = opendir("/dev/input");
2030 if (dirp == NULL)
2031 logerr(1, "Failed to open /dev/input");
2032
2033 while ((dp = readdir(dirp)) != NULL) {
2034 if (fnmatch("event[0-9]*", dp->d_name, 0) == 0) {
2035 strncpy(path + 11, dp->d_name, 10);
2036 (void)r_init(path);
2037 }
2038 }
2039 (void)closedir(dirp);
2040
2041 return;
2042 }
2043
2044 static void
r_deinit(struct rodent * r)2045 r_deinit(struct rodent *r)
2046 {
2047 struct kevent ke[3];
2048
2049 if (r == NULL)
2050 return;
2051 if (r->mfd != -1) {
2052 EV_SET(ke, r->mfd, EVFILT_READ, EV_DELETE, 0, 0, r);
2053 EV_SET(ke + 1, r->mfd << 1, EVFILT_TIMER, EV_DELETE, 0, 0, r);
2054 EV_SET(ke + 2, r->mfd << 1 | 1,
2055 EVFILT_TIMER, EV_DELETE, 0, 0, r);
2056 kevent(kfd, ke, nitems(ke), NULL, 0, NULL);
2057 close(r->mfd);
2058 }
2059 SLIST_REMOVE(&rodents, r, rodent, next);
2060 debug("destroy device: port: %s model: %s", r->dev.path, r->dev.name);
2061 free(r);
2062 }
2063
2064 static void
r_deinit_all(void)2065 r_deinit_all(void)
2066 {
2067 while (!SLIST_EMPTY(&rodents))
2068 r_deinit(SLIST_FIRST(&rodents));
2069 }
2070
2071 static int
r_protocol_evdev(enum device_type type,struct tpad * tp,struct evstate * ev,struct input_event * ie,mousestatus_t * act)2072 r_protocol_evdev(enum device_type type, struct tpad *tp, struct evstate *ev,
2073 struct input_event *ie, mousestatus_t *act)
2074 {
2075 const struct tpcaps *tphw = &tp->hw;
2076 const struct tpinfo *tpinfo = &tp->info;
2077
2078 static int butmapev[8] = { /* evdev */
2079 0,
2080 MOUSE_BUTTON1DOWN,
2081 MOUSE_BUTTON3DOWN,
2082 MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
2083 MOUSE_BUTTON2DOWN,
2084 MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
2085 MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
2086 MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
2087 };
2088 struct timespec ietime;
2089
2090 /* Drop ignored codes */
2091 switch (ie->type) {
2092 case EV_REL:
2093 if (bit_test(ev->rel_ignore, ie->code))
2094 return (0);
2095 case EV_ABS:
2096 if (bit_test(ev->abs_ignore, ie->code))
2097 return (0);
2098 case EV_KEY:
2099 if (bit_test(ev->key_ignore, ie->code))
2100 return (0);
2101 }
2102
2103 if (debug > 1)
2104 debug("received event 0x%02x, 0x%04x, %d",
2105 ie->type, ie->code, ie->value);
2106
2107 switch (ie->type) {
2108 case EV_REL:
2109 switch (ie->code) {
2110 case REL_X:
2111 ev->dx += ie->value;
2112 break;
2113 case REL_Y:
2114 ev->dy += ie->value;
2115 break;
2116 case REL_WHEEL:
2117 ev->dz += ie->value;
2118 break;
2119 case REL_HWHEEL:
2120 ev->dw += ie->value;
2121 break;
2122 }
2123 break;
2124 case EV_ABS:
2125 switch (ie->code) {
2126 case ABS_X:
2127 if (!tphw->is_mt)
2128 ev->dx += ie->value - ev->st.x;
2129 ev->st.x = ie->value;
2130 break;
2131 case ABS_Y:
2132 if (!tphw->is_mt)
2133 ev->dy += ie->value - ev->st.y;
2134 ev->st.y = ie->value;
2135 break;
2136 case ABS_PRESSURE:
2137 ev->st.p = ie->value;
2138 break;
2139 case ABS_TOOL_WIDTH:
2140 ev->st.w = ie->value;
2141 break;
2142 case ABS_MT_SLOT:
2143 if (tphw->is_mt)
2144 ev->slot = ie->value;
2145 break;
2146 case ABS_MT_TRACKING_ID:
2147 if (tphw->is_mt &&
2148 ev->slot >= 0 && ev->slot < MAX_FINGERS) {
2149 if (ie->value != -1 && ev->mt[ev->slot].id > 0 &&
2150 ie->value + 1 != ev->mt[ev->slot].id) {
2151 debug("tracking id changed %d->%d",
2152 ie->value, ev->mt[ev->slot].id - 1);
2153 ev->mt[ev->slot].id = 0;
2154 } else
2155 ev->mt[ev->slot].id = ie->value + 1;
2156 }
2157 break;
2158 case ABS_MT_POSITION_X:
2159 if (tphw->is_mt &&
2160 ev->slot >= 0 && ev->slot < MAX_FINGERS) {
2161 /* Find fastest finger */
2162 int dx = ie->value - ev->mt[ev->slot].x;
2163 if (abs(dx) > abs(ev->dx))
2164 ev->dx = dx;
2165 ev->mt[ev->slot].x = ie->value;
2166 }
2167 break;
2168 case ABS_MT_POSITION_Y:
2169 if (tphw->is_mt &&
2170 ev->slot >= 0 && ev->slot < MAX_FINGERS) {
2171 /* Find fastest finger */
2172 int dy = ie->value - ev->mt[ev->slot].y;
2173 if (abs(dy) > abs(ev->dy))
2174 ev->dy = dy;
2175 ev->mt[ev->slot].y = ie->value;
2176 }
2177 break;
2178 }
2179 break;
2180 case EV_KEY:
2181 switch (ie->code) {
2182 case BTN_TOUCH:
2183 ev->st.id = ie->value != 0 ? 1 : 0;
2184 break;
2185 case BTN_TOOL_FINGER:
2186 ev->nfingers = ie->value != 0 ? 1 : ev->nfingers;
2187 break;
2188 case BTN_TOOL_DOUBLETAP:
2189 ev->nfingers = ie->value != 0 ? 2 : ev->nfingers;
2190 break;
2191 case BTN_TOOL_TRIPLETAP:
2192 ev->nfingers = ie->value != 0 ? 3 : ev->nfingers;
2193 break;
2194 case BTN_TOOL_QUADTAP:
2195 ev->nfingers = ie->value != 0 ? 4 : ev->nfingers;
2196 break;
2197 case BTN_TOOL_QUINTTAP:
2198 ev->nfingers = ie->value != 0 ? 5 : ev->nfingers;
2199 break;
2200 case BTN_LEFT ... BTN_LEFT + 7:
2201 ev->buttons &= ~(1 << (ie->code - BTN_LEFT));
2202 ev->buttons |= ((!!ie->value) << (ie->code - BTN_LEFT));
2203 break;
2204 }
2205 break;
2206 }
2207
2208 if ( ie->type != EV_SYN ||
2209 (ie->code != SYN_REPORT && ie->code != SYN_DROPPED))
2210 return (0);
2211
2212 /*
2213 * assembly full package
2214 */
2215
2216 ietime.tv_sec = ie->time.tv_sec;
2217 ietime.tv_nsec = ie->time.tv_usec * 1000;
2218
2219 if (!tphw->cap_pressure && ev->st.id != 0)
2220 ev->st.p = MAX(tpinfo->min_pressure_hi, tpinfo->tap_threshold);
2221 if (tphw->cap_touch && ev->st.id == 0)
2222 ev->st.p = 0;
2223
2224 act->obutton = act->button;
2225 act->button = butmapev[ev->buttons & MOUSE_SYS_STDBUTTONS];
2226 act->button |= (ev->buttons & ~MOUSE_SYS_STDBUTTONS);
2227
2228 if (type == DEVICE_TYPE_TOUCHPAD) {
2229 if (debug > 1)
2230 debug("absolute data %d,%d,%d,%d", ev->st.x, ev->st.y,
2231 ev->st.p, ev->st.w);
2232 switch (r_gestures(tp, ev->st.x, ev->st.y, ev->st.p, ev->st.w,
2233 ev->nfingers, &ietime, act)) {
2234 case GEST_IGNORE:
2235 ev->dx = 0;
2236 ev->dy = 0;
2237 ev->dz = 0;
2238 ev->acc_dx = ev->acc_dy = 0;
2239 debug("gesture IGNORE");
2240 break;
2241 case GEST_ACCUMULATE: /* Revertable pointer movement. */
2242 ev->acc_dx += ev->dx;
2243 ev->acc_dy += ev->dy;
2244 debug("gesture ACCUMULATE %d,%d", ev->dx, ev->dy);
2245 ev->dx = 0;
2246 ev->dy = 0;
2247 break;
2248 case GEST_MOVE: /* Pointer movement. */
2249 ev->dx += ev->acc_dx;
2250 ev->dy += ev->acc_dy;
2251 ev->acc_dx = ev->acc_dy = 0;
2252 debug("gesture MOVE %d,%d", ev->dx, ev->dy);
2253 break;
2254 case GEST_VSCROLL: /* Vertical scrolling. */
2255 if (tpinfo->natural_scroll)
2256 ev->dz = -ev->dy;
2257 else
2258 ev->dz = ev->dy;
2259 ev->dx = -ev->acc_dx;
2260 ev->dy = -ev->acc_dy;
2261 ev->acc_dx = ev->acc_dy = 0;
2262 debug("gesture VSCROLL %d", ev->dz);
2263 break;
2264 case GEST_HSCROLL: /* Horizontal scrolling. */
2265 /*
2266 if (ev.dx != 0) {
2267 if (tpinfo->natural_scroll)
2268 act->button |= (ev.dx > 0)
2269 ? MOUSE_BUTTON6DOWN
2270 : MOUSE_BUTTON7DOWN;
2271 else
2272 act->button |= (ev.dx > 0)
2273 ? MOUSE_BUTTON7DOWN
2274 : MOUSE_BUTTON6DOWN;
2275 }
2276 */
2277 ev->dx = -ev->acc_dx;
2278 ev->dy = -ev->acc_dy;
2279 ev->acc_dx = ev->acc_dy = 0;
2280 debug("gesture HSCROLL %d", ev->dw);
2281 break;
2282 }
2283 }
2284
2285 debug("assembled full packet %d,%d,%d", ev->dx, ev->dy, ev->dz);
2286 act->dx = ev->dx;
2287 act->dy = ev->dy;
2288 act->dz = ev->dz;
2289 ev->dx = ev->dy = ev->dz = ev->dw = 0;
2290
2291 /* has something changed? */
2292 act->flags = ((act->dx || act->dy || act->dz) ? MOUSE_POSCHANGED : 0)
2293 | (act->obutton ^ act->button);
2294
2295 return (act->flags);
2296 }
2297
2298 static int
r_protocol_sysmouse(uint8_t * pBuf,mousestatus_t * act)2299 r_protocol_sysmouse(uint8_t *pBuf, mousestatus_t *act)
2300 {
2301 static int butmapmsc[8] = { /* sysmouse */
2302 0,
2303 MOUSE_BUTTON3DOWN,
2304 MOUSE_BUTTON2DOWN,
2305 MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN,
2306 MOUSE_BUTTON1DOWN,
2307 MOUSE_BUTTON1DOWN | MOUSE_BUTTON3DOWN,
2308 MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN,
2309 MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN | MOUSE_BUTTON3DOWN
2310 };
2311
2312 debug("%02x %02x %02x %02x %02x %02x %02x %02x", pBuf[0], pBuf[1],
2313 pBuf[2], pBuf[3], pBuf[4], pBuf[5], pBuf[6], pBuf[7]);
2314
2315 if ((pBuf[0] & MOUSE_SYS_SYNCMASK) != MOUSE_SYS_SYNC)
2316 return (0);
2317
2318 act->button = butmapmsc[(~pBuf[0]) & MOUSE_SYS_STDBUTTONS];
2319 act->dx = (signed char)(pBuf[1]) + (signed char)(pBuf[3]);
2320 act->dy = - ((signed char)(pBuf[2]) + (signed char)(pBuf[4]));
2321 act->dz = ((signed char)(pBuf[5] << 1) + (signed char)(pBuf[6] << 1)) >> 1;
2322 act->button |= ((~pBuf[7] & MOUSE_SYS_EXTBUTTONS) << 3);
2323
2324 /* has something changed? */
2325 act->flags = ((act->dx || act->dy || act->dz) ? MOUSE_POSCHANGED : 0)
2326 | (act->obutton ^ act->button);
2327
2328 return (act->flags);
2329 }
2330
2331 static void
r_vscroll_detect(struct rodent * r,struct scroll * sc,mousestatus_t * act)2332 r_vscroll_detect(struct rodent *r, struct scroll *sc, mousestatus_t *act)
2333 {
2334 mousestatus_t newaction;
2335
2336 /* Allow middle button drags to scroll up and down */
2337 if (act->button == MOUSE_BUTTON2DOWN) {
2338 if (sc->state == SCROLL_NOTSCROLLING) {
2339 sc->state = SCROLL_PREPARE;
2340 sc->movement = sc->hmovement = 0;
2341 debug("PREPARING TO SCROLL");
2342 }
2343 return;
2344 }
2345
2346 /* This isn't a middle button down... move along... */
2347 switch (sc->state) {
2348 case SCROLL_SCROLLING:
2349 /*
2350 * We were scrolling, someone let go of button 2.
2351 * Now turn autoscroll off.
2352 */
2353 sc->state = SCROLL_NOTSCROLLING;
2354 debug("DONE WITH SCROLLING / %d", sc->state);
2355 break;
2356 case SCROLL_PREPARE:
2357 newaction = *act;
2358
2359 /* We were preparing to scroll, but we never moved... */
2360 r_timestamp(act, &r->btstate, &r->e3b, &r->drift);
2361 r_statetrans(r, act, &newaction,
2362 A(newaction.button & MOUSE_BUTTON1DOWN,
2363 act->button & MOUSE_BUTTON3DOWN));
2364
2365 /* Send middle down */
2366 newaction.button = MOUSE_BUTTON2DOWN;
2367 r_click(&newaction, &r->btstate);
2368
2369 /* Send middle up */
2370 r_timestamp(&newaction, &r->btstate, &r->e3b, &r->drift);
2371 newaction.obutton = newaction.button;
2372 newaction.button = act->button;
2373 r_click(&newaction, &r->btstate);
2374 break;
2375 default:
2376 break;
2377 }
2378 }
2379
2380 static void
r_vscroll(struct scroll * sc,mousestatus_t * act)2381 r_vscroll(struct scroll *sc, mousestatus_t *act)
2382 {
2383 switch (sc->state) {
2384 case SCROLL_PREPARE:
2385 /* Middle button down, waiting for movement threshold */
2386 if (act->dy == 0 && act->dx == 0)
2387 break;
2388 if (sc->enable_vert) {
2389 sc->movement += act->dy;
2390 if ((u_int)abs(sc->movement) > sc->threshold)
2391 sc->state = SCROLL_SCROLLING;
2392 }
2393 if (sc->enable_hor) {
2394 sc->hmovement += act->dx;
2395 if ((u_int)abs(sc->hmovement) > sc->threshold)
2396 sc->state = SCROLL_SCROLLING;
2397 }
2398 if (sc->state == SCROLL_SCROLLING)
2399 sc->movement = sc->hmovement = 0;
2400 break;
2401 case SCROLL_SCROLLING:
2402 if (sc->enable_vert) {
2403 sc->movement += act->dy;
2404 debug("SCROLL: %d", sc->movement);
2405 if (sc->movement < -(int)sc->speed) {
2406 /* Scroll down */
2407 act->dz = -1;
2408 sc->movement = 0;
2409 }
2410 else if (sc->movement > (int)sc->speed) {
2411 /* Scroll up */
2412 act->dz = 1;
2413 sc->movement = 0;
2414 }
2415 }
2416 if (sc->enable_hor) {
2417 sc->hmovement += act->dx;
2418 debug("HORIZONTAL SCROLL: %d", sc->hmovement);
2419
2420 if (sc->hmovement < -(int)sc->speed) {
2421 act->dz = -2;
2422 sc->hmovement = 0;
2423 }
2424 else if (sc->hmovement > (int)sc->speed) {
2425 act->dz = 2;
2426 sc->hmovement = 0;
2427 }
2428 }
2429
2430 /* Don't move while scrolling */
2431 act->dx = act->dy = 0;
2432 break;
2433 default:
2434 break;
2435 }
2436 }
2437
2438 static bool
r_drift(struct drift * drift,mousestatus_t * act)2439 r_drift (struct drift *drift, mousestatus_t *act)
2440 {
2441 struct timespec tmp;
2442
2443 /* X or/and Y movement only - possibly drift */
2444 tssub(&drift->current_ts, &drift->last_activity, &tmp);
2445 if (tscmp(&tmp, &drift->after_ts, >)) {
2446 tssub(&drift->current_ts, &drift->since, &tmp);
2447 if (tscmp(&tmp, &drift->time_ts, <)) {
2448 drift->last.x += act->dx;
2449 drift->last.y += act->dy;
2450 } else {
2451 /* discard old accumulated steps (drift) */
2452 if (tscmp(&tmp, &drift->twotime_ts, >))
2453 drift->previous.x = drift->previous.y = 0;
2454 else
2455 drift->previous = drift->last;
2456 drift->last.x = act->dx;
2457 drift->last.y = act->dy;
2458 drift->since = drift->current_ts;
2459 }
2460 if ((u_int)abs(drift->last.x) + abs(drift->last.y) > drift->distance) {
2461 /* real movement, pass all accumulated steps */
2462 act->dx = drift->previous.x + drift->last.x;
2463 act->dy = drift->previous.y + drift->last.y;
2464 /* and reset accumulators */
2465 tsclr(&drift->since);
2466 drift->last.x = drift->last.y = 0;
2467 /* drift_previous will be cleared at next movement*/
2468 drift->last_activity = drift->current_ts;
2469 } else {
2470 return (true); /* don't pass current movement to
2471 * console driver */
2472 }
2473 }
2474 return (false);
2475 }
2476
2477 static int
r_statetrans(struct rodent * r,mousestatus_t * a1,mousestatus_t * a2,int trans)2478 r_statetrans(struct rodent *r, mousestatus_t *a1, mousestatus_t *a2, int trans)
2479 {
2480 struct e3bstate *e3b = &r->e3b;
2481 bool changed;
2482 int flags;
2483
2484 a2->dx = a1->dx;
2485 a2->dy = a1->dy;
2486 a2->dz = a1->dz;
2487 a2->obutton = a2->button;
2488 a2->button = a1->button;
2489 a2->flags = a1->flags;
2490 changed = false;
2491
2492 if (!e3b->enabled)
2493 return (false);
2494
2495 if (debug > 2)
2496 debug("state:%d, trans:%d -> state:%d",
2497 e3b->mouse_button_state, trans,
2498 states[e3b->mouse_button_state].s[trans]);
2499 /*
2500 * Avoid re-ordering button and movement events. While a button
2501 * event is deferred, throw away up to BUTTON2_MAXMOVE movement
2502 * events to allow for mouse jitter. If more movement events
2503 * occur, then complete the deferred button events immediately.
2504 */
2505 if ((a2->dx != 0 || a2->dy != 0) &&
2506 S_DELAYED(states[e3b->mouse_button_state].s[trans])) {
2507 if (++e3b->mouse_move_delayed > BUTTON2_MAXMOVE) {
2508 e3b->mouse_move_delayed = 0;
2509 e3b->mouse_button_state =
2510 states[e3b->mouse_button_state].s[A_TIMEOUT];
2511 changed = true;
2512 } else
2513 a2->dx = a2->dy = 0;
2514 } else
2515 e3b->mouse_move_delayed = 0;
2516 if (e3b->mouse_button_state != states[e3b->mouse_button_state].s[trans])
2517 changed = true;
2518 if (changed)
2519 clock_gettime(CLOCK_MONOTONIC_FAST,
2520 &e3b->mouse_button_state_ts);
2521 e3b->mouse_button_state = states[e3b->mouse_button_state].s[trans];
2522 a2->button &= ~(MOUSE_BUTTON1DOWN | MOUSE_BUTTON2DOWN |
2523 MOUSE_BUTTON3DOWN);
2524 a2->button &= states[e3b->mouse_button_state].mask;
2525 a2->button |= states[e3b->mouse_button_state].buttons;
2526 flags = a2->flags & MOUSE_POSCHANGED;
2527 flags |= a2->obutton ^ a2->button;
2528 if (flags & MOUSE_BUTTON2DOWN) {
2529 a2->flags = flags & MOUSE_BUTTON2DOWN;
2530 r_timestamp(a2, &r->btstate, e3b, &r->drift);
2531 }
2532 a2->flags = flags;
2533
2534 return (changed);
2535 }
2536
2537 static char *
skipspace(char * s)2538 skipspace(char *s)
2539 {
2540 while(isspace(*s))
2541 ++s;
2542 return (s);
2543 }
2544
2545 static bool
r_installmap(char * arg,struct btstate * bt)2546 r_installmap(char *arg, struct btstate *bt)
2547 {
2548 u_long pbutton;
2549 u_long lbutton;
2550 char *s;
2551
2552 while (*arg) {
2553 arg = skipspace(arg);
2554 s = arg;
2555 while (isdigit(*arg))
2556 ++arg;
2557 arg = skipspace(arg);
2558 if ((arg <= s) || (*arg != '='))
2559 return (false);
2560 lbutton = strtoul(s, NULL, 10);
2561
2562 arg = skipspace(++arg);
2563 s = arg;
2564 while (isdigit(*arg))
2565 ++arg;
2566 if ((arg <= s) || (!isspace(*arg) && (*arg != '\0')))
2567 return (false);
2568 pbutton = strtoul(s, NULL, 10);
2569
2570 if (lbutton == 0 || lbutton > MOUSE_MAXBUTTON)
2571 return (false);
2572 if (pbutton == 0 || pbutton > MOUSE_MAXBUTTON)
2573 return (false);
2574 bt->p2l[pbutton - 1] = 1 << (lbutton - 1);
2575 bt->mstate[lbutton - 1] = &bt->bstate[pbutton - 1];
2576 }
2577
2578 return (true);
2579 }
2580
2581 static char *
r_installzmap(char ** argv,int argc,int * idx,struct btstate * bt)2582 r_installzmap(char **argv, int argc, int* idx, struct btstate *bt)
2583 {
2584 char *arg, *errstr;
2585 u_long i, j;
2586
2587 arg = argv[*idx];
2588 ++*idx;
2589 if (strcmp(arg, "x") == 0) {
2590 bt->zmap[0] = MOUSE_XAXIS;
2591 return (NULL);
2592 }
2593 if (strcmp(arg, "y") == 0) {
2594 bt->zmap[0] = MOUSE_YAXIS;
2595 return (NULL);
2596 }
2597 i = strtoul(arg, NULL, 10);
2598 /*
2599 * Use button i for negative Z axis movement and
2600 * button (i + 1) for positive Z axis movement.
2601 */
2602 if (i == 0 || i >= MOUSE_MAXBUTTON) {
2603 asprintf(&errstr, "invalid argument `%s'", arg);
2604 return (errstr);
2605 }
2606 bt->zmap[0] = i;
2607 bt->zmap[1] = i + 1;
2608 debug("optind: %d, optarg: '%s'", *idx, arg);
2609 for (j = 1; j < ZMAP_MAXBUTTON; ++j) {
2610 if ((*idx >= argc) || !isdigit(*argv[*idx]))
2611 break;
2612 i = strtoul(argv[*idx], NULL, 10);
2613 if (i == 0 || i >= MOUSE_MAXBUTTON) {
2614 asprintf(&errstr, "invalid argument `%s'", argv[*idx]);
2615 return (errstr);
2616 }
2617 bt->zmap[j] = i;
2618 ++*idx;
2619 }
2620 if ((bt->zmap[2] != 0) && (bt->zmap[3] == 0))
2621 bt->zmap[3] = bt->zmap[2] + 1;
2622
2623 return (NULL);
2624 }
2625
2626 static void
r_map(mousestatus_t * act1,mousestatus_t * act2,struct btstate * bt)2627 r_map(mousestatus_t *act1, mousestatus_t *act2, struct btstate *bt)
2628 {
2629 int pb;
2630 int pbuttons;
2631 int lbuttons;
2632
2633 pbuttons = act1->button;
2634 lbuttons = 0;
2635
2636 act2->obutton = act2->button;
2637 if (pbuttons & bt->wmode) {
2638 pbuttons &= ~bt->wmode;
2639 act1->dz = act1->dy;
2640 act1->dx = 0;
2641 act1->dy = 0;
2642 }
2643 act2->dx = act1->dx;
2644 act2->dy = act1->dy;
2645 act2->dz = act1->dz;
2646
2647 switch (bt->zmap[0]) {
2648 case 0: /* do nothing */
2649 break;
2650 case MOUSE_XAXIS:
2651 if (act1->dz != 0) {
2652 act2->dx = act1->dz;
2653 act2->dz = 0;
2654 }
2655 break;
2656 case MOUSE_YAXIS:
2657 if (act1->dz != 0) {
2658 act2->dy = act1->dz;
2659 act2->dz = 0;
2660 }
2661 break;
2662 default: /* buttons */
2663 pbuttons &= ~(bt->zmap[0] | bt->zmap[1]
2664 | bt->zmap[2] | bt->zmap[3]);
2665 if ((act1->dz < -1) && bt->zmap[2]) {
2666 pbuttons |= bt->zmap[2];
2667 bt->zstate[2].count = 1;
2668 } else if (act1->dz < 0) {
2669 pbuttons |= bt->zmap[0];
2670 bt->zstate[0].count = 1;
2671 } else if ((act1->dz > 1) && bt->zmap[3]) {
2672 pbuttons |= bt->zmap[3];
2673 bt->zstate[3].count = 1;
2674 } else if (act1->dz > 0) {
2675 pbuttons |= bt->zmap[1];
2676 bt->zstate[1].count = 1;
2677 }
2678 act2->dz = 0;
2679 break;
2680 }
2681
2682 for (pb = 0; (pb < MOUSE_MAXBUTTON) && (pbuttons != 0); ++pb) {
2683 lbuttons |= (pbuttons & 1) ? bt->p2l[pb] : 0;
2684 pbuttons >>= 1;
2685 }
2686 act2->button = lbuttons;
2687
2688 act2->flags =
2689 ((act2->dx || act2->dy || act2->dz) ? MOUSE_POSCHANGED : 0)
2690 | (act2->obutton ^ act2->button);
2691 }
2692
2693 static void
r_timestamp(mousestatus_t * act,struct btstate * bt,struct e3bstate * e3b,struct drift * drift)2694 r_timestamp(mousestatus_t *act, struct btstate *bt, struct e3bstate *e3b,
2695 struct drift *drift)
2696 {
2697 struct timespec ts;
2698 struct timespec ts1;
2699 struct timespec ts2;
2700 int button;
2701 int mask;
2702 int i;
2703
2704 mask = act->flags & MOUSE_BUTTONS;
2705 #if 0
2706 if (mask == 0)
2707 return;
2708 #endif
2709
2710 clock_gettime(CLOCK_MONOTONIC_FAST, &ts1);
2711 drift->current_ts = ts1;
2712
2713 /* double click threshold */
2714 ts = tssubms(&ts1, bt->clickthreshold);
2715 debug("ts: %jd %ld", (intmax_t)ts.tv_sec, ts.tv_nsec);
2716
2717 /* 3 button emulation timeout */
2718 ts2 = tssubms(&ts1, e3b->button2timeout);
2719
2720 button = MOUSE_BUTTON1DOWN;
2721 for (i = 0; (i < MOUSE_MAXBUTTON) && (mask != 0); ++i) {
2722 if (mask & 1) {
2723 if (act->button & button) {
2724 /* the button is down */
2725 debug(" : %jd %ld",
2726 (intmax_t)bt->bstate[i].ts.tv_sec,
2727 bt->bstate[i].ts.tv_nsec);
2728 if (tscmp(&ts, &bt->bstate[i].ts, >)) {
2729 bt->bstate[i].count = 1;
2730 } else {
2731 ++bt->bstate[i].count;
2732 }
2733 bt->bstate[i].ts = ts1;
2734 } else {
2735 /* the button is up */
2736 bt->bstate[i].ts = ts1;
2737 }
2738 } else {
2739 if (act->button & button) {
2740 /* the button has been down */
2741 if (tscmp(&ts2, &bt->bstate[i].ts, >)) {
2742 bt->bstate[i].count = 1;
2743 bt->bstate[i].ts = ts1;
2744 act->flags |= button;
2745 debug("button %d timeout", i + 1);
2746 }
2747 } else {
2748 /* the button has been up */
2749 }
2750 }
2751 button <<= 1;
2752 mask >>= 1;
2753 }
2754 }
2755
2756 static bool
r_timeout(struct e3bstate * e3b)2757 r_timeout(struct e3bstate *e3b)
2758 {
2759 struct timespec ts;
2760 struct timespec ts1;
2761
2762 if (states[e3b->mouse_button_state].timeout)
2763 return (true);
2764 clock_gettime(CLOCK_MONOTONIC_FAST, &ts1);
2765 ts = tssubms(&ts1, e3b->button2timeout);
2766 return (tscmp(&ts, &e3b->mouse_button_state_ts, >));
2767 }
2768
2769 static void
r_move(mousestatus_t * act,struct accel * acc)2770 r_move(mousestatus_t *act, struct accel *acc)
2771 {
2772 struct mouse_info mouse;
2773
2774 bzero(&mouse, sizeof(mouse));
2775 if (acc->is_exponential) {
2776 expoacc(acc, act->dx, act->dy, act->dz,
2777 &mouse.u.data.x, &mouse.u.data.y, &mouse.u.data.z);
2778 } else {
2779 linacc(acc, act->dx, act->dy, act->dz,
2780 &mouse.u.data.x, &mouse.u.data.y, &mouse.u.data.z);
2781 }
2782 mouse.operation = MOUSE_MOTION_EVENT;
2783 mouse.u.data.buttons = act->button;
2784 if (debug < 2 && !paused)
2785 ioctl(cfd, CONS_MOUSECTL, &mouse);
2786 }
2787
2788 static void
r_click(mousestatus_t * act,struct btstate * bt)2789 r_click(mousestatus_t *act, struct btstate *bt)
2790 {
2791 struct mouse_info mouse;
2792 int button;
2793 int mask;
2794 int i;
2795
2796 mask = act->flags & MOUSE_BUTTONS;
2797 if (mask == 0)
2798 return;
2799
2800 button = MOUSE_BUTTON1DOWN;
2801 for (i = 0; (i < MOUSE_MAXBUTTON) && (mask != 0); ++i) {
2802 if (mask & 1) {
2803 debug("mstate[%d]->count:%d", i, bt->mstate[i]->count);
2804 if (act->button & button) {
2805 /* the button is down */
2806 mouse.u.event.value = bt->mstate[i]->count;
2807 } else {
2808 /* the button is up */
2809 mouse.u.event.value = 0;
2810 }
2811 mouse.operation = MOUSE_BUTTON_EVENT;
2812 mouse.u.event.id = button;
2813 if (debug < 2 && !paused)
2814 ioctl(cfd, CONS_MOUSECTL, &mouse);
2815 debug("button %d count %d", i + 1,
2816 mouse.u.event.value);
2817 }
2818 button <<= 1;
2819 mask >>= 1;
2820 }
2821 }
2822
2823 static enum gesture
r_gestures(struct tpad * tp,int x0,int y0,u_int z,int w,int nfingers,struct timespec * time,mousestatus_t * ms)2824 r_gestures(struct tpad *tp, int x0, int y0, u_int z, int w, int nfingers,
2825 struct timespec *time, mousestatus_t *ms)
2826 {
2827 struct tpstate *gest = &tp->gest;
2828 const struct tpcaps *tphw = &tp->hw;
2829 const struct tpinfo *tpinfo = &tp->info;
2830 int tap_timeout = tpinfo->tap_timeout;
2831
2832 /*
2833 * Check pressure to detect a real wanted action on the
2834 * touchpad.
2835 */
2836 if (z >= tpinfo->min_pressure_hi ||
2837 (gest->fingerdown && z >= tpinfo->min_pressure_lo)) {
2838 /* XXX Verify values? */
2839 bool two_finger_scroll = tpinfo->two_finger_scroll;
2840 bool three_finger_drag = tpinfo->three_finger_drag;
2841 int max_width = tpinfo->max_width;
2842 u_int max_pressure = tpinfo->max_pressure;
2843 int margin_top = tpinfo->margin_top;
2844 int margin_right = tpinfo->margin_right;
2845 int margin_bottom = tpinfo->margin_bottom;
2846 int margin_left = tpinfo->margin_left;
2847 int vscroll_hor_area = tpinfo->vscroll_hor_area * tphw->res_x;
2848 int vscroll_ver_area = tpinfo->vscroll_ver_area * tphw->res_y;;
2849
2850 int max_x = tphw->max_x;
2851 int max_y = tphw->max_y;
2852 int min_x = tphw->min_x;
2853 int min_y = tphw->min_y;
2854
2855 int dx, dy;
2856 int start_x, start_y;
2857 int tap_max_delta_x, tap_max_delta_y;
2858 int prev_nfingers;
2859
2860 /* Palm detection. */
2861 if (nfingers == 1 &&
2862 ((tphw->cap_width && w > max_width) ||
2863 (tphw->cap_pressure && z > max_pressure))) {
2864 /*
2865 * We consider the packet irrelevant for the current
2866 * action when:
2867 * - there is a single active touch
2868 * - the width isn't comprised in:
2869 * [0; max_width]
2870 * - the pressure isn't comprised in:
2871 * [min_pressure; max_pressure]
2872 *
2873 * Note that this doesn't terminate the current action.
2874 */
2875 debug("palm detected! (%d)", z);
2876 return(GEST_IGNORE);
2877 }
2878
2879 /*
2880 * Limit the coordinates to the specified margins because
2881 * this area isn't very reliable.
2882 */
2883 if (margin_left != 0 && x0 <= min_x + margin_left)
2884 x0 = min_x + margin_left;
2885 else if (margin_right != 0 && x0 >= max_x - margin_right)
2886 x0 = max_x - margin_right;
2887 if (margin_bottom != 0 && y0 <= min_y + margin_bottom)
2888 y0 = min_y + margin_bottom;
2889 else if (margin_top != 0 && y0 >= max_y - margin_top)
2890 y0 = max_y - margin_top;
2891
2892 debug("packet: [%d, %d], %d, %d", x0, y0, z, w);
2893
2894 /*
2895 * If the action is just beginning, init the structure and
2896 * compute tap timeout.
2897 */
2898 if (!gest->fingerdown) {
2899 debug("----");
2900
2901 /* Reset pressure peak. */
2902 gest->zmax = 0;
2903
2904 /* Reset fingers count. */
2905 gest->fingers_nb = 0;
2906
2907 /* Reset virtual scrolling state. */
2908 gest->in_vscroll = 0;
2909
2910 /* Compute tap timeout. */
2911 if (tap_timeout != 0)
2912 gest->taptimeout = tsaddms(time, tap_timeout);
2913 else
2914 tsclr(&gest->taptimeout);
2915
2916 gest->fingerdown = true;
2917
2918 gest->start_x = x0;
2919 gest->start_y = y0;
2920 }
2921
2922 prev_nfingers = gest->prev_nfingers;
2923
2924 gest->prev_x = x0;
2925 gest->prev_y = y0;
2926 gest->prev_nfingers = nfingers;
2927
2928 start_x = gest->start_x;
2929 start_y = gest->start_y;
2930
2931 /* Process ClickPad softbuttons */
2932 if (tphw->is_clickpad && ms->button & MOUSE_BUTTON1DOWN) {
2933 int y_ok, center_bt, center_x, right_bt, right_x;
2934 y_ok = tpinfo->softbuttons_y < 0
2935 ? start_y < min_y - tpinfo->softbuttons_y
2936 : start_y > max_y - tpinfo->softbuttons_y;
2937
2938 center_bt = MOUSE_BUTTON2DOWN;
2939 center_x = min_x + tpinfo->softbutton2_x;
2940 right_bt = MOUSE_BUTTON3DOWN;
2941 right_x = min_x + tpinfo->softbutton3_x;
2942
2943 if (center_x > 0 && right_x > 0 && center_x > right_x) {
2944 center_bt = MOUSE_BUTTON3DOWN;
2945 center_x = min_x + tpinfo->softbutton3_x;
2946 right_bt = MOUSE_BUTTON2DOWN;
2947 right_x = min_x + tpinfo->softbutton2_x;
2948 }
2949
2950 if (right_x > 0 && start_x > right_x && y_ok)
2951 ms->button = (ms->button &
2952 ~MOUSE_BUTTON1DOWN) | right_bt;
2953 else if (center_x > 0 && start_x > center_x && y_ok)
2954 ms->button = (ms->button &
2955 ~MOUSE_BUTTON1DOWN) | center_bt;
2956 }
2957
2958 /* If in tap-hold or three fingers, add the recorded button. */
2959 if (gest->in_taphold || (nfingers == 3 && three_finger_drag))
2960 ms->button |= gest->tap_button;
2961
2962 /*
2963 * For tap, we keep the maximum number of fingers and the
2964 * pressure peak.
2965 */
2966 gest->fingers_nb = MAX(nfingers, gest->fingers_nb);
2967 gest->zmax = MAX(z, gest->zmax);
2968
2969 dx = abs(x0 - start_x);
2970 dy = abs(y0 - start_y);
2971
2972 /*
2973 * A scrolling action must not conflict with a tap action.
2974 * Here are the conditions to consider a scrolling action:
2975 * - the action in a configurable area
2976 * - one of the following:
2977 * . the distance between the last packet and the
2978 * first should be above a configurable minimum
2979 * . tap timed out
2980 */
2981 if (!gest->in_taphold && !ms->button &&
2982 (!gest->in_vscroll || two_finger_scroll) &&
2983 (tscmp(time, &gest->taptimeout, >) ||
2984 ((gest->fingers_nb == 2 || !two_finger_scroll) &&
2985 (dx >= tpinfo->vscroll_min_delta * tphw->res_x ||
2986 dy >= tpinfo->vscroll_min_delta * tphw->res_y)))) {
2987 /*
2988 * Handle two finger scrolling.
2989 * Note that we don't rely on fingers_nb
2990 * as that keeps the maximum number of fingers.
2991 */
2992 if (two_finger_scroll) {
2993 if (nfingers == 2) {
2994 gest->in_vscroll += dy ? 2 : 0;
2995 gest->in_vscroll += dx ? 1 : 0;
2996 }
2997 } else {
2998 /* Check for horizontal scrolling. */
2999 if ((vscroll_hor_area > 0 &&
3000 start_y <= min_y + vscroll_hor_area) ||
3001 (vscroll_hor_area < 0 &&
3002 start_y >= max_y + vscroll_hor_area))
3003 gest->in_vscroll += 2;
3004
3005 /* Check for vertical scrolling. */
3006 if ((vscroll_ver_area > 0 &&
3007 start_x <= min_x + vscroll_ver_area) ||
3008 (vscroll_ver_area < 0 &&
3009 start_x >= max_x + vscroll_ver_area))
3010 gest->in_vscroll += 1;
3011 }
3012 /* Avoid conflicts if area overlaps. */
3013 if (gest->in_vscroll >= 3)
3014 gest->in_vscroll = (dx > dy) ? 2 : 1;
3015 }
3016 /*
3017 * Reset two finger scrolling when the number of fingers
3018 * is different from two or any button is pressed.
3019 */
3020 if (two_finger_scroll && gest->in_vscroll != 0 &&
3021 (nfingers != 2 || ms->button))
3022 gest->in_vscroll = 0;
3023
3024 debug("virtual scrolling: %s "
3025 "(direction=%d, dx=%d, dy=%d, fingers=%d)",
3026 gest->in_vscroll != 0 ? "YES" : "NO",
3027 gest->in_vscroll, dx, dy, gest->fingers_nb);
3028
3029 /* Workaround cursor jump on finger set changes */
3030 if (prev_nfingers != nfingers)
3031 return (GEST_IGNORE);
3032
3033 switch (gest->in_vscroll) {
3034 case 1:
3035 return (GEST_VSCROLL);
3036 case 2:
3037 return (GEST_HSCROLL);
3038 default:
3039 /* NO-OP */;
3040 }
3041
3042 /* Max delta is disabled for multi-fingers tap. */
3043 if (gest->fingers_nb == 1 &&
3044 tscmp(time, &gest->taptimeout, <=)) {
3045 tap_max_delta_x = tpinfo->tap_max_delta * tphw->res_x;
3046 tap_max_delta_y = tpinfo->tap_max_delta * tphw->res_y;
3047
3048 debug("dx=%d, dy=%d, deltax=%d, deltay=%d",
3049 dx, dy, tap_max_delta_x, tap_max_delta_y);
3050 if (dx > tap_max_delta_x || dy > tap_max_delta_y) {
3051 debug("not a tap");
3052 tsclr(&gest->taptimeout);
3053 }
3054 }
3055
3056 if (tscmp(time, &gest->taptimeout, <=))
3057 return (gest->fingers_nb > 1 ?
3058 GEST_IGNORE : GEST_ACCUMULATE);
3059 else
3060 return (GEST_MOVE);
3061 }
3062
3063 /*
3064 * Handle a case when clickpad pressure drops before than
3065 * button up event when surface is released after click.
3066 * It interferes with softbuttons.
3067 */
3068 if (tphw->is_clickpad && tpinfo->softbuttons_y != 0)
3069 ms->button &= ~MOUSE_BUTTON1DOWN;
3070
3071 gest->prev_nfingers = 0;
3072
3073 if (gest->fingerdown) {
3074 /*
3075 * An action is currently taking place but the pressure
3076 * dropped under the minimum, putting an end to it.
3077 */
3078
3079 gest->fingerdown = false;
3080
3081 /* Check for tap. */
3082 debug("zmax=%d fingers=%d", gest->zmax, gest->fingers_nb);
3083 if (!gest->in_vscroll && gest->zmax >= tpinfo->tap_threshold &&
3084 tscmp(time, &gest->taptimeout, <=)) {
3085 /*
3086 * We have a tap if:
3087 * - the maximum pressure went over tap_threshold
3088 * - the action ended before tap_timeout
3089 *
3090 * To handle tap-hold, we must delay any button push to
3091 * the next action.
3092 */
3093 if (gest->in_taphold) {
3094 /*
3095 * This is the second and last tap of a
3096 * double tap action, not a tap-hold.
3097 */
3098 gest->in_taphold = false;
3099
3100 /*
3101 * For double-tap to work:
3102 * - no button press is emitted (to
3103 * simulate a button release)
3104 * - PSM_FLAGS_FINGERDOWN is set to
3105 * force the next packet to emit a
3106 * button press)
3107 */
3108 debug("button RELEASE: %d", gest->tap_button);
3109 gest->fingerdown = true;
3110
3111 /* Schedule button press on next event */
3112 gest->idletimeout = 0;
3113 } else {
3114 /*
3115 * This is the first tap: we set the
3116 * tap-hold state and notify the button
3117 * down event.
3118 */
3119 gest->in_taphold = true;
3120 gest->idletimeout = tpinfo->taphold_timeout;
3121 gest->taptimeout = tsaddms(time, tap_timeout);
3122
3123 switch (gest->fingers_nb) {
3124 case 3:
3125 gest->tap_button =
3126 MOUSE_BUTTON2DOWN;
3127 break;
3128 case 2:
3129 gest->tap_button =
3130 MOUSE_BUTTON3DOWN;
3131 break;
3132 default:
3133 gest->tap_button =
3134 MOUSE_BUTTON1DOWN;
3135 }
3136 debug("button PRESS: %d", gest->tap_button);
3137 ms->button |= gest->tap_button;
3138 }
3139 } else {
3140 /*
3141 * Not enough pressure or timeout: reset
3142 * tap-hold state.
3143 */
3144 if (gest->in_taphold) {
3145 debug("button RELEASE: %d", gest->tap_button);
3146 gest->in_taphold = false;
3147 } else {
3148 debug("not a tap-hold");
3149 }
3150 }
3151 } else if (!gest->fingerdown && gest->in_taphold) {
3152 /*
3153 * For a tap-hold to work, the button must remain down at
3154 * least until timeout (where the in_taphold flags will be
3155 * cleared) or during the next action.
3156 */
3157 if (tscmp(time, &gest->taptimeout, <=)) {
3158 ms->button |= gest->tap_button;
3159 } else {
3160 debug("button RELEASE: %d", gest->tap_button);
3161 gest->in_taphold = false;
3162 }
3163 }
3164
3165 return (GEST_IGNORE);
3166 }
3167