evdev: use a different filter for low resolution touchpad on the Lenovo X230
[platform/upstream/libinput.git] / src / evdev.c
1 /*
2  * Copyright © 2010 Intel Corporation
3  * Copyright © 2013 Jonas Ådahl
4  *
5  * Permission to use, copy, modify, distribute, and sell this software and
6  * its documentation for any purpose is hereby granted without fee, provided
7  * that the above copyright notice appear in all copies and that both that
8  * copyright notice and this permission notice appear in supporting
9  * documentation, and that the name of the copyright holders not be used in
10  * advertising or publicity pertaining to distribution of the software
11  * without specific, written prior permission.  The copyright holders make
12  * no representations about the suitability of this software for any
13  * purpose.  It is provided "as is" without express or implied warranty.
14  *
15  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
16  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
17  * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
18  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
19  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
20  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  */
23
24 #include "config.h"
25
26 #include <errno.h>
27 #include <stdbool.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include "linux/input.h"
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <mtdev-plumbing.h>
34 #include <assert.h>
35 #include <time.h>
36 #include <math.h>
37
38 #include "libinput.h"
39 #include "evdev.h"
40 #include "filter.h"
41 #include "libinput-private.h"
42
43 #define DEFAULT_WHEEL_CLICK_ANGLE 15
44 #define DEFAULT_MIDDLE_BUTTON_SCROLL_TIMEOUT 200
45
46 enum evdev_key_type {
47         EVDEV_KEY_TYPE_NONE,
48         EVDEV_KEY_TYPE_KEY,
49         EVDEV_KEY_TYPE_BUTTON,
50 };
51
52 enum evdev_device_udev_tags {
53         EVDEV_UDEV_TAG_INPUT = (1 << 0),
54         EVDEV_UDEV_TAG_KEYBOARD = (1 << 1),
55         EVDEV_UDEV_TAG_MOUSE = (1 << 2),
56         EVDEV_UDEV_TAG_TOUCHPAD = (1 << 3),
57         EVDEV_UDEV_TAG_TOUCHSCREEN = (1 << 4),
58         EVDEV_UDEV_TAG_TABLET = (1 << 5),
59         EVDEV_UDEV_TAG_JOYSTICK = (1 << 6),
60         EVDEV_UDEV_TAG_ACCELEROMETER = (1 << 7),
61         EVDEV_UDEV_TAG_BUTTONSET = (1 << 8),
62 };
63
64 struct evdev_udev_tag_match {
65         const char *name;
66         enum evdev_device_udev_tags tag;
67 };
68
69 static const struct evdev_udev_tag_match evdev_udev_tag_matches[] = {
70         {"ID_INPUT",                    EVDEV_UDEV_TAG_INPUT},
71         {"ID_INPUT_KEYBOARD",           EVDEV_UDEV_TAG_KEYBOARD},
72         {"ID_INPUT_KEY",                EVDEV_UDEV_TAG_KEYBOARD},
73         {"ID_INPUT_MOUSE",              EVDEV_UDEV_TAG_MOUSE},
74         {"ID_INPUT_TOUCHPAD",           EVDEV_UDEV_TAG_TOUCHPAD},
75         {"ID_INPUT_TOUCHSCREEN",        EVDEV_UDEV_TAG_TOUCHSCREEN},
76         {"ID_INPUT_TABLET",             EVDEV_UDEV_TAG_TABLET},
77         {"ID_INPUT_TABLET_PAD",         EVDEV_UDEV_TAG_BUTTONSET},
78         {"ID_INPUT_JOYSTICK",           EVDEV_UDEV_TAG_JOYSTICK},
79         {"ID_INPUT_ACCELEROMETER",      EVDEV_UDEV_TAG_ACCELEROMETER},
80
81         /* sentinel value */
82         { 0 },
83 };
84
85 static void
86 hw_set_key_down(struct evdev_device *device, int code, int pressed)
87 {
88         long_set_bit_state(device->hw_key_mask, code, pressed);
89 }
90
91 static int
92 hw_is_key_down(struct evdev_device *device, int code)
93 {
94         return long_bit_is_set(device->hw_key_mask, code);
95 }
96
97 static int
98 get_key_down_count(struct evdev_device *device, int code)
99 {
100         return device->key_count[code];
101 }
102
103 static int
104 update_key_down_count(struct evdev_device *device, int code, int pressed)
105 {
106         int key_count;
107         assert(code >= 0 && code < KEY_CNT);
108
109         if (pressed) {
110                 key_count = ++device->key_count[code];
111         } else {
112                 assert(device->key_count[code] > 0);
113                 key_count = --device->key_count[code];
114         }
115
116         if (key_count > 32) {
117                 log_bug_libinput(device->base.seat->libinput,
118                                  "Key count for %s reached abnormal values\n",
119                                  libevdev_event_code_get_name(EV_KEY, code));
120         }
121
122         return key_count;
123 }
124
125 void
126 evdev_keyboard_notify_key(struct evdev_device *device,
127                           uint32_t time,
128                           int key,
129                           enum libinput_key_state state)
130 {
131         int down_count;
132
133         down_count = update_key_down_count(device, key, state);
134
135         if ((state == LIBINPUT_KEY_STATE_PRESSED && down_count == 1) ||
136             (state == LIBINPUT_KEY_STATE_RELEASED && down_count == 0))
137                 keyboard_notify_key(&device->base, time, key, state);
138 }
139
140 void
141 evdev_pointer_notify_physical_button(struct evdev_device *device,
142                                      uint32_t time,
143                                      int button,
144                                      enum libinput_button_state state)
145 {
146         if (evdev_middlebutton_filter_button(device,
147                                              time,
148                                              button,
149                                              state))
150                         return;
151
152         evdev_pointer_notify_button(device, time, button, state);
153 }
154
155 void
156 evdev_pointer_notify_button(struct evdev_device *device,
157                             uint32_t time,
158                             int button,
159                             enum libinput_button_state state)
160 {
161         int down_count;
162
163         down_count = update_key_down_count(device, button, state);
164
165         if ((state == LIBINPUT_BUTTON_STATE_PRESSED && down_count == 1) ||
166             (state == LIBINPUT_BUTTON_STATE_RELEASED && down_count == 0)) {
167                 pointer_notify_button(&device->base, time, button, state);
168
169                 if (state == LIBINPUT_BUTTON_STATE_RELEASED) {
170                         if (device->left_handed.change_to_enabled)
171                                 device->left_handed.change_to_enabled(device);
172
173                         if (device->scroll.change_scroll_method)
174                                 device->scroll.change_scroll_method(device);
175                 }
176         }
177
178 }
179
180 void
181 evdev_device_led_update(struct evdev_device *device, enum libinput_led leds)
182 {
183         static const struct {
184                 enum libinput_led weston;
185                 int evdev;
186         } map[] = {
187                 { LIBINPUT_LED_NUM_LOCK, LED_NUML },
188                 { LIBINPUT_LED_CAPS_LOCK, LED_CAPSL },
189                 { LIBINPUT_LED_SCROLL_LOCK, LED_SCROLLL },
190         };
191         struct input_event ev[ARRAY_LENGTH(map) + 1];
192         unsigned int i;
193
194         if (!(device->seat_caps & EVDEV_DEVICE_KEYBOARD))
195                 return;
196
197         memset(ev, 0, sizeof(ev));
198         for (i = 0; i < ARRAY_LENGTH(map); i++) {
199                 ev[i].type = EV_LED;
200                 ev[i].code = map[i].evdev;
201                 ev[i].value = !!(leds & map[i].weston);
202         }
203         ev[i].type = EV_SYN;
204         ev[i].code = SYN_REPORT;
205
206         i = write(device->fd, ev, sizeof ev);
207         (void)i; /* no, we really don't care about the return value */
208 }
209
210 static void
211 transform_absolute(struct evdev_device *device,
212                    struct device_coords *point)
213 {
214         if (!device->abs.apply_calibration)
215                 return;
216
217         matrix_mult_vec(&device->abs.calibration, &point->x, &point->y);
218 }
219
220 static inline double
221 scale_axis(const struct input_absinfo *absinfo, double val, double to_range)
222 {
223         return (val - absinfo->minimum) * to_range /
224                 (absinfo->maximum - absinfo->minimum + 1);
225 }
226
227 double
228 evdev_device_transform_x(struct evdev_device *device,
229                          double x,
230                          uint32_t width)
231 {
232         return scale_axis(device->abs.absinfo_x, x, width);
233 }
234
235 double
236 evdev_device_transform_y(struct evdev_device *device,
237                          double y,
238                          uint32_t height)
239 {
240         return scale_axis(device->abs.absinfo_y, y, height);
241 }
242
243 static inline void
244 normalize_delta(struct evdev_device *device,
245                 const struct device_coords *delta,
246                 struct normalized_coords *normalized)
247 {
248         normalized->x = delta->x * DEFAULT_MOUSE_DPI / (double)device->dpi;
249         normalized->y = delta->y * DEFAULT_MOUSE_DPI / (double)device->dpi;
250 }
251
252 static void
253 evdev_flush_pending_event(struct evdev_device *device, uint64_t time)
254 {
255         struct libinput *libinput = device->base.seat->libinput;
256         int slot;
257         int seat_slot;
258         struct libinput_device *base = &device->base;
259         struct libinput_seat *seat = base->seat;
260         struct normalized_coords accel, unaccel;
261         struct device_coords point;
262
263         slot = device->mt.slot;
264
265         switch (device->pending_event) {
266         case EVDEV_NONE:
267                 return;
268         case EVDEV_RELATIVE_MOTION:
269                 normalize_delta(device, &device->rel, &unaccel);
270                 device->rel.x = 0;
271                 device->rel.y = 0;
272
273                 /* Use unaccelerated deltas for pointing stick scroll */
274                 if (device->scroll.method == LIBINPUT_CONFIG_SCROLL_ON_BUTTON_DOWN &&
275                     hw_is_key_down(device, device->scroll.button)) {
276                         if (device->scroll.button_scroll_active)
277                                 evdev_post_scroll(device, time,
278                                                   LIBINPUT_POINTER_AXIS_SOURCE_CONTINUOUS,
279                                                   &unaccel);
280                         break;
281                 }
282
283                 /* Apply pointer acceleration. */
284                 accel = filter_dispatch(device->pointer.filter, &unaccel, device, time);
285
286                 if (normalized_is_zero(accel) && normalized_is_zero(unaccel))
287                         break;
288
289                 pointer_notify_motion(base, time, &accel, &unaccel);
290                 break;
291         case EVDEV_ABSOLUTE_MT_DOWN:
292                 if (!(device->seat_caps & EVDEV_DEVICE_TOUCH))
293                         break;
294
295                 if (device->mt.slots[slot].seat_slot != -1) {
296                         log_bug_kernel(libinput,
297                                        "%s: Driver sent multiple touch down for the "
298                                        "same slot",
299                                        udev_device_get_devnode(device->udev_device));
300                         break;
301                 }
302
303                 seat_slot = ffs(~seat->slot_map) - 1;
304                 device->mt.slots[slot].seat_slot = seat_slot;
305
306                 if (seat_slot == -1)
307                         break;
308
309                 seat->slot_map |= 1 << seat_slot;
310                 point = device->mt.slots[slot].point;
311                 transform_absolute(device, &point);
312
313                 touch_notify_touch_down(base, time, slot, seat_slot,
314                                         &point);
315                 break;
316         case EVDEV_ABSOLUTE_MT_MOTION:
317                 if (!(device->seat_caps & EVDEV_DEVICE_TOUCH))
318                         break;
319
320                 seat_slot = device->mt.slots[slot].seat_slot;
321                 point = device->mt.slots[slot].point;
322
323                 if (seat_slot == -1)
324                         break;
325
326                 transform_absolute(device, &point);
327                 touch_notify_touch_motion(base, time, slot, seat_slot,
328                                           &point);
329                 break;
330         case EVDEV_ABSOLUTE_MT_UP:
331                 if (!(device->seat_caps & EVDEV_DEVICE_TOUCH))
332                         break;
333
334                 seat_slot = device->mt.slots[slot].seat_slot;
335                 device->mt.slots[slot].seat_slot = -1;
336
337                 if (seat_slot == -1)
338                         break;
339
340                 seat->slot_map &= ~(1 << seat_slot);
341
342                 touch_notify_touch_up(base, time, slot, seat_slot);
343                 break;
344         case EVDEV_ABSOLUTE_TOUCH_DOWN:
345                 if (!(device->seat_caps & EVDEV_DEVICE_TOUCH))
346                         break;
347
348                 if (device->abs.seat_slot != -1) {
349                         log_bug_kernel(libinput,
350                                        "%s: Driver sent multiple touch down for the "
351                                        "same slot",
352                                        udev_device_get_devnode(device->udev_device));
353                         break;
354                 }
355
356                 seat_slot = ffs(~seat->slot_map) - 1;
357                 device->abs.seat_slot = seat_slot;
358
359                 if (seat_slot == -1)
360                         break;
361
362                 seat->slot_map |= 1 << seat_slot;
363
364                 point = device->abs.point;
365                 transform_absolute(device, &point);
366
367                 touch_notify_touch_down(base, time, -1, seat_slot, &point);
368                 break;
369         case EVDEV_ABSOLUTE_MOTION:
370                 point = device->abs.point;
371                 transform_absolute(device, &point);
372
373                 if (device->seat_caps & EVDEV_DEVICE_TOUCH) {
374                         seat_slot = device->abs.seat_slot;
375
376                         if (seat_slot == -1)
377                                 break;
378
379                         touch_notify_touch_motion(base, time, -1, seat_slot,
380                                                   &point);
381                 } else if (device->seat_caps & EVDEV_DEVICE_POINTER) {
382                         pointer_notify_motion_absolute(base, time, &point);
383                 }
384                 break;
385         case EVDEV_ABSOLUTE_TOUCH_UP:
386                 if (!(device->seat_caps & EVDEV_DEVICE_TOUCH))
387                         break;
388
389                 seat_slot = device->abs.seat_slot;
390                 device->abs.seat_slot = -1;
391
392                 if (seat_slot == -1)
393                         break;
394
395                 seat->slot_map &= ~(1 << seat_slot);
396
397                 touch_notify_touch_up(base, time, -1, seat_slot);
398                 break;
399         default:
400                 assert(0 && "Unknown pending event type");
401                 break;
402         }
403
404         device->pending_event = EVDEV_NONE;
405 }
406
407 static enum evdev_key_type
408 get_key_type(uint16_t code)
409 {
410         if (code == BTN_TOUCH)
411                 return EVDEV_KEY_TYPE_NONE;
412
413         if (code >= KEY_ESC && code <= KEY_MICMUTE)
414                 return EVDEV_KEY_TYPE_KEY;
415         if (code >= BTN_MISC && code <= BTN_GEAR_UP)
416                 return EVDEV_KEY_TYPE_BUTTON;
417         if (code >= KEY_OK && code <= KEY_LIGHTS_TOGGLE)
418                 return EVDEV_KEY_TYPE_KEY;
419         if (code >= BTN_DPAD_UP && code <= BTN_TRIGGER_HAPPY40)
420                 return EVDEV_KEY_TYPE_BUTTON;
421         return EVDEV_KEY_TYPE_NONE;
422 }
423
424 static void
425 evdev_button_scroll_timeout(uint64_t time, void *data)
426 {
427         struct evdev_device *device = data;
428
429         device->scroll.button_scroll_active = true;
430 }
431
432 static void
433 evdev_button_scroll_button(struct evdev_device *device,
434                            uint64_t time, int is_press)
435 {
436         if (is_press) {
437                 libinput_timer_set(&device->scroll.timer,
438                                 time + DEFAULT_MIDDLE_BUTTON_SCROLL_TIMEOUT);
439         } else {
440                 libinput_timer_cancel(&device->scroll.timer);
441                 if (device->scroll.button_scroll_active) {
442                         evdev_stop_scroll(device, time,
443                                           LIBINPUT_POINTER_AXIS_SOURCE_CONTINUOUS);
444                         device->scroll.button_scroll_active = false;
445                 } else {
446                         /* If the button is released quickly enough emit the
447                          * button press/release events. */
448                         evdev_pointer_notify_physical_button(device, time,
449                                         device->scroll.button,
450                                         LIBINPUT_BUTTON_STATE_PRESSED);
451                         evdev_pointer_notify_physical_button(device, time,
452                                         device->scroll.button,
453                                         LIBINPUT_BUTTON_STATE_RELEASED);
454                 }
455         }
456 }
457
458 static void
459 evdev_process_touch_button(struct evdev_device *device,
460                            uint64_t time, int value)
461 {
462         if (device->pending_event != EVDEV_NONE &&
463             device->pending_event != EVDEV_ABSOLUTE_MOTION)
464                 evdev_flush_pending_event(device, time);
465
466         device->pending_event = (value ?
467                                  EVDEV_ABSOLUTE_TOUCH_DOWN :
468                                  EVDEV_ABSOLUTE_TOUCH_UP);
469 }
470
471 static inline void
472 evdev_process_key(struct evdev_device *device,
473                   struct input_event *e, uint64_t time)
474 {
475         enum evdev_key_type type;
476
477         /* ignore kernel key repeat */
478         if (e->value == 2)
479                 return;
480
481         if (e->code == BTN_TOUCH) {
482                 if (!device->is_mt)
483                         evdev_process_touch_button(device, time, e->value);
484                 return;
485         }
486
487         evdev_flush_pending_event(device, time);
488
489         type = get_key_type(e->code);
490
491         /* Ignore key release events from the kernel for keys that libinput
492          * never got a pressed event for. */
493         if (e->value == 0) {
494                 switch (type) {
495                 case EVDEV_KEY_TYPE_NONE:
496                         break;
497                 case EVDEV_KEY_TYPE_KEY:
498                 case EVDEV_KEY_TYPE_BUTTON:
499                         if (!hw_is_key_down(device, e->code))
500                                 return;
501                 }
502         }
503
504         hw_set_key_down(device, e->code, e->value);
505
506         switch (type) {
507         case EVDEV_KEY_TYPE_NONE:
508                 break;
509         case EVDEV_KEY_TYPE_KEY:
510                 evdev_keyboard_notify_key(
511                         device,
512                         time,
513                         e->code,
514                         e->value ? LIBINPUT_KEY_STATE_PRESSED :
515                                    LIBINPUT_KEY_STATE_RELEASED);
516                 break;
517         case EVDEV_KEY_TYPE_BUTTON:
518                 if (device->scroll.method == LIBINPUT_CONFIG_SCROLL_ON_BUTTON_DOWN &&
519                     e->code == device->scroll.button) {
520                         evdev_button_scroll_button(device, time, e->value);
521                         break;
522                 }
523                 evdev_pointer_notify_physical_button(
524                         device,
525                         time,
526                         evdev_to_left_handed(device, e->code),
527                         e->value ? LIBINPUT_BUTTON_STATE_PRESSED :
528                                    LIBINPUT_BUTTON_STATE_RELEASED);
529                 break;
530         }
531 }
532
533 static void
534 evdev_process_touch(struct evdev_device *device,
535                     struct input_event *e,
536                     uint64_t time)
537 {
538         switch (e->code) {
539         case ABS_MT_SLOT:
540                 if ((size_t)e->value >= device->mt.slots_len) {
541                         log_bug_libinput(device->base.seat->libinput,
542                                          "%s exceeds slots (%d of %d)\n",
543                                          device->devname,
544                                          e->value,
545                                          device->mt.slots_len);
546                         e->value = device->mt.slots_len - 1;
547                 }
548                 evdev_flush_pending_event(device, time);
549                 device->mt.slot = e->value;
550                 break;
551         case ABS_MT_TRACKING_ID:
552                 if (device->pending_event != EVDEV_NONE &&
553                     device->pending_event != EVDEV_ABSOLUTE_MT_MOTION)
554                         evdev_flush_pending_event(device, time);
555                 if (e->value >= 0)
556                         device->pending_event = EVDEV_ABSOLUTE_MT_DOWN;
557                 else
558                         device->pending_event = EVDEV_ABSOLUTE_MT_UP;
559                 break;
560         case ABS_MT_POSITION_X:
561                 device->mt.slots[device->mt.slot].point.x = e->value;
562                 if (device->pending_event == EVDEV_NONE)
563                         device->pending_event = EVDEV_ABSOLUTE_MT_MOTION;
564                 break;
565         case ABS_MT_POSITION_Y:
566                 device->mt.slots[device->mt.slot].point.y = e->value;
567                 if (device->pending_event == EVDEV_NONE)
568                         device->pending_event = EVDEV_ABSOLUTE_MT_MOTION;
569                 break;
570         }
571 }
572
573 static inline void
574 evdev_process_absolute_motion(struct evdev_device *device,
575                               struct input_event *e)
576 {
577         switch (e->code) {
578         case ABS_X:
579                 device->abs.point.x = e->value;
580                 if (device->pending_event == EVDEV_NONE)
581                         device->pending_event = EVDEV_ABSOLUTE_MOTION;
582                 break;
583         case ABS_Y:
584                 device->abs.point.y = e->value;
585                 if (device->pending_event == EVDEV_NONE)
586                         device->pending_event = EVDEV_ABSOLUTE_MOTION;
587                 break;
588         }
589 }
590
591 static void
592 evdev_notify_axis(struct evdev_device *device,
593                   uint64_t time,
594                   uint32_t axes,
595                   enum libinput_pointer_axis_source source,
596                   const struct normalized_coords *delta_in,
597                   const struct discrete_coords *discrete_in)
598 {
599         struct normalized_coords delta = *delta_in;
600         struct discrete_coords discrete = *discrete_in;
601
602         if (device->scroll.natural_scrolling_enabled) {
603                 delta.x *= -1;
604                 delta.y *= -1;
605                 discrete.x *= -1;
606                 discrete.y *= -1;
607         }
608
609         pointer_notify_axis(&device->base,
610                             time,
611                             axes,
612                             source,
613                             &delta,
614                             &discrete);
615 }
616
617 static inline void
618 evdev_process_relative(struct evdev_device *device,
619                        struct input_event *e, uint64_t time)
620 {
621         struct normalized_coords wheel_degrees = { 0.0, 0.0 };
622         struct discrete_coords discrete = { 0.0, 0.0 };
623
624         switch (e->code) {
625         case REL_X:
626                 if (device->pending_event != EVDEV_RELATIVE_MOTION)
627                         evdev_flush_pending_event(device, time);
628                 device->rel.x += e->value;
629                 device->pending_event = EVDEV_RELATIVE_MOTION;
630                 break;
631         case REL_Y:
632                 if (device->pending_event != EVDEV_RELATIVE_MOTION)
633                         evdev_flush_pending_event(device, time);
634                 device->rel.y += e->value;
635                 device->pending_event = EVDEV_RELATIVE_MOTION;
636                 break;
637         case REL_WHEEL:
638                 evdev_flush_pending_event(device, time);
639                 wheel_degrees.y = -1 * e->value *
640                                         device->scroll.wheel_click_angle;
641                 discrete.y = -1 * e->value;
642                 evdev_notify_axis(
643                         device,
644                         time,
645                         AS_MASK(LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL),
646                         LIBINPUT_POINTER_AXIS_SOURCE_WHEEL,
647                         &wheel_degrees,
648                         &discrete);
649                 break;
650         case REL_HWHEEL:
651                 evdev_flush_pending_event(device, time);
652                 wheel_degrees.x = e->value * device->scroll.wheel_click_angle;
653                 discrete.x = e->value;
654                 evdev_notify_axis(
655                         device,
656                         time,
657                         AS_MASK(LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL),
658                         LIBINPUT_POINTER_AXIS_SOURCE_WHEEL,
659                         &wheel_degrees,
660                         &discrete);
661                 break;
662         }
663 }
664
665 static inline void
666 evdev_process_absolute(struct evdev_device *device,
667                        struct input_event *e,
668                        uint64_t time)
669 {
670         if (device->is_mt) {
671                 evdev_process_touch(device, e, time);
672         } else {
673                 evdev_process_absolute_motion(device, e);
674         }
675 }
676
677 static inline bool
678 evdev_any_button_down(struct evdev_device *device)
679 {
680         unsigned int button;
681
682         for (button = BTN_LEFT; button < BTN_JOYSTICK; button++) {
683                 if (libevdev_has_event_code(device->evdev, EV_KEY, button) &&
684                     hw_is_key_down(device, button))
685                         return true;
686         }
687         return false;
688 }
689
690 static inline bool
691 evdev_need_touch_frame(struct evdev_device *device)
692 {
693         if (!(device->seat_caps & EVDEV_DEVICE_TOUCH))
694                 return false;
695
696         switch (device->pending_event) {
697         case EVDEV_NONE:
698         case EVDEV_RELATIVE_MOTION:
699                 break;
700         case EVDEV_ABSOLUTE_MT_DOWN:
701         case EVDEV_ABSOLUTE_MT_MOTION:
702         case EVDEV_ABSOLUTE_MT_UP:
703         case EVDEV_ABSOLUTE_TOUCH_DOWN:
704         case EVDEV_ABSOLUTE_TOUCH_UP:
705         case EVDEV_ABSOLUTE_MOTION:
706                 return true;
707         }
708
709         return false;
710 }
711
712 static void
713 evdev_tag_external_mouse(struct evdev_device *device,
714                          struct udev_device *udev_device)
715 {
716         int bustype;
717
718         bustype = libevdev_get_id_bustype(device->evdev);
719         if (bustype == BUS_USB || bustype == BUS_BLUETOOTH) {
720                 if (device->seat_caps & EVDEV_DEVICE_POINTER)
721                         device->tags |= EVDEV_TAG_EXTERNAL_MOUSE;
722         }
723 }
724
725 static void
726 evdev_tag_trackpoint(struct evdev_device *device,
727                      struct udev_device *udev_device)
728 {
729         if (libevdev_has_property(device->evdev, INPUT_PROP_POINTING_STICK))
730                 device->tags |= EVDEV_TAG_TRACKPOINT;
731 }
732
733 static void
734 fallback_process(struct evdev_dispatch *dispatch,
735                  struct evdev_device *device,
736                  struct input_event *event,
737                  uint64_t time)
738 {
739         bool need_frame = false;
740
741         switch (event->type) {
742         case EV_REL:
743                 evdev_process_relative(device, event, time);
744                 break;
745         case EV_ABS:
746                 evdev_process_absolute(device, event, time);
747                 break;
748         case EV_KEY:
749                 evdev_process_key(device, event, time);
750                 break;
751         case EV_SYN:
752                 need_frame = evdev_need_touch_frame(device);
753                 evdev_flush_pending_event(device, time);
754                 if (need_frame)
755                         touch_notify_frame(&device->base, time);
756                 break;
757         }
758 }
759
760 static void
761 fallback_destroy(struct evdev_dispatch *dispatch)
762 {
763         free(dispatch);
764 }
765
766 static void
767 fallback_tag_device(struct evdev_device *device,
768                     struct udev_device *udev_device)
769 {
770         evdev_tag_external_mouse(device, udev_device);
771         evdev_tag_trackpoint(device, udev_device);
772 }
773
774 static int
775 evdev_calibration_has_matrix(struct libinput_device *libinput_device)
776 {
777         struct evdev_device *device = (struct evdev_device*)libinput_device;
778
779         return device->abs.absinfo_x && device->abs.absinfo_y;
780 }
781
782 static enum libinput_config_status
783 evdev_calibration_set_matrix(struct libinput_device *libinput_device,
784                              const float matrix[6])
785 {
786         struct evdev_device *device = (struct evdev_device*)libinput_device;
787
788         evdev_device_calibrate(device, matrix);
789
790         return LIBINPUT_CONFIG_STATUS_SUCCESS;
791 }
792
793 static int
794 evdev_calibration_get_matrix(struct libinput_device *libinput_device,
795                              float matrix[6])
796 {
797         struct evdev_device *device = (struct evdev_device*)libinput_device;
798
799         matrix_to_farray6(&device->abs.usermatrix, matrix);
800
801         return !matrix_is_identity(&device->abs.usermatrix);
802 }
803
804 static int
805 evdev_calibration_get_default_matrix(struct libinput_device *libinput_device,
806                                      float matrix[6])
807 {
808         struct evdev_device *device = (struct evdev_device*)libinput_device;
809
810         matrix_to_farray6(&device->abs.default_calibration, matrix);
811
812         return !matrix_is_identity(&device->abs.default_calibration);
813 }
814
815 struct evdev_dispatch_interface fallback_interface = {
816         fallback_process,
817         NULL, /* remove */
818         fallback_destroy,
819         NULL, /* device_added */
820         NULL, /* device_removed */
821         NULL, /* device_suspended */
822         NULL, /* device_resumed */
823         fallback_tag_device,
824 };
825
826 static uint32_t
827 evdev_sendevents_get_modes(struct libinput_device *device)
828 {
829         return LIBINPUT_CONFIG_SEND_EVENTS_DISABLED;
830 }
831
832 static enum libinput_config_status
833 evdev_sendevents_set_mode(struct libinput_device *device,
834                           enum libinput_config_send_events_mode mode)
835 {
836         struct evdev_device *evdev = (struct evdev_device*)device;
837         struct evdev_dispatch *dispatch = evdev->dispatch;
838
839         if (mode == dispatch->sendevents.current_mode)
840                 return LIBINPUT_CONFIG_STATUS_SUCCESS;
841
842         switch(mode) {
843         case LIBINPUT_CONFIG_SEND_EVENTS_ENABLED:
844                 evdev_device_resume(evdev);
845                 break;
846         case LIBINPUT_CONFIG_SEND_EVENTS_DISABLED:
847                 evdev_device_suspend(evdev);
848                 break;
849         default: /* no support for combined modes yet */
850                 return LIBINPUT_CONFIG_STATUS_UNSUPPORTED;
851         }
852
853         dispatch->sendevents.current_mode = mode;
854
855         return LIBINPUT_CONFIG_STATUS_SUCCESS;
856 }
857
858 static enum libinput_config_send_events_mode
859 evdev_sendevents_get_mode(struct libinput_device *device)
860 {
861         struct evdev_device *evdev = (struct evdev_device*)device;
862         struct evdev_dispatch *dispatch = evdev->dispatch;
863
864         return dispatch->sendevents.current_mode;
865 }
866
867 static enum libinput_config_send_events_mode
868 evdev_sendevents_get_default_mode(struct libinput_device *device)
869 {
870         return LIBINPUT_CONFIG_SEND_EVENTS_ENABLED;
871 }
872
873 static int
874 evdev_left_handed_has(struct libinput_device *device)
875 {
876         /* This is only hooked up when we have left-handed configuration, so we
877          * can hardcode 1 here */
878         return 1;
879 }
880
881 static void
882 evdev_change_to_left_handed(struct evdev_device *device)
883 {
884         if (device->left_handed.want_enabled == device->left_handed.enabled)
885                 return;
886
887         if (evdev_any_button_down(device))
888                 return;
889
890         device->left_handed.enabled = device->left_handed.want_enabled;
891 }
892
893 static enum libinput_config_status
894 evdev_left_handed_set(struct libinput_device *device, int left_handed)
895 {
896         struct evdev_device *evdev_device = (struct evdev_device *)device;
897
898         evdev_device->left_handed.want_enabled = left_handed ? true : false;
899
900         evdev_device->left_handed.change_to_enabled(evdev_device);
901
902         return LIBINPUT_CONFIG_STATUS_SUCCESS;
903 }
904
905 static int
906 evdev_left_handed_get(struct libinput_device *device)
907 {
908         struct evdev_device *evdev_device = (struct evdev_device *)device;
909
910         /* return the wanted configuration, even if it hasn't taken
911          * effect yet! */
912         return evdev_device->left_handed.want_enabled;
913 }
914
915 static int
916 evdev_left_handed_get_default(struct libinput_device *device)
917 {
918         return 0;
919 }
920
921 int
922 evdev_init_left_handed(struct evdev_device *device,
923                        void (*change_to_left_handed)(struct evdev_device *))
924 {
925         device->left_handed.config.has = evdev_left_handed_has;
926         device->left_handed.config.set = evdev_left_handed_set;
927         device->left_handed.config.get = evdev_left_handed_get;
928         device->left_handed.config.get_default = evdev_left_handed_get_default;
929         device->base.config.left_handed = &device->left_handed.config;
930         device->left_handed.enabled = false;
931         device->left_handed.want_enabled = false;
932         device->left_handed.change_to_enabled = change_to_left_handed;
933
934         return 0;
935 }
936
937 static uint32_t
938 evdev_scroll_get_methods(struct libinput_device *device)
939 {
940         return LIBINPUT_CONFIG_SCROLL_ON_BUTTON_DOWN;
941 }
942
943 static void
944 evdev_change_scroll_method(struct evdev_device *device)
945 {
946         if (device->scroll.want_method == device->scroll.method &&
947             device->scroll.want_button == device->scroll.button)
948                 return;
949
950         if (evdev_any_button_down(device))
951                 return;
952
953         device->scroll.method = device->scroll.want_method;
954         device->scroll.button = device->scroll.want_button;
955 }
956
957 static enum libinput_config_status
958 evdev_scroll_set_method(struct libinput_device *device,
959                         enum libinput_config_scroll_method method)
960 {
961         struct evdev_device *evdev = (struct evdev_device*)device;
962
963         evdev->scroll.want_method = method;
964         evdev->scroll.change_scroll_method(evdev);
965
966         return LIBINPUT_CONFIG_STATUS_SUCCESS;
967 }
968
969 static enum libinput_config_scroll_method
970 evdev_scroll_get_method(struct libinput_device *device)
971 {
972         struct evdev_device *evdev = (struct evdev_device *)device;
973
974         /* return the wanted configuration, even if it hasn't taken
975          * effect yet! */
976         return evdev->scroll.want_method;
977 }
978
979 static enum libinput_config_scroll_method
980 evdev_scroll_get_default_method(struct libinput_device *device)
981 {
982         struct evdev_device *evdev = (struct evdev_device *)device;
983
984         if (libevdev_has_property(evdev->evdev, INPUT_PROP_POINTING_STICK))
985                 return LIBINPUT_CONFIG_SCROLL_ON_BUTTON_DOWN;
986         else
987                 return LIBINPUT_CONFIG_SCROLL_NO_SCROLL;
988 }
989
990 static enum libinput_config_status
991 evdev_scroll_set_button(struct libinput_device *device,
992                         uint32_t button)
993 {
994         struct evdev_device *evdev = (struct evdev_device*)device;
995
996         evdev->scroll.want_button = button;
997         evdev->scroll.change_scroll_method(evdev);
998
999         return LIBINPUT_CONFIG_STATUS_SUCCESS;
1000 }
1001
1002 static uint32_t
1003 evdev_scroll_get_button(struct libinput_device *device)
1004 {
1005         struct evdev_device *evdev = (struct evdev_device *)device;
1006
1007         /* return the wanted configuration, even if it hasn't taken
1008          * effect yet! */
1009         return evdev->scroll.want_button;
1010 }
1011
1012 static uint32_t
1013 evdev_scroll_get_default_button(struct libinput_device *device)
1014 {
1015         struct evdev_device *evdev = (struct evdev_device *)device;
1016
1017         if (libevdev_has_property(evdev->evdev, INPUT_PROP_POINTING_STICK))
1018                 return BTN_MIDDLE;
1019         else
1020                 return 0;
1021 }
1022
1023 static int
1024 evdev_init_button_scroll(struct evdev_device *device,
1025                          void (*change_scroll_method)(struct evdev_device *))
1026 {
1027         libinput_timer_init(&device->scroll.timer, device->base.seat->libinput,
1028                             evdev_button_scroll_timeout, device);
1029         device->scroll.config.get_methods = evdev_scroll_get_methods;
1030         device->scroll.config.set_method = evdev_scroll_set_method;
1031         device->scroll.config.get_method = evdev_scroll_get_method;
1032         device->scroll.config.get_default_method = evdev_scroll_get_default_method;
1033         device->scroll.config.set_button = evdev_scroll_set_button;
1034         device->scroll.config.get_button = evdev_scroll_get_button;
1035         device->scroll.config.get_default_button = evdev_scroll_get_default_button;
1036         device->base.config.scroll_method = &device->scroll.config;
1037         device->scroll.method = evdev_scroll_get_default_method((struct libinput_device *)device);
1038         device->scroll.want_method = device->scroll.method;
1039         device->scroll.button = evdev_scroll_get_default_button((struct libinput_device *)device);
1040         device->scroll.want_button = device->scroll.button;
1041         device->scroll.change_scroll_method = change_scroll_method;
1042
1043         return 0;
1044 }
1045
1046 static void
1047 evdev_init_calibration(struct evdev_device *device,
1048                        struct evdev_dispatch *dispatch)
1049 {
1050         device->base.config.calibration = &dispatch->calibration;
1051
1052         dispatch->calibration.has_matrix = evdev_calibration_has_matrix;
1053         dispatch->calibration.set_matrix = evdev_calibration_set_matrix;
1054         dispatch->calibration.get_matrix = evdev_calibration_get_matrix;
1055         dispatch->calibration.get_default_matrix = evdev_calibration_get_default_matrix;
1056 }
1057
1058 static void
1059 evdev_init_sendevents(struct evdev_device *device,
1060                       struct evdev_dispatch *dispatch)
1061 {
1062         device->base.config.sendevents = &dispatch->sendevents.config;
1063
1064         dispatch->sendevents.current_mode = LIBINPUT_CONFIG_SEND_EVENTS_ENABLED;
1065         dispatch->sendevents.config.get_modes = evdev_sendevents_get_modes;
1066         dispatch->sendevents.config.set_mode = evdev_sendevents_set_mode;
1067         dispatch->sendevents.config.get_mode = evdev_sendevents_get_mode;
1068         dispatch->sendevents.config.get_default_mode = evdev_sendevents_get_default_mode;
1069 }
1070
1071 static int
1072 evdev_scroll_config_natural_has(struct libinput_device *device)
1073 {
1074         return 1;
1075 }
1076
1077 static enum libinput_config_status
1078 evdev_scroll_config_natural_set(struct libinput_device *device,
1079                                 int enabled)
1080 {
1081         struct evdev_device *dev = (struct evdev_device *)device;
1082
1083         dev->scroll.natural_scrolling_enabled = enabled ? true : false;
1084
1085         return LIBINPUT_CONFIG_STATUS_SUCCESS;
1086 }
1087
1088 static int
1089 evdev_scroll_config_natural_get(struct libinput_device *device)
1090 {
1091         struct evdev_device *dev = (struct evdev_device *)device;
1092
1093         return dev->scroll.natural_scrolling_enabled ? 1 : 0;
1094 }
1095
1096 static int
1097 evdev_scroll_config_natural_get_default(struct libinput_device *device)
1098 {
1099         /* could enable this on Apple touchpads. could do that, could
1100          * very well do that... */
1101         return 0;
1102 }
1103
1104 void
1105 evdev_init_natural_scroll(struct evdev_device *device)
1106 {
1107         device->scroll.config_natural.has = evdev_scroll_config_natural_has;
1108         device->scroll.config_natural.set_enabled = evdev_scroll_config_natural_set;
1109         device->scroll.config_natural.get_enabled = evdev_scroll_config_natural_get;
1110         device->scroll.config_natural.get_default_enabled = evdev_scroll_config_natural_get_default;
1111         device->scroll.natural_scrolling_enabled = false;
1112         device->base.config.natural_scroll = &device->scroll.config_natural;
1113 }
1114
1115 static struct evdev_dispatch *
1116 fallback_dispatch_create(struct libinput_device *device)
1117 {
1118         struct evdev_dispatch *dispatch = zalloc(sizeof *dispatch);
1119         struct evdev_device *evdev_device = (struct evdev_device *)device;
1120
1121         if (dispatch == NULL)
1122                 return NULL;
1123
1124         dispatch->interface = &fallback_interface;
1125
1126         if (evdev_device->left_handed.want_enabled &&
1127             evdev_init_left_handed(evdev_device,
1128                                    evdev_change_to_left_handed) == -1) {
1129                 free(dispatch);
1130                 return NULL;
1131         }
1132
1133         if (evdev_device->scroll.want_button &&
1134             evdev_init_button_scroll(evdev_device,
1135                                      evdev_change_scroll_method) == -1) {
1136                 free(dispatch);
1137                 return NULL;
1138         }
1139
1140         if (evdev_device->scroll.natural_scrolling_enabled)
1141                 evdev_init_natural_scroll(evdev_device);
1142
1143         evdev_init_calibration(evdev_device, dispatch);
1144         evdev_init_sendevents(evdev_device, dispatch);
1145
1146         /* BTN_MIDDLE is set on mice even when it's not present. So
1147          * we can only use the absense of BTN_MIDDLE to mean something, i.e.
1148          * we enable it by default on anything that only has L&R.
1149          * If we have L&R and no middle, we don't expose it as config
1150          * option */
1151         if (libevdev_has_event_code(evdev_device->evdev, EV_KEY, BTN_LEFT) &&
1152             libevdev_has_event_code(evdev_device->evdev, EV_KEY, BTN_RIGHT)) {
1153                 bool has_middle = libevdev_has_event_code(evdev_device->evdev,
1154                                                           EV_KEY,
1155                                                           BTN_MIDDLE);
1156                 bool want_config = has_middle;
1157                 bool enable_by_default = !has_middle;
1158
1159                 evdev_init_middlebutton(evdev_device,
1160                                         enable_by_default,
1161                                         want_config);
1162         }
1163
1164         return dispatch;
1165 }
1166
1167 static inline void
1168 evdev_process_event(struct evdev_device *device, struct input_event *e)
1169 {
1170         struct evdev_dispatch *dispatch = device->dispatch;
1171         uint64_t time = e->time.tv_sec * 1000ULL + e->time.tv_usec / 1000;
1172
1173 #if 0
1174         if (libevdev_event_is_code(e, EV_SYN, SYN_REPORT))
1175                 log_debug(device->base.seat->libinput,
1176                           "-------------- EV_SYN ------------\n");
1177         else
1178                 log_debug(device->base.seat->libinput,
1179                           "%-7s %-16s %-20s %4d\n",
1180                           evdev_device_get_sysname(device),
1181                           libevdev_event_type_get_name(e->type),
1182                           libevdev_event_code_get_name(e->type, e->code),
1183                           e->value);
1184 #endif
1185
1186         dispatch->interface->process(dispatch, device, e, time);
1187 }
1188
1189 static inline void
1190 evdev_device_dispatch_one(struct evdev_device *device,
1191                           struct input_event *ev)
1192 {
1193         if (!device->mtdev) {
1194                 evdev_process_event(device, ev);
1195         } else {
1196                 mtdev_put_event(device->mtdev, ev);
1197                 if (libevdev_event_is_code(ev, EV_SYN, SYN_REPORT)) {
1198                         while (!mtdev_empty(device->mtdev)) {
1199                                 struct input_event e;
1200                                 mtdev_get_event(device->mtdev, &e);
1201                                 evdev_process_event(device, &e);
1202                         }
1203                 }
1204         }
1205 }
1206
1207 static int
1208 evdev_sync_device(struct evdev_device *device)
1209 {
1210         struct input_event ev;
1211         int rc;
1212
1213         do {
1214                 rc = libevdev_next_event(device->evdev,
1215                                          LIBEVDEV_READ_FLAG_SYNC, &ev);
1216                 if (rc < 0)
1217                         break;
1218                 evdev_device_dispatch_one(device, &ev);
1219         } while (rc == LIBEVDEV_READ_STATUS_SYNC);
1220
1221         return rc == -EAGAIN ? 0 : rc;
1222 }
1223
1224 static void
1225 evdev_device_dispatch(void *data)
1226 {
1227         struct evdev_device *device = data;
1228         struct libinput *libinput = device->base.seat->libinput;
1229         struct input_event ev;
1230         int rc;
1231
1232         /* If the compositor is repainting, this function is called only once
1233          * per frame and we have to process all the events available on the
1234          * fd, otherwise there will be input lag. */
1235         do {
1236                 rc = libevdev_next_event(device->evdev,
1237                                          LIBEVDEV_READ_FLAG_NORMAL, &ev);
1238                 if (rc == LIBEVDEV_READ_STATUS_SYNC) {
1239                         switch (ratelimit_test(&device->syn_drop_limit)) {
1240                         case RATELIMIT_PASS:
1241                                 log_info(libinput, "SYN_DROPPED event from "
1242                                          "\"%s\" - some input events have "
1243                                          "been lost.\n", device->devname);
1244                                 break;
1245                         case RATELIMIT_THRESHOLD:
1246                                 log_info(libinput, "SYN_DROPPED flood "
1247                                          "from \"%s\"\n",
1248                                          device->devname);
1249                                 break;
1250                         case RATELIMIT_EXCEEDED:
1251                                 break;
1252                         }
1253
1254                         /* send one more sync event so we handle all
1255                            currently pending events before we sync up
1256                            to the current state */
1257                         ev.code = SYN_REPORT;
1258                         evdev_device_dispatch_one(device, &ev);
1259
1260                         rc = evdev_sync_device(device);
1261                         if (rc == 0)
1262                                 rc = LIBEVDEV_READ_STATUS_SUCCESS;
1263                 } else if (rc == LIBEVDEV_READ_STATUS_SUCCESS) {
1264                         evdev_device_dispatch_one(device, &ev);
1265                 }
1266         } while (rc == LIBEVDEV_READ_STATUS_SUCCESS);
1267
1268         if (rc != -EAGAIN && rc != -EINTR) {
1269                 libinput_remove_source(libinput, device->source);
1270                 device->source = NULL;
1271         }
1272 }
1273
1274 static int
1275 evdev_accel_config_available(struct libinput_device *device)
1276 {
1277         /* this function is only called if we set up ptraccel, so we can
1278            reply with a resounding "Yes" */
1279         return 1;
1280 }
1281
1282 static enum libinput_config_status
1283 evdev_accel_config_set_speed(struct libinput_device *device, double speed)
1284 {
1285         struct evdev_device *dev = (struct evdev_device *)device;
1286
1287         if (!filter_set_speed(dev->pointer.filter, speed))
1288                 return LIBINPUT_CONFIG_STATUS_INVALID;
1289
1290         return LIBINPUT_CONFIG_STATUS_SUCCESS;
1291 }
1292
1293 static double
1294 evdev_accel_config_get_speed(struct libinput_device *device)
1295 {
1296         struct evdev_device *dev = (struct evdev_device *)device;
1297
1298         return filter_get_speed(dev->pointer.filter);
1299 }
1300
1301 static double
1302 evdev_accel_config_get_default_speed(struct libinput_device *device)
1303 {
1304         return 0.0;
1305 }
1306
1307 int
1308 evdev_device_init_pointer_acceleration(struct evdev_device *device,
1309                                        accel_profile_func_t profile)
1310 {
1311         device->pointer.filter = create_pointer_accelerator_filter(profile);
1312         if (!device->pointer.filter)
1313                 return -1;
1314
1315         device->pointer.config.available = evdev_accel_config_available;
1316         device->pointer.config.set_speed = evdev_accel_config_set_speed;
1317         device->pointer.config.get_speed = evdev_accel_config_get_speed;
1318         device->pointer.config.get_default_speed = evdev_accel_config_get_default_speed;
1319         device->base.config.accel = &device->pointer.config;
1320
1321         evdev_accel_config_set_speed(&device->base,
1322                      evdev_accel_config_get_default_speed(&device->base));
1323
1324         return 0;
1325 }
1326
1327 static inline int
1328 evdev_need_mtdev(struct evdev_device *device)
1329 {
1330         struct libevdev *evdev = device->evdev;
1331
1332         return (libevdev_has_event_code(evdev, EV_ABS, ABS_MT_POSITION_X) &&
1333                 libevdev_has_event_code(evdev, EV_ABS, ABS_MT_POSITION_Y) &&
1334                 !libevdev_has_event_code(evdev, EV_ABS, ABS_MT_SLOT));
1335 }
1336
1337 static void
1338 evdev_tag_device(struct evdev_device *device)
1339 {
1340         if (device->dispatch->interface->tag_device)
1341                 device->dispatch->interface->tag_device(device,
1342                                                         device->udev_device);
1343 }
1344
1345 static inline int
1346 evdev_read_wheel_click_prop(struct evdev_device *device)
1347 {
1348         struct libinput *libinput = device->base.seat->libinput;
1349         const char *prop;
1350         int angle = DEFAULT_WHEEL_CLICK_ANGLE;
1351
1352         prop = udev_device_get_property_value(device->udev_device,
1353                                               "MOUSE_WHEEL_CLICK_ANGLE");
1354         if (prop) {
1355                 angle = parse_mouse_wheel_click_angle_property(prop);
1356                 if (!angle) {
1357                         log_error(libinput,
1358                                   "Mouse wheel click angle '%s' is present but invalid,"
1359                                   "using %d degrees instead\n",
1360                                   device->devname,
1361                                   DEFAULT_WHEEL_CLICK_ANGLE);
1362                         angle = DEFAULT_WHEEL_CLICK_ANGLE;
1363                 }
1364         }
1365
1366         return angle;
1367 }
1368
1369 static inline int
1370 evdev_get_trackpoint_dpi(struct evdev_device *device)
1371 {
1372         struct libinput *libinput = device->base.seat->libinput;
1373         const char *trackpoint_accel;
1374         double accel = DEFAULT_TRACKPOINT_ACCEL;
1375
1376         trackpoint_accel = udev_device_get_property_value(
1377                                 device->udev_device, "POINTINGSTICK_CONST_ACCEL");
1378         if (trackpoint_accel) {
1379                 accel = parse_trackpoint_accel_property(trackpoint_accel);
1380                 if (accel == 0.0) {
1381                         log_error(libinput, "Trackpoint accel property for "
1382                                             "'%s' is present but invalid, "
1383                                             "using %.2f instead\n",
1384                                             device->devname,
1385                                             DEFAULT_TRACKPOINT_ACCEL);
1386                         accel = DEFAULT_TRACKPOINT_ACCEL;
1387                 }
1388         }
1389
1390         return DEFAULT_MOUSE_DPI / accel;
1391 }
1392
1393 static inline int
1394 evdev_read_dpi_prop(struct evdev_device *device)
1395 {
1396         struct libinput *libinput = device->base.seat->libinput;
1397         const char *mouse_dpi;
1398         int dpi = DEFAULT_MOUSE_DPI;
1399
1400         /*
1401          * Trackpoints do not have dpi, instead hwdb may contain a
1402          * POINTINGSTICK_CONST_ACCEL value to compensate for sensitivity
1403          * differences between models, we translate this to a fake dpi.
1404          */
1405         if (libevdev_has_property(device->evdev, INPUT_PROP_POINTING_STICK))
1406                 return evdev_get_trackpoint_dpi(device);
1407
1408         mouse_dpi = udev_device_get_property_value(device->udev_device,
1409                                                    "MOUSE_DPI");
1410         if (mouse_dpi) {
1411                 dpi = parse_mouse_dpi_property(mouse_dpi);
1412                 if (!dpi) {
1413                         log_error(libinput, "Mouse DPI property for '%s' is "
1414                                             "present but invalid, using %d "
1415                                             "DPI instead\n",
1416                                             device->devname,
1417                                             DEFAULT_MOUSE_DPI);
1418                         dpi = DEFAULT_MOUSE_DPI;
1419                 }
1420         }
1421
1422         return dpi;
1423 }
1424
1425 static inline enum evdev_device_model
1426 evdev_read_model(struct evdev_device *device)
1427 {
1428         const struct model_map {
1429                 const char *property;
1430                 enum evdev_device_model model;
1431         } model_map[] = {
1432                 { "LIBINPUT_MODEL_LENOVO_X230", EVDEV_MODEL_LENOVO_X230 },
1433                 { NULL, EVDEV_MODEL_DEFAULT },
1434         };
1435         const struct model_map *m = model_map;
1436
1437         while (m->property) {
1438                 if (!!udev_device_get_property_value(device->udev_device,
1439                                                      m->property))
1440                         break;
1441                 m++;
1442         }
1443
1444         return m->model;
1445 }
1446
1447 /* Return 1 if the given resolutions have been set, or 0 otherwise */
1448 inline int
1449 evdev_fix_abs_resolution(struct evdev_device *device,
1450                          unsigned int xcode,
1451                          unsigned int ycode,
1452                          int xresolution,
1453                          int yresolution)
1454 {
1455         struct libinput *libinput = device->base.seat->libinput;
1456         struct libevdev *evdev = device->evdev;
1457         const struct input_absinfo *absx, *absy;
1458         struct input_absinfo fixed;
1459         int rc = 0;
1460
1461         if (!(xcode == ABS_X && ycode == ABS_Y)  &&
1462             !(xcode == ABS_MT_POSITION_X && ycode == ABS_MT_POSITION_Y)) {
1463                 log_bug_libinput(libinput,
1464                                  "Invalid x/y code combination %d/%d\n",
1465                                  xcode, ycode);
1466                 return 0;
1467         }
1468
1469         if (xresolution == 0 || yresolution == 0 ||
1470             (xresolution == EVDEV_FAKE_RESOLUTION && xresolution != yresolution) ||
1471             (yresolution == EVDEV_FAKE_RESOLUTION && xresolution != yresolution)) {
1472                 log_bug_libinput(libinput,
1473                                  "Invalid x/y resolutions %d/%d\n",
1474                                  xresolution, yresolution);
1475                 return 0;
1476         }
1477
1478         absx = libevdev_get_abs_info(evdev, xcode);
1479         absy = libevdev_get_abs_info(evdev, ycode);
1480
1481         if (absx->resolution == 0 || absx->resolution == EVDEV_FAKE_RESOLUTION) {
1482                 fixed = *absx;
1483                 fixed.resolution = xresolution;
1484                 /* libevdev_set_abs_info() changes the absinfo we already
1485                    have a pointer to, no need to fetch it again */
1486                 libevdev_set_abs_info(evdev, xcode, &fixed);
1487                 rc = 1;
1488         }
1489
1490         if (absy->resolution == 0 || absy->resolution == EVDEV_FAKE_RESOLUTION) {
1491                 fixed = *absy;
1492                 fixed.resolution = yresolution;
1493                 /* libevdev_set_abs_info() changes the absinfo we already
1494                    have a pointer to, no need to fetch it again */
1495                 libevdev_set_abs_info(evdev, ycode, &fixed);
1496                 rc = 1;
1497         }
1498
1499         return rc;
1500 }
1501
1502 static enum evdev_device_udev_tags
1503 evdev_device_get_udev_tags(struct evdev_device *device,
1504                            struct udev_device *udev_device)
1505 {
1506         const char *prop;
1507         enum evdev_device_udev_tags tags = 0;
1508         const struct evdev_udev_tag_match *match;
1509         int i;
1510
1511         for (i = 0; i < 2 && udev_device; i++) {
1512                 match = evdev_udev_tag_matches;
1513                 while (match->name) {
1514                         prop = udev_device_get_property_value(
1515                                                       udev_device,
1516                                                       match->name);
1517                         if (prop)
1518                                 tags |= match->tag;
1519
1520                         match++;
1521                 }
1522                 udev_device = udev_device_get_parent(udev_device);
1523         }
1524
1525         return tags;
1526 }
1527
1528 /* Fake MT devices have the ABS_MT_SLOT bit set because of
1529    the limited ABS_* range - they aren't MT devices, they
1530    just have too many ABS_ axes */
1531 static inline bool
1532 evdev_is_fake_mt_device(struct evdev_device *device)
1533 {
1534         struct libevdev *evdev = device->evdev;
1535
1536         return libevdev_has_event_code(evdev, EV_ABS, ABS_MT_SLOT) &&
1537                 libevdev_get_num_slots(evdev) == -1;
1538 }
1539
1540 static inline void
1541 evdev_fix_android_mt(struct evdev_device *device)
1542 {
1543         struct libevdev *evdev = device->evdev;
1544
1545         if (libevdev_has_event_code(evdev, EV_ABS, ABS_X) ||
1546             libevdev_has_event_code(evdev, EV_ABS, ABS_Y))
1547                 return;
1548
1549         if (!libevdev_has_event_code(evdev, EV_ABS, ABS_MT_POSITION_X) ||
1550             !libevdev_has_event_code(evdev, EV_ABS, ABS_MT_POSITION_Y) ||
1551             evdev_is_fake_mt_device(device))
1552                 return;
1553
1554         libevdev_enable_event_code(evdev, EV_ABS, ABS_X,
1555                       libevdev_get_abs_info(evdev, ABS_MT_POSITION_X));
1556         libevdev_enable_event_code(evdev, EV_ABS, ABS_Y,
1557                       libevdev_get_abs_info(evdev, ABS_MT_POSITION_Y));
1558 }
1559
1560 static inline int
1561 evdev_check_min_max(struct evdev_device *device, unsigned int code)
1562 {
1563         struct libevdev *evdev = device->evdev;
1564         const struct input_absinfo *absinfo;
1565
1566         if (!libevdev_has_event_code(evdev, EV_ABS, code))
1567                 return 0;
1568
1569         absinfo = libevdev_get_abs_info(evdev, code);
1570         if (absinfo->minimum == absinfo->maximum) {
1571                 /* Some devices have a sort-of legitimate min/max of 0 for
1572                  * ABS_MISC and above (e.g. Roccat Kone XTD). Don't ignore
1573                  * them, simply disable the axes so we won't get events,
1574                  * we don't know what to do with them anyway.
1575                  */
1576                 if (absinfo->minimum == 0 &&
1577                     code >= ABS_MISC && code < ABS_MT_SLOT) {
1578                         log_info(device->base.seat->libinput,
1579                                  "Disabling EV_ABS %#x on device '%s' (min == max == 0)\n",
1580                                  code,
1581                                  device->devname);
1582                         libevdev_disable_event_code(device->evdev,
1583                                                     EV_ABS,
1584                                                     code);
1585                 } else {
1586                         log_bug_kernel(device->base.seat->libinput,
1587                                        "Device '%s' has min == max on %s\n",
1588                                        device->devname,
1589                                        libevdev_event_code_get_name(EV_ABS, code));
1590                         return -1;
1591                 }
1592         }
1593
1594         return 0;
1595 }
1596
1597 static int
1598 evdev_reject_device(struct evdev_device *device)
1599 {
1600         struct libinput *libinput = device->base.seat->libinput;
1601         struct libevdev *evdev = device->evdev;
1602         unsigned int code;
1603         const struct input_absinfo *absx, *absy;
1604
1605         if (libevdev_has_event_code(evdev, EV_ABS, ABS_X) ^
1606             libevdev_has_event_code(evdev, EV_ABS, ABS_Y))
1607                 return -1;
1608
1609         if (libevdev_has_event_code(evdev, EV_ABS, ABS_MT_POSITION_X) ^
1610             libevdev_has_event_code(evdev, EV_ABS, ABS_MT_POSITION_Y))
1611                 return -1;
1612
1613         if (libevdev_has_event_code(evdev, EV_ABS, ABS_X)) {
1614                 absx = libevdev_get_abs_info(evdev, ABS_X);
1615                 absy = libevdev_get_abs_info(evdev, ABS_Y);
1616                 if ((absx->resolution == 0 && absy->resolution != 0) ||
1617                     (absx->resolution != 0 && absy->resolution == 0)) {
1618                         log_bug_kernel(libinput,
1619                                        "Kernel has only x or y resolution, not both.\n");
1620                         return -1;
1621                 }
1622         }
1623
1624         if (!evdev_is_fake_mt_device(device) &&
1625             libevdev_has_event_code(evdev, EV_ABS, ABS_MT_POSITION_X)) {
1626                 absx = libevdev_get_abs_info(evdev, ABS_MT_POSITION_X);
1627                 absy = libevdev_get_abs_info(evdev, ABS_MT_POSITION_Y);
1628                 if ((absx->resolution == 0 && absy->resolution != 0) ||
1629                     (absx->resolution != 0 && absy->resolution == 0)) {
1630                         log_bug_kernel(libinput,
1631                                        "Kernel has only x or y MT resolution, not both.\n");
1632                         return -1;
1633                 }
1634         }
1635
1636         for (code = 0; code < ABS_CNT; code++) {
1637                 switch (code) {
1638                 case ABS_MISC:
1639                 case ABS_MT_SLOT:
1640                 case ABS_MT_TOOL_TYPE:
1641                         break;
1642                 default:
1643                         if (evdev_check_min_max(device, code) == -1)
1644                                 return -1;
1645                 }
1646         }
1647
1648         return 0;
1649 }
1650
1651 static int
1652 evdev_configure_mt_device(struct evdev_device *device)
1653 {
1654         struct libevdev *evdev = device->evdev;
1655         struct mt_slot *slots;
1656         int num_slots;
1657         int active_slot;
1658         int slot;
1659
1660         if (!libevdev_has_event_code(evdev, EV_ABS, ABS_MT_POSITION_X) ||
1661             !libevdev_has_event_code(evdev, EV_ABS, ABS_MT_POSITION_Y))
1662                  return 0;
1663
1664         if (evdev_fix_abs_resolution(device,
1665                                      ABS_MT_POSITION_X,
1666                                      ABS_MT_POSITION_Y,
1667                                      EVDEV_FAKE_RESOLUTION,
1668                                      EVDEV_FAKE_RESOLUTION))
1669                 device->abs.fake_resolution = 1;
1670
1671         device->abs.absinfo_x = libevdev_get_abs_info(evdev, ABS_MT_POSITION_X);
1672         device->abs.absinfo_y = libevdev_get_abs_info(evdev, ABS_MT_POSITION_Y);
1673         device->is_mt = 1;
1674
1675         /* We only handle the slotted Protocol B in libinput.
1676            Devices with ABS_MT_POSITION_* but not ABS_MT_SLOT
1677            require mtdev for conversion. */
1678         if (evdev_need_mtdev(device)) {
1679                 device->mtdev = mtdev_new_open(device->fd);
1680                 if (!device->mtdev)
1681                         return -1;
1682
1683                 /* pick 10 slots as default for type A
1684                    devices. */
1685                 num_slots = 10;
1686                 active_slot = device->mtdev->caps.slot.value;
1687         } else {
1688                 num_slots = libevdev_get_num_slots(device->evdev);
1689                 active_slot = libevdev_get_current_slot(evdev);
1690         }
1691
1692         slots = calloc(num_slots, sizeof(struct mt_slot));
1693         if (!slots)
1694                 return -1;
1695
1696         for (slot = 0; slot < num_slots; ++slot) {
1697                 slots[slot].seat_slot = -1;
1698                 slots[slot].point.x = 0;
1699                 slots[slot].point.y = 0;
1700         }
1701         device->mt.slots = slots;
1702         device->mt.slots_len = num_slots;
1703         device->mt.slot = active_slot;
1704
1705         return 0;
1706 }
1707
1708 static int
1709 evdev_configure_device(struct evdev_device *device)
1710 {
1711         struct libinput *libinput = device->base.seat->libinput;
1712         struct libevdev *evdev = device->evdev;
1713         const char *devnode = udev_device_get_devnode(device->udev_device);
1714         enum evdev_device_udev_tags udev_tags;
1715
1716         udev_tags = evdev_device_get_udev_tags(device, device->udev_device);
1717
1718         if ((udev_tags & EVDEV_UDEV_TAG_INPUT) == 0 ||
1719             (udev_tags & ~EVDEV_UDEV_TAG_INPUT) == 0) {
1720                 log_info(libinput,
1721                          "input device '%s', %s not tagged as input device\n",
1722                          device->devname, devnode);
1723                 return -1;
1724         }
1725
1726         log_info(libinput,
1727                  "input device '%s', %s is tagged by udev as:%s%s%s%s%s%s%s%s\n",
1728                  device->devname, devnode,
1729                  udev_tags & EVDEV_UDEV_TAG_KEYBOARD ? " Keyboard" : "",
1730                  udev_tags & EVDEV_UDEV_TAG_MOUSE ? " Mouse" : "",
1731                  udev_tags & EVDEV_UDEV_TAG_TOUCHPAD ? " Touchpad" : "",
1732                  udev_tags & EVDEV_UDEV_TAG_TOUCHSCREEN ? " Touchscreen" : "",
1733                  udev_tags & EVDEV_UDEV_TAG_TABLET ? " Tablet" : "",
1734                  udev_tags & EVDEV_UDEV_TAG_JOYSTICK ? " Joystick" : "",
1735                  udev_tags & EVDEV_UDEV_TAG_ACCELEROMETER ? " Accelerometer" : "",
1736                  udev_tags & EVDEV_UDEV_TAG_BUTTONSET ? " Buttonset" : "");
1737
1738         /* libwacom *adds* TABLET, TOUCHPAD but leaves JOYSTICK in place, so
1739            make sure we only ignore real joystick devices */
1740         if ((udev_tags & EVDEV_UDEV_TAG_JOYSTICK) == udev_tags) {
1741                 log_info(libinput,
1742                          "input device '%s', %s is a joystick, ignoring\n",
1743                          device->devname, devnode);
1744                 return -1;
1745         }
1746
1747         /* libwacom assigns tablet _and_ tablet_pad to the pad devices */
1748         if (udev_tags & EVDEV_UDEV_TAG_BUTTONSET) {
1749                 log_info(libinput,
1750                          "input device '%s', %s is a buttonset, ignoring\n",
1751                          device->devname, devnode);
1752                 return -1;
1753         }
1754
1755         if (evdev_reject_device(device) == -1) {
1756                 log_info(libinput,
1757                          "input device '%s', %s was rejected.\n",
1758                          device->devname, devnode);
1759                 return -1;
1760         }
1761
1762         if (!evdev_is_fake_mt_device(device))
1763                 evdev_fix_android_mt(device);
1764
1765         if (libevdev_has_event_code(evdev, EV_ABS, ABS_X)) {
1766                 if (evdev_fix_abs_resolution(device,
1767                                              ABS_X,
1768                                              ABS_Y,
1769                                              EVDEV_FAKE_RESOLUTION,
1770                                              EVDEV_FAKE_RESOLUTION))
1771                         device->abs.fake_resolution = 1;
1772                 device->abs.absinfo_x = libevdev_get_abs_info(evdev, ABS_X);
1773                 device->abs.absinfo_y = libevdev_get_abs_info(evdev, ABS_Y);
1774
1775                 if (evdev_is_fake_mt_device(device)) {
1776                         udev_tags &= ~EVDEV_UDEV_TAG_TOUCHSCREEN;
1777                 } else if (evdev_configure_mt_device(device) == -1) {
1778                         return -1;
1779                 }
1780         }
1781
1782         if (udev_tags & EVDEV_UDEV_TAG_TOUCHPAD) {
1783                 device->dispatch = evdev_mt_touchpad_create(device);
1784                 log_info(libinput,
1785                          "input device '%s', %s is a touchpad\n",
1786                          device->devname, devnode);
1787                 return device->dispatch == NULL ? -1 : 0;
1788         }
1789
1790         if (udev_tags & EVDEV_UDEV_TAG_MOUSE) {
1791                 if (!libevdev_has_event_code(evdev, EV_ABS, ABS_X) &&
1792                     !libevdev_has_event_code(evdev, EV_ABS, ABS_Y) &&
1793                     evdev_device_init_pointer_acceleration(
1794                                         device,
1795                                         pointer_accel_profile_linear) == -1)
1796                         return -1;
1797
1798                 device->seat_caps |= EVDEV_DEVICE_POINTER;
1799
1800                 log_info(libinput,
1801                          "input device '%s', %s is a pointer caps\n",
1802                          device->devname, devnode);
1803
1804                 /* want left-handed config option */
1805                 device->left_handed.want_enabled = true;
1806                 /* want natural-scroll config option */
1807                 device->scroll.natural_scrolling_enabled = true;
1808                 /* want button scrolling config option */
1809                 device->scroll.want_button = 1;
1810         }
1811
1812         if (udev_tags & EVDEV_UDEV_TAG_KEYBOARD) {
1813                 device->seat_caps |= EVDEV_DEVICE_KEYBOARD;
1814                 log_info(libinput,
1815                          "input device '%s', %s is a keyboard\n",
1816                          device->devname, devnode);
1817
1818                 /* want natural-scroll config option */
1819                 if (libevdev_has_event_code(evdev, EV_REL, REL_WHEEL) ||
1820                     libevdev_has_event_code(evdev, EV_REL, REL_HWHEEL)) {
1821                         device->scroll.natural_scrolling_enabled = true;
1822                         device->seat_caps |= EVDEV_DEVICE_POINTER;
1823                 }
1824         }
1825
1826         if (udev_tags & EVDEV_UDEV_TAG_TOUCHSCREEN) {
1827                 device->seat_caps |= EVDEV_DEVICE_TOUCH;
1828                 log_info(libinput,
1829                          "input device '%s', %s is a touch device\n",
1830                          device->devname, devnode);
1831         }
1832
1833         return 0;
1834 }
1835
1836 static void
1837 evdev_notify_added_device(struct evdev_device *device)
1838 {
1839         struct libinput_device *dev;
1840
1841         list_for_each(dev, &device->base.seat->devices_list, link) {
1842                 struct evdev_device *d = (struct evdev_device*)dev;
1843                 if (dev == &device->base)
1844                         continue;
1845
1846                 /* Notify existing device d about addition of device device */
1847                 if (d->dispatch->interface->device_added)
1848                         d->dispatch->interface->device_added(d, device);
1849
1850                 /* Notify new device device about existing device d */
1851                 if (device->dispatch->interface->device_added)
1852                         device->dispatch->interface->device_added(device, d);
1853
1854                 /* Notify new device device if existing device d is suspended */
1855                 if (d->suspended && device->dispatch->interface->device_suspended)
1856                         device->dispatch->interface->device_suspended(device, d);
1857         }
1858
1859         notify_added_device(&device->base);
1860 }
1861
1862 static int
1863 evdev_device_compare_syspath(struct udev_device *udev_device, int fd)
1864 {
1865         struct udev *udev = udev_device_get_udev(udev_device);
1866         struct udev_device *udev_device_new = NULL;
1867         struct stat st;
1868         int rc = 1;
1869
1870         if (fstat(fd, &st) < 0)
1871                 goto out;
1872
1873         udev_device_new = udev_device_new_from_devnum(udev, 'c', st.st_rdev);
1874         if (!udev_device_new)
1875                 goto out;
1876
1877         rc = strcmp(udev_device_get_syspath(udev_device_new),
1878                     udev_device_get_syspath(udev_device));
1879 out:
1880         if (udev_device_new)
1881                 udev_device_unref(udev_device_new);
1882         return rc;
1883 }
1884
1885 static int
1886 evdev_set_device_group(struct evdev_device *device,
1887                        struct udev_device *udev_device)
1888 {
1889         struct libinput_device_group *group = NULL;
1890         const char *udev_group;
1891
1892         udev_group = udev_device_get_property_value(udev_device,
1893                                                     "LIBINPUT_DEVICE_GROUP");
1894         if (udev_group) {
1895                 struct libinput_device *d;
1896
1897                 list_for_each(d, &device->base.seat->devices_list, link) {
1898                         const char *identifier = d->group->identifier;
1899
1900                         if (identifier &&
1901                             strcmp(identifier, udev_group) == 0) {
1902                                 group = d->group;
1903                                 break;
1904                         }
1905                 }
1906         }
1907
1908         if (!group) {
1909                 group = libinput_device_group_create(udev_group);
1910                 if (!group)
1911                         return 1;
1912                 libinput_device_set_device_group(&device->base, group);
1913                 libinput_device_group_unref(group);
1914         } else {
1915                 libinput_device_set_device_group(&device->base, group);
1916         }
1917
1918         return 0;
1919 }
1920
1921 struct evdev_device *
1922 evdev_device_create(struct libinput_seat *seat,
1923                     struct udev_device *udev_device)
1924 {
1925         struct libinput *libinput = seat->libinput;
1926         struct evdev_device *device = NULL;
1927         int rc;
1928         int fd;
1929         int unhandled_device = 0;
1930         const char *devnode = udev_device_get_devnode(udev_device);
1931
1932         /* Use non-blocking mode so that we can loop on read on
1933          * evdev_device_data() until all events on the fd are
1934          * read.  mtdev_get() also expects this. */
1935         fd = open_restricted(libinput, devnode, O_RDWR | O_NONBLOCK);
1936         if (fd < 0) {
1937                 log_info(libinput,
1938                          "opening input device '%s' failed (%s).\n",
1939                          devnode, strerror(-fd));
1940                 return NULL;
1941         }
1942
1943         if (evdev_device_compare_syspath(udev_device, fd) != 0)
1944                 goto err;
1945
1946         device = zalloc(sizeof *device);
1947         if (device == NULL)
1948                 goto err;
1949
1950         libinput_device_init(&device->base, seat);
1951         libinput_seat_ref(seat);
1952
1953         rc = libevdev_new_from_fd(fd, &device->evdev);
1954         if (rc != 0)
1955                 goto err;
1956
1957         libevdev_set_clock_id(device->evdev, CLOCK_MONOTONIC);
1958
1959         device->seat_caps = 0;
1960         device->is_mt = 0;
1961         device->mtdev = NULL;
1962         device->udev_device = udev_device_ref(udev_device);
1963         device->rel.x = 0;
1964         device->rel.y = 0;
1965         device->abs.seat_slot = -1;
1966         device->dispatch = NULL;
1967         device->fd = fd;
1968         device->pending_event = EVDEV_NONE;
1969         device->devname = libevdev_get_name(device->evdev);
1970         device->scroll.threshold = 5.0; /* Default may be overridden */
1971         device->scroll.direction = 0;
1972         device->scroll.wheel_click_angle =
1973                 evdev_read_wheel_click_prop(device);
1974         device->dpi = evdev_read_dpi_prop(device);
1975         device->model = evdev_read_model(device);
1976         /* at most 5 SYN_DROPPED log-messages per 30s */
1977         ratelimit_init(&device->syn_drop_limit, 30ULL * 1000, 5);
1978
1979         matrix_init_identity(&device->abs.calibration);
1980         matrix_init_identity(&device->abs.usermatrix);
1981         matrix_init_identity(&device->abs.default_calibration);
1982
1983         if (evdev_configure_device(device) == -1)
1984                 goto err;
1985
1986         if (device->seat_caps == 0) {
1987                 unhandled_device = 1;
1988                 goto err;
1989         }
1990
1991         /* If the dispatch was not set up use the fallback. */
1992         if (device->dispatch == NULL)
1993                 device->dispatch = fallback_dispatch_create(&device->base);
1994         if (device->dispatch == NULL)
1995                 goto err;
1996
1997         device->source =
1998                 libinput_add_fd(libinput, fd, evdev_device_dispatch, device);
1999         if (!device->source)
2000                 goto err;
2001
2002         if (evdev_set_device_group(device, udev_device))
2003                 goto err;
2004
2005         list_insert(seat->devices_list.prev, &device->base.link);
2006
2007         evdev_tag_device(device);
2008         evdev_notify_added_device(device);
2009
2010         return device;
2011
2012 err:
2013         if (fd >= 0)
2014                 close_restricted(libinput, fd);
2015         if (device)
2016                 evdev_device_destroy(device);
2017
2018         return unhandled_device ? EVDEV_UNHANDLED_DEVICE :  NULL;
2019 }
2020
2021 const char *
2022 evdev_device_get_output(struct evdev_device *device)
2023 {
2024         return device->output_name;
2025 }
2026
2027 const char *
2028 evdev_device_get_sysname(struct evdev_device *device)
2029 {
2030         return udev_device_get_sysname(device->udev_device);
2031 }
2032
2033 const char *
2034 evdev_device_get_name(struct evdev_device *device)
2035 {
2036         return device->devname;
2037 }
2038
2039 unsigned int
2040 evdev_device_get_id_product(struct evdev_device *device)
2041 {
2042         return libevdev_get_id_product(device->evdev);
2043 }
2044
2045 unsigned int
2046 evdev_device_get_id_vendor(struct evdev_device *device)
2047 {
2048         return libevdev_get_id_vendor(device->evdev);
2049 }
2050
2051 struct udev_device *
2052 evdev_device_get_udev_device(struct evdev_device *device)
2053 {
2054         return udev_device_ref(device->udev_device);
2055 }
2056
2057 void
2058 evdev_device_set_default_calibration(struct evdev_device *device,
2059                                      const float calibration[6])
2060 {
2061         matrix_from_farray6(&device->abs.default_calibration, calibration);
2062         evdev_device_calibrate(device, calibration);
2063 }
2064
2065 void
2066 evdev_device_calibrate(struct evdev_device *device,
2067                        const float calibration[6])
2068 {
2069         struct matrix scale,
2070                       translate,
2071                       transform;
2072         double sx, sy;
2073
2074         matrix_from_farray6(&transform, calibration);
2075         device->abs.apply_calibration = !matrix_is_identity(&transform);
2076
2077         if (!device->abs.apply_calibration) {
2078                 matrix_init_identity(&device->abs.calibration);
2079                 return;
2080         }
2081
2082         sx = device->abs.absinfo_x->maximum - device->abs.absinfo_x->minimum + 1;
2083         sy = device->abs.absinfo_y->maximum - device->abs.absinfo_y->minimum + 1;
2084
2085         /* The transformation matrix is in the form:
2086          *  [ a b c ]
2087          *  [ d e f ]
2088          *  [ 0 0 1 ]
2089          * Where a, e are the scale components, a, b, d, e are the rotation
2090          * component (combined with scale) and c and f are the translation
2091          * component. The translation component in the input matrix must be
2092          * normalized to multiples of the device width and height,
2093          * respectively. e.g. c == 1 shifts one device-width to the right.
2094          *
2095          * We pre-calculate a single matrix to apply to event coordinates:
2096          *     M = Un-Normalize * Calibration * Normalize
2097          *
2098          * Normalize: scales the device coordinates to [0,1]
2099          * Calibration: user-supplied matrix
2100          * Un-Normalize: scales back up to device coordinates
2101          * Matrix maths requires the normalize/un-normalize in reverse
2102          * order.
2103          */
2104
2105         /* back up the user matrix so we can return it on request */
2106         matrix_from_farray6(&device->abs.usermatrix, calibration);
2107
2108         /* Un-Normalize */
2109         matrix_init_translate(&translate,
2110                               device->abs.absinfo_x->minimum,
2111                               device->abs.absinfo_y->minimum);
2112         matrix_init_scale(&scale, sx, sy);
2113         matrix_mult(&scale, &translate, &scale);
2114
2115         /* Calibration */
2116         matrix_mult(&transform, &scale, &transform);
2117
2118         /* Normalize */
2119         matrix_init_translate(&translate,
2120                               -device->abs.absinfo_x->minimum/sx,
2121                               -device->abs.absinfo_y->minimum/sy);
2122         matrix_init_scale(&scale, 1.0/sx, 1.0/sy);
2123         matrix_mult(&scale, &translate, &scale);
2124
2125         /* store final matrix in device */
2126         matrix_mult(&device->abs.calibration, &transform, &scale);
2127 }
2128
2129 int
2130 evdev_device_has_capability(struct evdev_device *device,
2131                             enum libinput_device_capability capability)
2132 {
2133         switch (capability) {
2134         case LIBINPUT_DEVICE_CAP_POINTER:
2135                 return !!(device->seat_caps & EVDEV_DEVICE_POINTER);
2136         case LIBINPUT_DEVICE_CAP_KEYBOARD:
2137                 return !!(device->seat_caps & EVDEV_DEVICE_KEYBOARD);
2138         case LIBINPUT_DEVICE_CAP_TOUCH:
2139                 return !!(device->seat_caps & EVDEV_DEVICE_TOUCH);
2140         default:
2141                 return 0;
2142         }
2143 }
2144
2145 int
2146 evdev_device_get_size(struct evdev_device *device,
2147                       double *width,
2148                       double *height)
2149 {
2150         const struct input_absinfo *x, *y;
2151
2152         x = libevdev_get_abs_info(device->evdev, ABS_X);
2153         y = libevdev_get_abs_info(device->evdev, ABS_Y);
2154
2155         if (!x || !y || device->abs.fake_resolution ||
2156             !x->resolution || !y->resolution)
2157                 return -1;
2158
2159         *width = evdev_convert_to_mm(x, x->maximum);
2160         *height = evdev_convert_to_mm(y, y->maximum);
2161
2162         return 0;
2163 }
2164
2165 int
2166 evdev_device_has_button(struct evdev_device *device, uint32_t code)
2167 {
2168         if (!(device->seat_caps & EVDEV_DEVICE_POINTER))
2169                 return -1;
2170
2171         return libevdev_has_event_code(device->evdev, EV_KEY, code);
2172 }
2173
2174 int
2175 evdev_device_has_key(struct evdev_device *device, uint32_t code)
2176 {
2177         if (!(device->seat_caps & EVDEV_DEVICE_KEYBOARD))
2178                 return -1;
2179
2180         return libevdev_has_event_code(device->evdev, EV_KEY, code);
2181 }
2182
2183 static inline bool
2184 evdev_is_scrolling(const struct evdev_device *device,
2185                    enum libinput_pointer_axis axis)
2186 {
2187         assert(axis == LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL ||
2188                axis == LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL);
2189
2190         return (device->scroll.direction & AS_MASK(axis)) != 0;
2191 }
2192
2193 static inline void
2194 evdev_start_scrolling(struct evdev_device *device,
2195                       enum libinput_pointer_axis axis)
2196 {
2197         assert(axis == LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL ||
2198                axis == LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL);
2199
2200         device->scroll.direction |= AS_MASK(axis);
2201 }
2202
2203 void
2204 evdev_post_scroll(struct evdev_device *device,
2205                   uint64_t time,
2206                   enum libinput_pointer_axis_source source,
2207                   const struct normalized_coords *delta)
2208 {
2209         const struct normalized_coords *trigger;
2210         struct normalized_coords event;
2211
2212         if (!evdev_is_scrolling(device,
2213                                 LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL))
2214                 device->scroll.buildup.y += delta->y;
2215         if (!evdev_is_scrolling(device,
2216                                 LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL))
2217                 device->scroll.buildup.x += delta->x;
2218
2219         trigger = &device->scroll.buildup;
2220
2221         /* If we're not scrolling yet, use a distance trigger: moving
2222            past a certain distance starts scrolling */
2223         if (!evdev_is_scrolling(device,
2224                                 LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL) &&
2225             !evdev_is_scrolling(device,
2226                                 LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL)) {
2227                 if (fabs(trigger->y) >= device->scroll.threshold)
2228                         evdev_start_scrolling(device,
2229                                               LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL);
2230                 if (fabs(trigger->x) >= device->scroll.threshold)
2231                         evdev_start_scrolling(device,
2232                                               LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL);
2233         /* We're already scrolling in one direction. Require some
2234            trigger speed to start scrolling in the other direction */
2235         } else if (!evdev_is_scrolling(device,
2236                                LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL)) {
2237                 if (fabs(delta->y) >= device->scroll.threshold)
2238                         evdev_start_scrolling(device,
2239                                       LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL);
2240         } else if (!evdev_is_scrolling(device,
2241                                 LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL)) {
2242                 if (fabs(delta->x) >= device->scroll.threshold)
2243                         evdev_start_scrolling(device,
2244                                       LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL);
2245         }
2246
2247         event = *delta;
2248
2249         /* We use the trigger to enable, but the delta from this event for
2250          * the actual scroll movement. Otherwise we get a jump once
2251          * scrolling engages */
2252         if (!evdev_is_scrolling(device,
2253                                LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL))
2254                 event.y = 0.0;
2255
2256         if (!evdev_is_scrolling(device,
2257                                LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL))
2258                 event.x = 0.0;
2259
2260         if (!normalized_is_zero(event)) {
2261                 const struct discrete_coords zero_discrete = { 0.0, 0.0 };
2262                 evdev_notify_axis(device,
2263                                   time,
2264                                   device->scroll.direction,
2265                                   source,
2266                                   &event,
2267                                   &zero_discrete);
2268         }
2269 }
2270
2271 void
2272 evdev_stop_scroll(struct evdev_device *device,
2273                   uint64_t time,
2274                   enum libinput_pointer_axis_source source)
2275 {
2276         const struct normalized_coords zero = { 0.0, 0.0 };
2277         const struct discrete_coords zero_discrete = { 0.0, 0.0 };
2278
2279         /* terminate scrolling with a zero scroll event */
2280         if (device->scroll.direction != 0)
2281                 pointer_notify_axis(&device->base,
2282                                     time,
2283                                     device->scroll.direction,
2284                                     source,
2285                                     &zero,
2286                                     &zero_discrete);
2287
2288         device->scroll.buildup.x = 0;
2289         device->scroll.buildup.y = 0;
2290         device->scroll.direction = 0;
2291 }
2292
2293 static void
2294 release_pressed_keys(struct evdev_device *device)
2295 {
2296         struct libinput *libinput = device->base.seat->libinput;
2297         uint64_t time;
2298         int code;
2299
2300         if ((time = libinput_now(libinput)) == 0)
2301                 return;
2302
2303         for (code = 0; code < KEY_CNT; code++) {
2304                 int count = get_key_down_count(device, code);
2305
2306                 if (count > 1) {
2307                         log_bug_libinput(libinput,
2308                                          "Key %d is down %d times.\n",
2309                                          code,
2310                                          count);
2311                 }
2312
2313                 while (get_key_down_count(device, code) > 0) {
2314                         switch (get_key_type(code)) {
2315                         case EVDEV_KEY_TYPE_NONE:
2316                                 break;
2317                         case EVDEV_KEY_TYPE_KEY:
2318                                 evdev_keyboard_notify_key(
2319                                         device,
2320                                         time,
2321                                         code,
2322                                         LIBINPUT_KEY_STATE_RELEASED);
2323                                 break;
2324                         case EVDEV_KEY_TYPE_BUTTON:
2325                                 evdev_pointer_notify_physical_button(
2326                                         device,
2327                                         time,
2328                                         evdev_to_left_handed(device, code),
2329                                         LIBINPUT_BUTTON_STATE_RELEASED);
2330                                 break;
2331                         }
2332                 }
2333         }
2334 }
2335
2336 void
2337 evdev_notify_suspended_device(struct evdev_device *device)
2338 {
2339         struct libinput_device *it;
2340
2341         if (device->suspended)
2342                 return;
2343
2344         list_for_each(it, &device->base.seat->devices_list, link) {
2345                 struct evdev_device *d = (struct evdev_device*)it;
2346                 if (it == &device->base)
2347                         continue;
2348
2349                 if (d->dispatch->interface->device_suspended)
2350                         d->dispatch->interface->device_suspended(d, device);
2351         }
2352
2353         device->suspended = 1;
2354 }
2355
2356 void
2357 evdev_notify_resumed_device(struct evdev_device *device)
2358 {
2359         struct libinput_device *it;
2360
2361         if (!device->suspended)
2362                 return;
2363
2364         list_for_each(it, &device->base.seat->devices_list, link) {
2365                 struct evdev_device *d = (struct evdev_device*)it;
2366                 if (it == &device->base)
2367                         continue;
2368
2369                 if (d->dispatch->interface->device_resumed)
2370                         d->dispatch->interface->device_resumed(d, device);
2371         }
2372
2373         device->suspended = 0;
2374 }
2375
2376 int
2377 evdev_device_suspend(struct evdev_device *device)
2378 {
2379         evdev_notify_suspended_device(device);
2380
2381         if (device->source) {
2382                 libinput_remove_source(device->base.seat->libinput,
2383                                        device->source);
2384                 device->source = NULL;
2385         }
2386
2387         release_pressed_keys(device);
2388
2389         if (device->mtdev) {
2390                 mtdev_close_delete(device->mtdev);
2391                 device->mtdev = NULL;
2392         }
2393
2394         if (device->fd != -1) {
2395                 close_restricted(device->base.seat->libinput, device->fd);
2396                 device->fd = -1;
2397         }
2398
2399         return 0;
2400 }
2401
2402 int
2403 evdev_device_resume(struct evdev_device *device)
2404 {
2405         struct libinput *libinput = device->base.seat->libinput;
2406         int fd;
2407         const char *devnode;
2408         struct input_event ev;
2409         enum libevdev_read_status status;
2410
2411         if (device->fd != -1)
2412                 return 0;
2413
2414         if (device->was_removed)
2415                 return -ENODEV;
2416
2417         devnode = udev_device_get_devnode(device->udev_device);
2418         fd = open_restricted(libinput, devnode, O_RDWR | O_NONBLOCK);
2419
2420         if (fd < 0)
2421                 return -errno;
2422
2423         if (evdev_device_compare_syspath(device->udev_device, fd)) {
2424                 close_restricted(libinput, fd);
2425                 return -ENODEV;
2426         }
2427
2428         device->fd = fd;
2429
2430         if (evdev_need_mtdev(device)) {
2431                 device->mtdev = mtdev_new_open(device->fd);
2432                 if (!device->mtdev)
2433                         return -ENODEV;
2434         }
2435
2436         libevdev_change_fd(device->evdev, fd);
2437         libevdev_set_clock_id(device->evdev, CLOCK_MONOTONIC);
2438
2439         /* re-sync libevdev's view of the device, but discard the actual
2440            events. Our device is in a neutral state already */
2441         libevdev_next_event(device->evdev,
2442                             LIBEVDEV_READ_FLAG_FORCE_SYNC,
2443                             &ev);
2444         do {
2445                 status = libevdev_next_event(device->evdev,
2446                                              LIBEVDEV_READ_FLAG_SYNC,
2447                                              &ev);
2448         } while (status == LIBEVDEV_READ_STATUS_SYNC);
2449
2450         device->source =
2451                 libinput_add_fd(libinput, fd, evdev_device_dispatch, device);
2452         if (!device->source) {
2453                 mtdev_close_delete(device->mtdev);
2454                 return -ENOMEM;
2455         }
2456
2457         memset(device->hw_key_mask, 0, sizeof(device->hw_key_mask));
2458
2459         evdev_notify_resumed_device(device);
2460
2461         return 0;
2462 }
2463
2464 void
2465 evdev_device_remove(struct evdev_device *device)
2466 {
2467         struct libinput_device *dev;
2468
2469         list_for_each(dev, &device->base.seat->devices_list, link) {
2470                 struct evdev_device *d = (struct evdev_device*)dev;
2471                 if (dev == &device->base)
2472                         continue;
2473
2474                 if (d->dispatch->interface->device_removed)
2475                         d->dispatch->interface->device_removed(d, device);
2476         }
2477
2478         evdev_device_suspend(device);
2479
2480         if (device->dispatch->interface->remove)
2481                 device->dispatch->interface->remove(device->dispatch);
2482
2483         /* A device may be removed while suspended, mark it to
2484          * skip re-opening a different device with the same node */
2485         device->was_removed = true;
2486
2487         list_remove(&device->base.link);
2488
2489         notify_removed_device(&device->base);
2490         libinput_device_unref(&device->base);
2491 }
2492
2493 void
2494 evdev_device_destroy(struct evdev_device *device)
2495 {
2496         struct evdev_dispatch *dispatch;
2497
2498         dispatch = device->dispatch;
2499         if (dispatch)
2500                 dispatch->interface->destroy(dispatch);
2501
2502         if (device->base.group)
2503                 libinput_device_group_unref(device->base.group);
2504
2505         filter_destroy(device->pointer.filter);
2506         libinput_seat_unref(device->base.seat);
2507         libevdev_free(device->evdev);
2508         udev_device_unref(device->udev_device);
2509         free(device->mt.slots);
2510         free(device);
2511 }