evdev: casting unsigned int to int to compare value
[platform/upstream/libinput.git] / src / evdev-fallback.c
1 /*
2  * Copyright © 2010 Intel Corporation
3  * Copyright © 2013 Jonas Ådahl
4  * Copyright © 2013-2017 Red Hat, Inc.
5  * Copyright © 2017 James Ye <jye836@gmail.com>
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the "Software"),
9  * to deal in the Software without restriction, including without limitation
10  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11  * and/or sell copies of the Software, and to permit persons to whom the
12  * Software is furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice (including the next
15  * paragraph) shall be included in all copies or substantial portions of the
16  * Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
21  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24  * DEALINGS IN THE SOFTWARE.
25  */
26
27 #include "config.h"
28
29 #include <mtdev-plumbing.h>
30
31 #include "evdev-fallback.h"
32 #include "util-input-event.h"
33
34 static void
35 fallback_keyboard_notify_key(struct fallback_dispatch *dispatch,
36                              struct evdev_device *device,
37                              uint64_t time,
38                              int key,
39                              enum libinput_key_state state)
40 {
41         int down_count;
42
43         down_count = evdev_update_key_down_count(device, key, state);
44
45         if ((state == LIBINPUT_KEY_STATE_PRESSED && down_count == 1) ||
46             (state == LIBINPUT_KEY_STATE_RELEASED && down_count == 0))
47                 keyboard_notify_key(&device->base, time, key, state);
48 }
49
50 static void
51 fallback_lid_notify_toggle(struct fallback_dispatch *dispatch,
52                            struct evdev_device *device,
53                            uint64_t time)
54 {
55         if (dispatch->lid.is_closed ^ dispatch->lid.is_closed_client_state) {
56                 switch_notify_toggle(&device->base,
57                                      time,
58                                      LIBINPUT_SWITCH_LID,
59                                      dispatch->lid.is_closed);
60                 dispatch->lid.is_closed_client_state = dispatch->lid.is_closed;
61         }
62 }
63
64 void
65 fallback_notify_physical_button(struct fallback_dispatch *dispatch,
66                                 struct evdev_device *device,
67                                 uint64_t time,
68                                 int button,
69                                 enum libinput_button_state state)
70 {
71         evdev_pointer_notify_physical_button(device, time, button, state);
72 }
73
74 static enum libinput_switch_state
75 fallback_interface_get_switch_state(struct evdev_dispatch *evdev_dispatch,
76                                     enum libinput_switch sw)
77 {
78         struct fallback_dispatch *dispatch = fallback_dispatch(evdev_dispatch);
79
80         switch (sw) {
81         case LIBINPUT_SWITCH_TABLET_MODE:
82                 break;
83         default:
84                 /* Internal function only, so we can abort here */
85                 abort();
86         }
87
88         return dispatch->tablet_mode.sw.state ?
89                         LIBINPUT_SWITCH_STATE_ON :
90                         LIBINPUT_SWITCH_STATE_OFF;
91 }
92
93 static inline bool
94 post_button_scroll(struct evdev_device *device,
95                    struct device_float_coords raw,
96                    uint64_t time)
97 {
98         if (device->scroll.method != LIBINPUT_CONFIG_SCROLL_ON_BUTTON_DOWN)
99                 return false;
100
101         switch(device->scroll.button_scroll_state) {
102         case BUTTONSCROLL_IDLE:
103                 return false;
104         case BUTTONSCROLL_BUTTON_DOWN:
105                 /* if the button is down but scroll is not active, we're within the
106                    timeout where we swallow motion events but don't post
107                    scroll buttons */
108                 evdev_log_debug(device, "btnscroll: discarding\n");
109                 return true;
110         case BUTTONSCROLL_READY:
111                 device->scroll.button_scroll_state = BUTTONSCROLL_SCROLLING;
112                 _fallthrough_;
113         case BUTTONSCROLL_SCROLLING:
114                 {
115                 const struct normalized_coords normalized =
116                                 filter_dispatch_constant(device->pointer.filter,
117                                                          &raw,
118                                                          device,
119                                                          time);
120                 evdev_post_scroll(device, time,
121                                   LIBINPUT_POINTER_AXIS_SOURCE_CONTINUOUS,
122                                   &normalized);
123                 }
124                 return true;
125         }
126
127         assert(!"invalid scroll button state");
128 }
129
130 static inline bool
131 fallback_filter_defuzz_touch(struct fallback_dispatch *dispatch,
132                              struct evdev_device *device,
133                              struct mt_slot *slot)
134 {
135         struct device_coords point;
136
137         if (!dispatch->mt.want_hysteresis)
138                 return false;
139
140         point = evdev_hysteresis(&slot->point,
141                                  &slot->hysteresis_center,
142                                  &dispatch->mt.hysteresis_margin);
143         slot->point = point;
144
145         if (point.x == slot->hysteresis_center.x &&
146             point.y == slot->hysteresis_center.y)
147                 return true;
148
149         slot->hysteresis_center = point;
150
151         return false;
152 }
153
154 static inline void
155 fallback_rotate_relative(struct fallback_dispatch *dispatch,
156                          struct evdev_device *device)
157 {
158         struct device_coords rel = dispatch->rel;
159
160         if (!device->base.config.rotation)
161                 return;
162
163         /* loss of precision for non-90 degrees, but we only support 90 deg
164          * right now anyway */
165         matrix_mult_vec(&dispatch->rotation.matrix, &rel.x, &rel.y);
166
167         dispatch->rel = rel;
168 }
169
170 static void
171 fallback_flush_extra_aux_data(struct fallback_dispatch *dispatch,
172                                     struct evdev_device *device,
173                                     uint64_t time, int32_t type,
174                                     int32_t slot, int32_t seat_slot)
175 {
176         struct libinput_device *base = &device->base;
177         struct mt_aux_data *aux_data;
178
179         list_for_each(aux_data, &dispatch->mt.aux_data_list[slot], link) {
180                 if (aux_data->changed) {
181                         touch_notify_aux_data(base, time, slot, seat_slot, aux_data->code, aux_data->value);
182                         aux_data->changed = false;
183                 }
184         }
185 }
186
187 static void
188 fallback_flush_relative_motion(struct fallback_dispatch *dispatch,
189                                struct evdev_device *device,
190                                uint64_t time)
191 {
192         struct libinput_device *base = &device->base;
193         struct normalized_coords accel;
194         struct device_float_coords raw;
195
196         if (!(device->seat_caps & EVDEV_DEVICE_POINTER))
197                 return;
198
199         fallback_rotate_relative(dispatch, device);
200
201         raw.x = dispatch->rel.x;
202         raw.y = dispatch->rel.y;
203         dispatch->rel.x = 0;
204         dispatch->rel.y = 0;
205
206         /* Use unaccelerated deltas for pointing stick scroll */
207         if (post_button_scroll(device, raw, time))
208                 return;
209
210         if (device->pointer.filter) {
211                 /* Apply pointer acceleration. */
212                 accel = filter_dispatch(device->pointer.filter,
213                                         &raw,
214                                         device,
215                                         time);
216         } else {
217                 evdev_log_bug_libinput(device,
218                                        "accel filter missing\n");
219                 accel.x = accel.y = 0;
220         }
221
222         if (normalized_is_zero(accel))
223                 return;
224
225         pointer_notify_motion(base, time, &accel, &raw);
226 }
227
228 static void
229 fallback_flush_absolute_motion(struct fallback_dispatch *dispatch,
230                                struct evdev_device *device,
231                                uint64_t time)
232 {
233         struct libinput_device *base = &device->base;
234         struct device_coords point;
235
236         if (!(device->seat_caps & EVDEV_DEVICE_POINTER))
237                 return;
238
239         point = dispatch->abs.point;
240         evdev_transform_absolute(device, &point);
241
242         pointer_notify_motion_absolute(base, time, &point);
243 }
244
245 static bool
246 fallback_flush_mt_down(struct fallback_dispatch *dispatch,
247                        struct evdev_device *device,
248                        int slot_idx,
249                        uint64_t time)
250 {
251         struct libinput_device *base = &device->base;
252         struct libinput_seat *seat = base->seat;
253         struct device_coords point;
254         struct mt_slot *slot;
255         int seat_slot;
256
257         if (!(device->seat_caps & EVDEV_DEVICE_TOUCH))
258                 return false;
259
260         slot = &dispatch->mt.slots[slot_idx];
261         if (slot->seat_slot != -1) {
262                 evdev_log_bug_kernel(device,
263                                      "driver sent multiple touch down for the same slot");
264                 return false;
265         }
266
267         seat_slot = ffs(~seat->slot_map) - 1;
268         slot->seat_slot = seat_slot;
269
270         if (seat_slot == -1)
271                 return false;
272
273         seat->slot_map |= bit(seat_slot);
274         point = slot->point;
275         slot->hysteresis_center = point;
276         evdev_transform_absolute(device, &point);
277
278         fallback_flush_extra_aux_data(dispatch, device, time,
279                                 dispatch->pending_event, slot_idx, seat_slot);
280         touch_notify_touch_down(base, time, slot_idx, seat_slot,
281                                 &point, &slot->area, slot->pressure);
282
283         return true;
284 }
285
286 static bool
287 fallback_flush_mt_motion(struct fallback_dispatch *dispatch,
288                          struct evdev_device *device,
289                          int slot_idx,
290                          uint64_t time)
291 {
292         struct libinput_device *base = &device->base;
293         struct device_coords point;
294         struct mt_slot *slot;
295         int seat_slot;
296
297         if (!(device->seat_caps & EVDEV_DEVICE_TOUCH))
298                 return false;
299
300         slot = &dispatch->mt.slots[slot_idx];
301         seat_slot = slot->seat_slot;
302         point = slot->point;
303
304         if (seat_slot == -1)
305                 return false;
306
307         if (fallback_filter_defuzz_touch(dispatch, device, slot))
308                 return false;
309
310         evdev_transform_absolute(device, &point);
311
312         fallback_flush_extra_aux_data(dispatch, device, time,
313                                   dispatch->pending_event, slot_idx, seat_slot);
314         touch_notify_touch_motion(base, time, slot_idx, seat_slot,
315                                   &point, &slot->area, slot->pressure);
316
317         return true;
318 }
319
320 static bool
321 fallback_flush_mt_up(struct fallback_dispatch *dispatch,
322                      struct evdev_device *device,
323                      int slot_idx,
324                      uint64_t time)
325 {
326         struct libinput_device *base = &device->base;
327         struct libinput_seat *seat = base->seat;
328         struct mt_slot *slot;
329         int seat_slot;
330
331         if (!(device->seat_caps & EVDEV_DEVICE_TOUCH))
332                 return false;
333
334         slot = &dispatch->mt.slots[slot_idx];
335         seat_slot = slot->seat_slot;
336         slot->seat_slot = -1;
337
338         if (seat_slot == -1)
339                 return false;
340
341         seat->slot_map &= ~bit(seat_slot);
342
343         fallback_flush_extra_aux_data(dispatch, device, time,
344                                 dispatch->pending_event, slot_idx, seat_slot);
345         touch_notify_touch_up(base, time, slot_idx, seat_slot);
346
347         return true;
348 }
349
350 static bool
351 fallback_flush_mt_cancel(struct fallback_dispatch *dispatch,
352                          struct evdev_device *device,
353                          int slot_idx,
354                          uint64_t time)
355 {
356         struct libinput_device *base = &device->base;
357         struct libinput_seat *seat = base->seat;
358         struct mt_slot *slot;
359         int seat_slot;
360
361         if (!(device->seat_caps & EVDEV_DEVICE_TOUCH))
362                 return false;
363
364         slot = &dispatch->mt.slots[slot_idx];
365         seat_slot = slot->seat_slot;
366         slot->seat_slot = -1;
367
368         if (seat_slot == -1)
369                 return false;
370
371         seat->slot_map &= ~bit(seat_slot);
372
373         touch_notify_touch_cancel(base, time, slot_idx, seat_slot);
374
375         return true;
376 }
377
378 static bool
379 fallback_flush_st_down(struct fallback_dispatch *dispatch,
380                        struct evdev_device *device,
381                        uint64_t time)
382 {
383         struct libinput_device *base = &device->base;
384         struct libinput_seat *seat = base->seat;
385         struct device_coords point;
386         int seat_slot;
387         struct ellipse default_touch = {
388                 .major = DEFAULT_TOUCH_MAJOR,
389                 .minor = DEFAULT_TOUCH_MINOR,
390                 .orientation = DEFAULT_TOUCH_ORIENTATION
391         };
392
393         if (!(device->seat_caps & EVDEV_DEVICE_TOUCH))
394                 return false;
395
396         if (dispatch->abs.seat_slot != -1) {
397                 evdev_log_bug_kernel(device,
398                                      "driver sent multiple touch down for the same slot");
399                 return false;
400         }
401
402         seat_slot = ffs(~seat->slot_map) - 1;
403         dispatch->abs.seat_slot = seat_slot;
404
405         if (seat_slot == -1)
406                 return false;
407
408         seat->slot_map |= bit(seat_slot);
409
410         point = dispatch->abs.point;
411         evdev_transform_absolute(device, &point);
412
413         touch_notify_touch_down(base, time, -1, seat_slot, &point, &default_touch, DEFAULT_TOUCH_PRESSURE);
414
415         return true;
416 }
417
418 static bool
419 fallback_flush_st_motion(struct fallback_dispatch *dispatch,
420                          struct evdev_device *device,
421                          uint64_t time)
422 {
423         struct libinput_device *base = &device->base;
424         struct device_coords point;
425         int seat_slot;
426         struct ellipse default_touch = {
427                 .major = DEFAULT_TOUCH_MAJOR,
428                 .minor = DEFAULT_TOUCH_MINOR,
429                 .orientation = DEFAULT_TOUCH_ORIENTATION
430         };
431
432         point = dispatch->abs.point;
433         evdev_transform_absolute(device, &point);
434
435         seat_slot = dispatch->abs.seat_slot;
436
437         if (seat_slot == -1)
438                 return false;
439
440         touch_notify_touch_motion(base, time, -1, seat_slot, &point, &default_touch, DEFAULT_TOUCH_PRESSURE);
441
442         return true;
443 }
444
445 static bool
446 fallback_flush_st_up(struct fallback_dispatch *dispatch,
447                      struct evdev_device *device,
448                      uint64_t time)
449 {
450         struct libinput_device *base = &device->base;
451         struct libinput_seat *seat = base->seat;
452         int seat_slot;
453
454         if (!(device->seat_caps & EVDEV_DEVICE_TOUCH))
455                 return false;
456
457         seat_slot = dispatch->abs.seat_slot;
458         dispatch->abs.seat_slot = -1;
459
460         if (seat_slot == -1)
461                 return false;
462
463         seat->slot_map &= ~bit(seat_slot);
464
465         touch_notify_touch_up(base, time, -1, seat_slot);
466
467         return true;
468 }
469
470 static bool
471 fallback_flush_st_cancel(struct fallback_dispatch *dispatch,
472                          struct evdev_device *device,
473                          uint64_t time)
474 {
475         struct libinput_device *base = &device->base;
476         struct libinput_seat *seat = base->seat;
477         int seat_slot;
478
479         if (!(device->seat_caps & EVDEV_DEVICE_TOUCH))
480                 return false;
481
482         seat_slot = dispatch->abs.seat_slot;
483         dispatch->abs.seat_slot = -1;
484
485         if (seat_slot == -1)
486                 return false;
487
488         seat->slot_map &= ~bit(seat_slot);
489
490         touch_notify_touch_cancel(base, time, -1, seat_slot);
491
492         return true;
493 }
494
495 static void
496 fallback_process_touch_extra_aux_data(struct fallback_dispatch *dispatch,
497                     struct evdev_device *device,
498                     struct input_event *e)
499 {
500         struct mt_aux_data *aux_data;
501         struct list *current_axis_list;
502
503         if (!dispatch->mt.aux_data_list) return false;
504         if (dispatch->mt.slot < 0 || dispatch->mt.slot >= (int)dispatch->mt.slots_len)
505                 return false;
506
507         current_axis_list = &dispatch->mt.aux_data_list[dispatch->mt.slot];
508
509         if (list_empty(current_axis_list)) return false;
510
511         list_for_each(aux_data, current_axis_list, link) {
512                 if (aux_data->code == e->code) {
513                         if (aux_data->value != e->value) {
514                                 aux_data->changed = true;
515                                 aux_data->value = e->value;
516                         }
517                         break;
518                 }
519         }
520 }
521
522 static void
523 fallback_process_touch_button(struct fallback_dispatch *dispatch,
524                               struct evdev_device *device,
525                               uint64_t time, int value)
526 {
527         dispatch->pending_event |= (value) ?
528                                  EVDEV_ABSOLUTE_TOUCH_DOWN :
529                                  EVDEV_ABSOLUTE_TOUCH_UP;
530 }
531
532 static inline void
533 fallback_process_key(struct fallback_dispatch *dispatch,
534                      struct evdev_device *device,
535                      struct input_event *e, uint64_t time)
536 {
537         enum key_type type;
538
539         /* ignore kernel key repeat */
540         if (e->value == 2)
541                 return;
542
543         if (e->code == BTN_TOUCH) {
544                 if (!device->is_mt)
545                         fallback_process_touch_button(dispatch,
546                                                       device,
547                                                       time,
548                                                       e->value);
549                 return;
550         }
551
552         type = get_key_type(e->code);
553
554         /* Ignore key release events from the kernel for keys that libinput
555          * never got a pressed event for or key presses for keys that we
556          * think are still down */
557         switch (type) {
558         case KEY_TYPE_NONE:
559                 break;
560         case KEY_TYPE_KEY:
561         case KEY_TYPE_BUTTON:
562                 if ((e->value && hw_is_key_down(dispatch, e->code)) ||
563                     (e->value == 0 && !hw_is_key_down(dispatch, e->code))) {
564                         return;
565                 }
566
567                 dispatch->pending_event |= EVDEV_KEY;
568                 break;
569         }
570
571         hw_set_key_down(dispatch, e->code, e->value);
572
573         switch (type) {
574         case KEY_TYPE_NONE:
575                 break;
576         case KEY_TYPE_KEY:
577                 fallback_keyboard_notify_key(
578                              dispatch,
579                              device,
580                              time,
581                              e->code,
582                              e->value ? LIBINPUT_KEY_STATE_PRESSED :
583                                         LIBINPUT_KEY_STATE_RELEASED);
584                 break;
585         case KEY_TYPE_BUTTON:
586                 break;
587         }
588 }
589
590 static void
591 fallback_process_touch(struct fallback_dispatch *dispatch,
592                        struct evdev_device *device,
593                        struct input_event *e,
594                        uint64_t time)
595 {
596         struct mt_slot *slot = &dispatch->mt.slots[dispatch->mt.slot];
597
598         if (e->code == ABS_MT_SLOT) {
599                 if ((size_t)e->value >= dispatch->mt.slots_len) {
600                         evdev_log_bug_libinput(device,
601                                          "exceeded slot count (%d of max %zd)\n",
602                                          e->value,
603                                          dispatch->mt.slots_len);
604                         e->value = dispatch->mt.slots_len - 1;
605                 }
606                 dispatch->mt.slot = e->value;
607                 return;
608         }
609
610         switch (e->code) {
611         case ABS_MT_TRACKING_ID:
612                 if (e->value >= 0) {
613                         dispatch->pending_event |= EVDEV_ABSOLUTE_MT;
614                         slot->state = SLOT_STATE_BEGIN;
615                         if (dispatch->mt.has_palm) {
616                                 int v;
617                                 v = libevdev_get_slot_value(device->evdev,
618                                                             dispatch->mt.slot,
619                                                             ABS_MT_TOOL_TYPE);
620                                 switch (v) {
621                                 case MT_TOOL_PALM:
622                                         /* new touch, no cancel needed */
623                                         slot->palm_state = PALM_WAS_PALM;
624                                         break;
625                                 default:
626                                         slot->palm_state = PALM_NONE;
627                                         break;
628                                 }
629                         } else {
630                                 slot->palm_state = PALM_NONE;
631                         }
632                 } else {
633                         dispatch->pending_event |= EVDEV_ABSOLUTE_MT;
634                         slot->state = SLOT_STATE_END;
635                 }
636                 slot->dirty = true;
637                 break;
638         case ABS_MT_POSITION_X:
639                 evdev_device_check_abs_axis_range(device, e->code, e->value);
640                 dispatch->mt.slots[dispatch->mt.slot].point.x = e->value;
641                 dispatch->pending_event |= EVDEV_ABSOLUTE_MT;
642                 slot->dirty = true;
643                 break;
644         case ABS_MT_POSITION_Y:
645                 evdev_device_check_abs_axis_range(device, e->code, e->value);
646                 dispatch->mt.slots[dispatch->mt.slot].point.y = e->value;
647                 dispatch->pending_event |= EVDEV_ABSOLUTE_MT;
648                 slot->dirty = true;
649                 break;
650         case ABS_MT_TOOL_TYPE:
651                 /* The transitions matter - we (may) need to send a touch
652                  * cancel event if we just switched to a palm touch. And the
653                  * kernel may switch back to finger but we keep the touch as
654                  * palm - but then we need to reset correctly on a new touch
655                  * sequence.
656                  */
657                 switch (e->value) {
658                 case MT_TOOL_PALM:
659                         if (slot->palm_state == PALM_NONE)
660                                 slot->palm_state = PALM_NEW;
661                         break;
662                 default:
663                         if (slot->palm_state == PALM_IS_PALM)
664                                 slot->palm_state = PALM_WAS_PALM;
665                         break;
666                 }
667                 dispatch->pending_event |= EVDEV_ABSOLUTE_MT;
668                 slot->dirty = true;
669                 break;
670         case ABS_MT_TOUCH_MAJOR:
671                 dispatch->mt.slots[dispatch->mt.slot].area.major = e->value;
672                 if (dispatch->pending_event == EVDEV_NONE)
673                         dispatch->pending_event = EVDEV_ABSOLUTE_MT;
674                 break;
675         case ABS_MT_TOUCH_MINOR:
676                 dispatch->mt.slots[dispatch->mt.slot].area.minor = e->value;
677                 if (dispatch->pending_event == EVDEV_NONE)
678                         dispatch->pending_event = EVDEV_ABSOLUTE_MT;
679                 break;
680         case ABS_MT_ORIENTATION:
681                 dispatch->mt.slots[dispatch->mt.slot].area.orientation = e->value;
682                 if (dispatch->pending_event == EVDEV_NONE)
683                         dispatch->pending_event = EVDEV_ABSOLUTE_MT;
684                 break;
685         default:
686                 fallback_process_touch_extra_aux_data(dispatch, device, e);
687                 break;
688         }
689 }
690
691 static inline void
692 fallback_process_absolute_motion(struct fallback_dispatch *dispatch,
693                                  struct evdev_device *device,
694                                  struct input_event *e)
695 {
696         switch (e->code) {
697         case ABS_X:
698                 evdev_device_check_abs_axis_range(device, e->code, e->value);
699                 dispatch->abs.point.x = e->value;
700                 dispatch->pending_event |= EVDEV_ABSOLUTE_MOTION;
701                 break;
702         case ABS_Y:
703                 evdev_device_check_abs_axis_range(device, e->code, e->value);
704                 dispatch->abs.point.y = e->value;
705                 dispatch->pending_event |= EVDEV_ABSOLUTE_MOTION;
706                 break;
707         }
708 }
709
710 static void
711 fallback_lid_keyboard_event(uint64_t time,
712                             struct libinput_event *event,
713                             void *data)
714 {
715         struct fallback_dispatch *dispatch = fallback_dispatch(data);
716
717         if (!dispatch->lid.is_closed)
718                 return;
719
720         if (event->type != LIBINPUT_EVENT_KEYBOARD_KEY)
721                 return;
722
723         if (dispatch->lid.reliability == RELIABILITY_WRITE_OPEN) {
724                 int fd = libevdev_get_fd(dispatch->device->evdev);
725                 int rc;
726                 struct input_event ev[2];
727
728                 ev[0] = input_event_init(0, EV_SW, SW_LID, 0);
729                 ev[1] = input_event_init(0, EV_SYN, SYN_REPORT, 0);
730
731                 rc = write(fd, ev, sizeof(ev));
732
733                 if (rc < 0)
734                         evdev_log_error(dispatch->device,
735                                         "failed to write SW_LID state (%s)",
736                                         strerror(errno));
737
738                 /* In case write() fails, we sync the lid state manually
739                  * regardless. */
740         }
741
742         /* Posting the event here means we preempt the keyboard events that
743          * caused us to wake up, so the lid event is always passed on before
744          * the key event.
745          */
746         dispatch->lid.is_closed = false;
747         fallback_lid_notify_toggle(dispatch, dispatch->device, time);
748 }
749
750 static void
751 fallback_lid_toggle_keyboard_listener(struct fallback_dispatch *dispatch,
752                                       struct evdev_paired_keyboard *kbd,
753                                       bool is_closed)
754 {
755         assert(kbd->device);
756
757         libinput_device_remove_event_listener(&kbd->listener);
758
759         if (is_closed) {
760                 libinput_device_add_event_listener(
761                                         &kbd->device->base,
762                                         &kbd->listener,
763                                         fallback_lid_keyboard_event,
764                                         dispatch);
765         } else {
766                 libinput_device_init_event_listener(&kbd->listener);
767         }
768 }
769
770 static void
771 fallback_lid_toggle_keyboard_listeners(struct fallback_dispatch *dispatch,
772                                        bool is_closed)
773 {
774         struct evdev_paired_keyboard *kbd;
775
776         list_for_each(kbd, &dispatch->lid.paired_keyboard_list, link) {
777                 if (!kbd->device)
778                         continue;
779
780                 fallback_lid_toggle_keyboard_listener(dispatch,
781                                                       kbd,
782                                                       is_closed);
783         }
784 }
785
786 static inline void
787 fallback_process_switch(struct fallback_dispatch *dispatch,
788                         struct evdev_device *device,
789                         struct input_event *e,
790                         uint64_t time)
791 {
792         enum libinput_switch_state state;
793         bool is_closed;
794
795         /* TODO: this should to move to handle_state */
796
797         switch (e->code) {
798         case SW_LID:
799                 is_closed = !!e->value;
800
801                 fallback_lid_toggle_keyboard_listeners(dispatch, is_closed);
802
803                 if (dispatch->lid.is_closed == is_closed)
804                         return;
805
806                 dispatch->lid.is_closed = is_closed;
807                 fallback_lid_notify_toggle(dispatch, device, time);
808                 break;
809         case SW_TABLET_MODE:
810                 if (dispatch->tablet_mode.sw.state == e->value)
811                         return;
812
813                 dispatch->tablet_mode.sw.state = e->value;
814                 if (e->value)
815                         state = LIBINPUT_SWITCH_STATE_ON;
816                 else
817                         state = LIBINPUT_SWITCH_STATE_OFF;
818                 switch_notify_toggle(&device->base,
819                                      time,
820                                      LIBINPUT_SWITCH_TABLET_MODE,
821                                      state);
822                 break;
823         }
824 }
825
826 static inline bool
827 fallback_reject_relative(struct evdev_device *device,
828                          const struct input_event *e,
829                          uint64_t time)
830 {
831         if ((e->code == REL_X || e->code == REL_Y) &&
832             (device->seat_caps & EVDEV_DEVICE_POINTER) == 0) {
833                 evdev_log_bug_libinput_ratelimit(device,
834                                                  &device->nonpointer_rel_limit,
835                                                  "REL_X/Y from a non-pointer device\n");
836                 return true;
837         }
838
839         return false;
840 }
841
842 static inline void
843 fallback_process_relative(struct fallback_dispatch *dispatch,
844                           struct evdev_device *device,
845                           struct input_event *e, uint64_t time)
846 {
847         if (fallback_reject_relative(device, e, time))
848                 return;
849
850         switch (e->code) {
851         case REL_X:
852                 dispatch->rel.x += e->value;
853                 dispatch->pending_event |= EVDEV_RELATIVE_MOTION;
854                 break;
855         case REL_Y:
856                 dispatch->rel.y += e->value;
857                 dispatch->pending_event |= EVDEV_RELATIVE_MOTION;
858                 break;
859         }
860
861         fallback_wheel_process_relative(dispatch, device, e, time);
862 }
863
864 static inline void
865 fallback_process_absolute(struct fallback_dispatch *dispatch,
866                           struct evdev_device *device,
867                           struct input_event *e,
868                           uint64_t time)
869 {
870         if (device->is_mt) {
871                 fallback_process_touch(dispatch, device, e, time);
872         } else {
873                 fallback_process_absolute_motion(dispatch, device, e);
874         }
875 }
876
877 static inline bool
878 fallback_any_button_down(struct fallback_dispatch *dispatch,
879                       struct evdev_device *device)
880 {
881         unsigned int button;
882
883         for (button = BTN_LEFT; button < BTN_JOYSTICK; button++) {
884                 if (libevdev_has_event_code(device->evdev, EV_KEY, button) &&
885                     hw_is_key_down(dispatch, button))
886                         return true;
887         }
888         return false;
889 }
890
891 static inline bool
892 fallback_arbitrate_touch(struct fallback_dispatch *dispatch,
893                          struct mt_slot *slot)
894 {
895         bool discard = false;
896
897         if (dispatch->arbitration.state == ARBITRATION_IGNORE_RECT &&
898             point_in_rect(&slot->point, &dispatch->arbitration.rect)) {
899                 slot->palm_state = PALM_IS_PALM;
900                 discard = true;
901         }
902
903         return discard;
904 }
905
906 static inline bool
907 fallback_flush_mt_events(struct fallback_dispatch *dispatch,
908                          struct evdev_device *device,
909                          uint64_t time)
910 {
911         bool sent = false;
912
913         for (size_t i = 0; i < dispatch->mt.slots_len; i++) {
914                 struct mt_slot *slot = &dispatch->mt.slots[i];
915
916                 if (!slot->dirty)
917                         continue;
918
919                 slot->dirty = false;
920
921                 /* Any palm state other than PALM_NEW means we've either
922                  * already cancelled the touch or the touch was never
923                  * a finger anyway and we didn't send the begin.
924                  */
925                 if (slot->palm_state == PALM_NEW) {
926                         if (slot->state != SLOT_STATE_BEGIN)
927                                 sent = fallback_flush_mt_cancel(dispatch,
928                                                                 device,
929                                                                 i,
930                                                                 time);
931                         slot->palm_state = PALM_IS_PALM;
932                 } else if (slot->palm_state == PALM_NONE) {
933                         switch (slot->state) {
934                         case SLOT_STATE_BEGIN:
935                                 if (!fallback_arbitrate_touch(dispatch,
936                                                              slot)) {
937                                         sent = fallback_flush_mt_down(dispatch,
938                                                                       device,
939                                                                       i,
940                                                                       time);
941                                 }
942                                 break;
943                         case SLOT_STATE_UPDATE:
944                                 sent = fallback_flush_mt_motion(dispatch,
945                                                                 device,
946                                                                 i,
947                                                                 time);
948                                 break;
949                         case SLOT_STATE_END:
950                                 sent = fallback_flush_mt_up(dispatch,
951                                                             device,
952                                                             i,
953                                                             time);
954                                 break;
955                         case SLOT_STATE_NONE:
956                                 break;
957                         }
958                 }
959
960                 /* State machine continues independent of the palm state */
961                 switch (slot->state) {
962                 case SLOT_STATE_BEGIN:
963                         slot->state = SLOT_STATE_UPDATE;
964                         break;
965                 case SLOT_STATE_UPDATE:
966                         break;
967                 case SLOT_STATE_END:
968                         slot->state = SLOT_STATE_NONE;
969                         break;
970                 case SLOT_STATE_NONE:
971                         /* touch arbitration may swallow the begin,
972                          * so we may get updates for a touch still
973                          * in NONE state */
974                         break;
975                 }
976         }
977
978         return sent;
979 }
980
981 static void
982 fallback_handle_state(struct fallback_dispatch *dispatch,
983                       struct evdev_device *device,
984                       uint64_t time)
985 {
986         bool need_touch_frame = false;
987
988         /* Relative motion */
989         if (dispatch->pending_event & EVDEV_RELATIVE_MOTION)
990                 fallback_flush_relative_motion(dispatch, device, time);
991
992         /* Single touch or absolute pointer devices */
993         if (dispatch->pending_event & EVDEV_ABSOLUTE_TOUCH_DOWN) {
994                 if (fallback_flush_st_down(dispatch, device, time))
995                         need_touch_frame = true;
996         } else if (dispatch->pending_event & EVDEV_ABSOLUTE_MOTION) {
997                 if (device->seat_caps & EVDEV_DEVICE_TOUCH) {
998                         if (fallback_flush_st_motion(dispatch,
999                                                      device,
1000                                                      time))
1001                                 need_touch_frame = true;
1002                 } else if (device->seat_caps & EVDEV_DEVICE_POINTER) {
1003                         fallback_flush_absolute_motion(dispatch,
1004                                                        device,
1005                                                        time);
1006                 }
1007         }
1008
1009         if (dispatch->pending_event & EVDEV_ABSOLUTE_TOUCH_UP) {
1010                 if (fallback_flush_st_up(dispatch, device, time))
1011                         need_touch_frame = true;
1012         }
1013
1014         /* Multitouch devices */
1015         if (dispatch->pending_event & EVDEV_ABSOLUTE_MT)
1016                 need_touch_frame = fallback_flush_mt_events(dispatch,
1017                                                             device,
1018                                                             time);
1019
1020         if (need_touch_frame)
1021                 touch_notify_frame(&device->base, time);
1022
1023         fallback_wheel_handle_state(dispatch, device, time);
1024
1025         /* Buttons and keys */
1026         if (dispatch->pending_event & EVDEV_KEY) {
1027                 bool want_debounce = false;
1028                 for (unsigned int code = 0; code <= KEY_MAX; code++) {
1029                         if (!hw_key_has_changed(dispatch, code))
1030                                 continue;
1031
1032                         if (get_key_type(code) == KEY_TYPE_BUTTON) {
1033                                 want_debounce = true;
1034                                 break;
1035                         }
1036                 }
1037
1038                 if (want_debounce)
1039                         fallback_debounce_handle_state(dispatch, time);
1040
1041                 hw_key_update_last_state(dispatch);
1042         }
1043
1044         dispatch->pending_event = EVDEV_NONE;
1045 }
1046
1047 static void
1048 fallback_interface_process(struct evdev_dispatch *evdev_dispatch,
1049                            struct evdev_device *device,
1050                            struct input_event *event,
1051                            uint64_t time)
1052 {
1053         struct fallback_dispatch *dispatch = fallback_dispatch(evdev_dispatch);
1054
1055         if (dispatch->arbitration.in_arbitration)
1056                 return;
1057
1058         switch (event->type) {
1059         case EV_REL:
1060                 fallback_process_relative(dispatch, device, event, time);
1061                 break;
1062         case EV_ABS:
1063                 fallback_process_absolute(dispatch, device, event, time);
1064                 break;
1065         case EV_KEY:
1066                 fallback_process_key(dispatch, device, event, time);
1067                 break;
1068         case EV_SW:
1069                 fallback_process_switch(dispatch, device, event, time);
1070                 break;
1071         case EV_SYN:
1072                 fallback_handle_state(dispatch, device, time);
1073                 break;
1074         }
1075 }
1076
1077 static void
1078 cancel_touches(struct fallback_dispatch *dispatch,
1079                struct evdev_device *device,
1080                const struct device_coord_rect *rect,
1081                uint64_t time)
1082 {
1083         unsigned int idx;
1084         bool need_frame = false;
1085
1086         if (!rect || point_in_rect(&dispatch->abs.point, rect))
1087                 need_frame = fallback_flush_st_cancel(dispatch,
1088                                                       device,
1089                                                       time);
1090
1091         for (idx = 0; idx < dispatch->mt.slots_len; idx++) {
1092                 struct mt_slot *slot = &dispatch->mt.slots[idx];
1093
1094                 if (slot->seat_slot == -1)
1095                         continue;
1096
1097                 if ((!rect || point_in_rect(&slot->point, rect)) &&
1098                     fallback_flush_mt_cancel(dispatch, device, idx, time))
1099                         need_frame = true;
1100         }
1101
1102         if (need_frame)
1103                 touch_notify_frame(&device->base, time);
1104 }
1105
1106 static void
1107 release_pressed_keys(struct fallback_dispatch *dispatch,
1108                      struct evdev_device *device,
1109                      uint64_t time)
1110 {
1111         int code;
1112
1113         for (code = 0; code < KEY_CNT; code++) {
1114                 int count = get_key_down_count(device, code);
1115
1116                 if (count == 0)
1117                         continue;
1118
1119                 if (count > 1) {
1120                         evdev_log_bug_libinput(device,
1121                                                "key %d is down %d times.\n",
1122                                                code,
1123                                                count);
1124                 }
1125
1126                 switch (get_key_type(code)) {
1127                 case KEY_TYPE_NONE:
1128                         break;
1129                 case KEY_TYPE_KEY:
1130                         fallback_keyboard_notify_key(
1131                                 dispatch,
1132                                 device,
1133                                 time,
1134                                 code,
1135                                 LIBINPUT_KEY_STATE_RELEASED);
1136                         break;
1137                 case KEY_TYPE_BUTTON:
1138                         evdev_pointer_notify_button(
1139                                 device,
1140                                 time,
1141                                 evdev_to_left_handed(device, code),
1142                                 LIBINPUT_BUTTON_STATE_RELEASED);
1143                         break;
1144                 }
1145
1146                 count = get_key_down_count(device, code);
1147                 if (count != 0) {
1148                         evdev_log_bug_libinput(device,
1149                                                "releasing key %d failed.\n",
1150                                                code);
1151                         break;
1152                 }
1153         }
1154 }
1155
1156 static void
1157 fallback_return_to_neutral_state(struct fallback_dispatch *dispatch,
1158                                  struct evdev_device *device)
1159 {
1160         struct libinput *libinput = evdev_libinput_context(device);
1161         uint64_t time;
1162
1163         if ((time = libinput_now(libinput)) == 0)
1164                 return;
1165
1166         cancel_touches(dispatch, device, NULL, time);
1167         release_pressed_keys(dispatch, device, time);
1168         memset(dispatch->hw_key_mask, 0, sizeof(dispatch->hw_key_mask));
1169         memset(dispatch->hw_key_mask, 0, sizeof(dispatch->last_hw_key_mask));
1170 }
1171
1172 static void
1173 fallback_interface_suspend(struct evdev_dispatch *evdev_dispatch,
1174                            struct evdev_device *device)
1175 {
1176         struct fallback_dispatch *dispatch = fallback_dispatch(evdev_dispatch);
1177
1178         fallback_return_to_neutral_state(dispatch, device);
1179 }
1180
1181 static void
1182 fallback_interface_remove(struct evdev_dispatch *evdev_dispatch)
1183 {
1184         struct fallback_dispatch *dispatch = fallback_dispatch(evdev_dispatch);
1185         struct evdev_paired_keyboard *kbd;
1186
1187         libinput_timer_cancel(&dispatch->wheel.scroll_timer);
1188         libinput_timer_cancel(&dispatch->debounce.timer);
1189         libinput_timer_cancel(&dispatch->debounce.timer_short);
1190         libinput_timer_cancel(&dispatch->arbitration.arbitration_timer);
1191
1192         libinput_device_remove_event_listener(&dispatch->tablet_mode.other.listener);
1193
1194         list_for_each_safe(kbd,
1195                            &dispatch->lid.paired_keyboard_list,
1196                            link) {
1197                 evdev_paired_keyboard_destroy(kbd);
1198         }
1199 }
1200
1201 static void
1202 fallback_interface_sync_initial_state(struct evdev_device *device,
1203                                       struct evdev_dispatch *evdev_dispatch)
1204 {
1205         struct fallback_dispatch *dispatch = fallback_dispatch(evdev_dispatch);
1206         uint64_t time = libinput_now(evdev_libinput_context(device));
1207
1208         if (device->tags & EVDEV_TAG_LID_SWITCH) {
1209                 struct libevdev *evdev = device->evdev;
1210
1211                 dispatch->lid.is_closed = libevdev_get_event_value(evdev,
1212                                                                    EV_SW,
1213                                                                    SW_LID);
1214                 dispatch->lid.is_closed_client_state = false;
1215
1216                 /* For the initial state sync, we depend on whether the lid switch
1217                  * is reliable. If we know it's reliable, we sync as expected.
1218                  * If we're not sure, we ignore the initial state and only sync on
1219                  * the first future lid close event. Laptops with a broken switch
1220                  * that always have the switch in 'on' state thus don't mess up our
1221                  * touchpad.
1222                  */
1223                 if (dispatch->lid.is_closed &&
1224                     dispatch->lid.reliability == RELIABILITY_RELIABLE) {
1225                         fallback_lid_notify_toggle(dispatch, device, time);
1226                 }
1227         }
1228
1229         if (dispatch->tablet_mode.sw.state) {
1230                 switch_notify_toggle(&device->base,
1231                                      time,
1232                                      LIBINPUT_SWITCH_TABLET_MODE,
1233                                      LIBINPUT_SWITCH_STATE_ON);
1234         }
1235 }
1236
1237 static void
1238 fallback_interface_update_rect(struct evdev_dispatch *evdev_dispatch,
1239                                struct evdev_device *device,
1240                                 const struct phys_rect *phys_rect,
1241                                 uint64_t time)
1242 {
1243         struct fallback_dispatch *dispatch = fallback_dispatch(evdev_dispatch);
1244         struct device_coord_rect rect;
1245
1246         assert(phys_rect);
1247
1248         /* Existing touches do not change, we just update the rect and only
1249          * new touches in these areas will be ignored. If you want to paint
1250          * over your finger, be my guest. */
1251         rect = evdev_phys_rect_to_units(device, phys_rect);
1252         dispatch->arbitration.rect = rect;
1253 }
1254
1255 static void
1256 fallback_interface_toggle_touch(struct evdev_dispatch *evdev_dispatch,
1257                                 struct evdev_device *device,
1258                                 enum evdev_arbitration_state which,
1259                                 const struct phys_rect *phys_rect,
1260                                 uint64_t time)
1261 {
1262         struct fallback_dispatch *dispatch = fallback_dispatch(evdev_dispatch);
1263         struct device_coord_rect rect = {0};
1264
1265         if (which == dispatch->arbitration.state)
1266                 return;
1267
1268         switch (which) {
1269         case ARBITRATION_NOT_ACTIVE:
1270                 /* if in-kernel arbitration is in use and there is a touch
1271                  * and a pen in proximity, lifting the pen out of proximity
1272                  * causes a touch begin for the touch. On a hand-lift the
1273                  * proximity out precedes the touch up by a few ms, so we
1274                  * get what looks like a tap. Fix this by delaying
1275                  * arbitration by just a little bit so that any touch in
1276                  * event is caught as palm touch. */
1277                 libinput_timer_set(&dispatch->arbitration.arbitration_timer,
1278                                    time + ms2us(90));
1279                 break;
1280         case ARBITRATION_IGNORE_RECT:
1281                 assert(phys_rect);
1282                 rect = evdev_phys_rect_to_units(device, phys_rect);
1283                 cancel_touches(dispatch, device, &rect, time);
1284                 dispatch->arbitration.rect = rect;
1285                 break;
1286         case ARBITRATION_IGNORE_ALL:
1287                 libinput_timer_cancel(&dispatch->arbitration.arbitration_timer);
1288                 fallback_return_to_neutral_state(dispatch, device);
1289                 dispatch->arbitration.in_arbitration = true;
1290                 break;
1291         }
1292
1293         dispatch->arbitration.state = which;
1294 }
1295
1296 static void
1297 fallback_interface_destroy(struct evdev_dispatch *evdev_dispatch)
1298 {
1299         struct fallback_dispatch *dispatch = fallback_dispatch(evdev_dispatch);
1300
1301         libinput_timer_destroy(&dispatch->wheel.scroll_timer);
1302         libinput_timer_destroy(&dispatch->arbitration.arbitration_timer);
1303         libinput_timer_destroy(&dispatch->debounce.timer);
1304         libinput_timer_destroy(&dispatch->debounce.timer_short);
1305
1306         free(dispatch->mt.slots);
1307         free(dispatch);
1308 }
1309
1310 static void
1311 fallback_lid_pair_keyboard(struct evdev_device *lid_switch,
1312                            struct evdev_device *keyboard)
1313 {
1314         struct fallback_dispatch *dispatch =
1315                 fallback_dispatch(lid_switch->dispatch);
1316         struct evdev_paired_keyboard *kbd;
1317         size_t count = 0;
1318
1319         if ((keyboard->tags & EVDEV_TAG_KEYBOARD) == 0 ||
1320             (lid_switch->tags & EVDEV_TAG_LID_SWITCH) == 0)
1321                 return;
1322
1323         if ((keyboard->tags & EVDEV_TAG_INTERNAL_KEYBOARD) == 0)
1324                 return;
1325
1326         list_for_each(kbd, &dispatch->lid.paired_keyboard_list, link) {
1327                 count++;
1328                 if (count > 3) {
1329                         evdev_log_info(lid_switch,
1330                                        "lid: too many internal keyboards\n");
1331                         break;
1332                 }
1333         }
1334
1335         kbd = zalloc(sizeof(*kbd));
1336         kbd->device = keyboard;
1337         libinput_device_init_event_listener(&kbd->listener);
1338         list_insert(&dispatch->lid.paired_keyboard_list, &kbd->link);
1339         evdev_log_debug(lid_switch,
1340                         "lid: keyboard paired with %s<->%s\n",
1341                         lid_switch->devname,
1342                         keyboard->devname);
1343
1344         /* We need to init the event listener now only if the
1345          * reported state is closed. */
1346         if (dispatch->lid.is_closed)
1347                 fallback_lid_toggle_keyboard_listener(dispatch,
1348                                                       kbd,
1349                                                       dispatch->lid.is_closed);
1350 }
1351
1352 static void
1353 fallback_resume(struct fallback_dispatch *dispatch,
1354                 struct evdev_device *device)
1355 {
1356         if (dispatch->base.sendevents.current_mode ==
1357             LIBINPUT_CONFIG_SEND_EVENTS_DISABLED)
1358                 return;
1359
1360         evdev_device_resume(device);
1361 }
1362
1363 static void
1364 fallback_suspend(struct fallback_dispatch *dispatch,
1365                  struct evdev_device *device)
1366 {
1367         evdev_device_suspend(device);
1368 }
1369
1370 static void
1371 fallback_tablet_mode_switch_event(uint64_t time,
1372                                   struct libinput_event *event,
1373                                   void *data)
1374 {
1375         struct fallback_dispatch *dispatch = data;
1376         struct evdev_device *device = dispatch->device;
1377         struct libinput_event_switch *swev;
1378
1379         if (libinput_event_get_type(event) != LIBINPUT_EVENT_SWITCH_TOGGLE)
1380                 return;
1381
1382         swev = libinput_event_get_switch_event(event);
1383         if (libinput_event_switch_get_switch(swev) !=
1384             LIBINPUT_SWITCH_TABLET_MODE)
1385                 return;
1386
1387         switch (libinput_event_switch_get_switch_state(swev)) {
1388         case LIBINPUT_SWITCH_STATE_OFF:
1389                 fallback_resume(dispatch, device);
1390                 evdev_log_debug(device, "tablet-mode: resuming device\n");
1391                 break;
1392         case LIBINPUT_SWITCH_STATE_ON:
1393                 fallback_suspend(dispatch, device);
1394                 evdev_log_debug(device, "tablet-mode: suspending device\n");
1395                 break;
1396         }
1397 }
1398
1399 static void
1400 fallback_pair_tablet_mode(struct evdev_device *keyboard,
1401                           struct evdev_device *tablet_mode_switch)
1402 {
1403         struct fallback_dispatch *dispatch =
1404                 fallback_dispatch(keyboard->dispatch);
1405
1406         if ((keyboard->tags & EVDEV_TAG_EXTERNAL_KEYBOARD))
1407                 return;
1408
1409         if ((keyboard->tags & EVDEV_TAG_TRACKPOINT)) {
1410                 if (keyboard->tags & EVDEV_TAG_EXTERNAL_MOUSE)
1411                         return;
1412         /* This filters out all internal keyboard-like devices (Video
1413          * Switch) */
1414         } else if ((keyboard->tags & EVDEV_TAG_INTERNAL_KEYBOARD) == 0) {
1415                 return;
1416         }
1417
1418         if (evdev_device_has_model_quirk(keyboard,
1419                                          QUIRK_MODEL_TABLET_MODE_NO_SUSPEND))
1420                 return;
1421
1422         if ((tablet_mode_switch->tags & EVDEV_TAG_TABLET_MODE_SWITCH) == 0)
1423                 return;
1424
1425         if (dispatch->tablet_mode.other.sw_device)
1426                 return;
1427
1428         evdev_log_debug(keyboard,
1429                         "tablet-mode: paired %s<->%s\n",
1430                         keyboard->devname,
1431                         tablet_mode_switch->devname);
1432
1433         libinput_device_add_event_listener(&tablet_mode_switch->base,
1434                                 &dispatch->tablet_mode.other.listener,
1435                                 fallback_tablet_mode_switch_event,
1436                                 dispatch);
1437         dispatch->tablet_mode.other.sw_device = tablet_mode_switch;
1438
1439         if (evdev_device_switch_get_state(tablet_mode_switch,
1440                                           LIBINPUT_SWITCH_TABLET_MODE)
1441                     == LIBINPUT_SWITCH_STATE_ON) {
1442                 evdev_log_debug(keyboard, "tablet-mode: suspending device\n");
1443                 fallback_suspend(dispatch, keyboard);
1444         }
1445 }
1446
1447 static void
1448 fallback_interface_device_added(struct evdev_device *device,
1449                                 struct evdev_device *added_device)
1450 {
1451         fallback_lid_pair_keyboard(device, added_device);
1452         fallback_pair_tablet_mode(device, added_device);
1453 }
1454
1455 static void
1456 fallback_interface_device_removed(struct evdev_device *device,
1457                                   struct evdev_device *removed_device)
1458 {
1459         struct fallback_dispatch *dispatch =
1460                         fallback_dispatch(device->dispatch);
1461         struct evdev_paired_keyboard *kbd;
1462
1463         list_for_each_safe(kbd,
1464                            &dispatch->lid.paired_keyboard_list,
1465                            link) {
1466                 if (!kbd->device)
1467                         continue;
1468
1469                 if (kbd->device != removed_device)
1470                         continue;
1471
1472                 evdev_paired_keyboard_destroy(kbd);
1473         }
1474
1475         if (removed_device == dispatch->tablet_mode.other.sw_device) {
1476                 libinput_device_remove_event_listener(
1477                                 &dispatch->tablet_mode.other.listener);
1478                 libinput_device_init_event_listener(
1479                                 &dispatch->tablet_mode.other.listener);
1480                 dispatch->tablet_mode.other.sw_device = NULL;
1481         }
1482 }
1483
1484 struct evdev_dispatch_interface fallback_interface = {
1485         .process = fallback_interface_process,
1486         .suspend = fallback_interface_suspend,
1487         .remove = fallback_interface_remove,
1488         .destroy = fallback_interface_destroy,
1489         .device_added = fallback_interface_device_added,
1490         .device_removed = fallback_interface_device_removed,
1491         .device_suspended = fallback_interface_device_removed, /* treat as remove */
1492         .device_resumed = fallback_interface_device_added,   /* treat as add */
1493         .post_added = fallback_interface_sync_initial_state,
1494         .touch_arbitration_toggle = fallback_interface_toggle_touch,
1495         .touch_arbitration_update_rect = fallback_interface_update_rect,
1496         .get_switch_state = fallback_interface_get_switch_state,
1497 };
1498
1499 static void
1500 fallback_device_interface_set_aux_data(struct evdev_dispatch *evdev_dispatch, uint32_t code)
1501 {
1502         int i;
1503         struct fallback_dispatch *dispatch;
1504         struct mt_aux_data *aux_data;
1505
1506         dispatch = fallback_dispatch(evdev_dispatch);
1507
1508         if (!list_empty(&dispatch->mt.aux_data_list[0])) {
1509                 list_for_each(aux_data, &dispatch->mt.aux_data_list[0], link) {
1510                         if (code == aux_data->code) return;
1511                 }
1512         }
1513
1514         for (i = 0; i < (int)dispatch->mt.slots_len; i++) {
1515                 aux_data = calloc(1, sizeof(struct mt_aux_data));
1516                 if (!aux_data) goto failed;
1517                 aux_data->code = code;
1518                 list_insert(&dispatch->mt.aux_data_list[i], &aux_data->link);
1519         }
1520
1521         return;
1522 failed:
1523         for (i = i-1; i >= 0; i--) {
1524                 list_for_each_safe(aux_data, &dispatch->mt.aux_data_list[i], link) {
1525                         list_remove(&aux_data->link);
1526                         free(aux_data);
1527                 }
1528         }
1529 }
1530
1531 static void
1532 fallback_device_interface_free_aux_data(struct evdev_dispatch *evdev_dispatch)
1533 {
1534         int i;
1535         struct fallback_dispatch *dispatch;
1536         struct mt_aux_data *aux_data;
1537
1538         dispatch = fallback_dispatch(evdev_dispatch);
1539
1540         for (i = 0; i < (int)dispatch->mt.slots_len; i++) {
1541                 list_for_each_safe(aux_data, &dispatch->mt.aux_data_list[i], link) {
1542                         list_remove(&aux_data->link);
1543                         free(aux_data);
1544                 }
1545                 list_remove(&dispatch->mt.aux_data_list[i]);
1546         }
1547         free(dispatch->mt.aux_data_list);
1548 }
1549
1550 struct evdev_dispatch_device_interface fallback_device_interface = {
1551         .set_aux_data = fallback_device_interface_set_aux_data
1552 };
1553
1554 static void
1555 fallback_change_to_left_handed(struct evdev_device *device)
1556 {
1557         struct fallback_dispatch *dispatch = fallback_dispatch(device->dispatch);
1558
1559         if (device->left_handed.want_enabled == device->left_handed.enabled)
1560                 return;
1561
1562         if (fallback_any_button_down(dispatch, device))
1563                 return;
1564
1565         device->left_handed.enabled = device->left_handed.want_enabled;
1566 }
1567
1568 static void
1569 fallback_change_scroll_method(struct evdev_device *device)
1570 {
1571         struct fallback_dispatch *dispatch = fallback_dispatch(device->dispatch);
1572
1573         if (device->scroll.want_method == device->scroll.method &&
1574             device->scroll.want_button == device->scroll.button &&
1575             device->scroll.want_lock_enabled == device->scroll.lock_enabled)
1576                 return;
1577
1578         if (fallback_any_button_down(dispatch, device))
1579                 return;
1580
1581         device->scroll.method = device->scroll.want_method;
1582         device->scroll.button = device->scroll.want_button;
1583         device->scroll.lock_enabled = device->scroll.want_lock_enabled;
1584         evdev_set_button_scroll_lock_enabled(device, device->scroll.lock_enabled);
1585 }
1586
1587 static int
1588 fallback_rotation_config_is_available(struct libinput_device *device)
1589 {
1590         /* This function only gets called when we support rotation */
1591         return 1;
1592 }
1593
1594 static enum libinput_config_status
1595 fallback_rotation_config_set_angle(struct libinput_device *libinput_device,
1596                                 unsigned int degrees_cw)
1597 {
1598         struct evdev_device *device = evdev_device(libinput_device);
1599         struct fallback_dispatch *dispatch = fallback_dispatch(device->dispatch);
1600
1601         dispatch->rotation.angle = degrees_cw;
1602         matrix_init_rotate(&dispatch->rotation.matrix, degrees_cw);
1603
1604         return LIBINPUT_CONFIG_STATUS_SUCCESS;
1605 }
1606
1607 static unsigned int
1608 fallback_rotation_config_get_angle(struct libinput_device *libinput_device)
1609 {
1610         struct evdev_device *device = evdev_device(libinput_device);
1611         struct fallback_dispatch *dispatch = fallback_dispatch(device->dispatch);
1612
1613         return dispatch->rotation.angle;
1614 }
1615
1616 static unsigned int
1617 fallback_rotation_config_get_default_angle(struct libinput_device *device)
1618 {
1619         return 0;
1620 }
1621
1622 static void
1623 fallback_init_rotation(struct fallback_dispatch *dispatch,
1624                        struct evdev_device *device)
1625 {
1626         if ((device->model_flags & EVDEV_MODEL_TRACKBALL) == 0)
1627                 return;
1628
1629         dispatch->rotation.config.is_available = fallback_rotation_config_is_available;
1630         dispatch->rotation.config.set_angle = fallback_rotation_config_set_angle;
1631         dispatch->rotation.config.get_angle = fallback_rotation_config_get_angle;
1632         dispatch->rotation.config.get_default_angle = fallback_rotation_config_get_default_angle;
1633         dispatch->rotation.is_enabled = false;
1634         matrix_init_identity(&dispatch->rotation.matrix);
1635         device->base.config.rotation = &dispatch->rotation.config;
1636 }
1637
1638 static inline int
1639 fallback_dispatch_init_slots(struct fallback_dispatch *dispatch,
1640                              struct evdev_device *device)
1641 {
1642         struct libevdev *evdev = device->evdev;
1643         struct mt_slot *slots;
1644         int num_slots;
1645         int active_slot;
1646         int slot;
1647
1648         if (evdev_is_fake_mt_device(device) ||
1649             !libevdev_has_event_code(evdev, EV_ABS, ABS_MT_POSITION_X) ||
1650             !libevdev_has_event_code(evdev, EV_ABS, ABS_MT_POSITION_Y))
1651                  return 0;
1652
1653         /* We only handle the slotted Protocol B in libinput.
1654            Devices with ABS_MT_POSITION_* but not ABS_MT_SLOT
1655            require mtdev for conversion. */
1656         if (evdev_need_mtdev(device)) {
1657                 device->mtdev = mtdev_new_open(device->fd);
1658                 if (!device->mtdev)
1659                         return -1;
1660
1661                 /* pick 10 slots as default for type A
1662                    devices. */
1663                 num_slots = 10;
1664                 active_slot = device->mtdev->caps.slot.value;
1665         } else {
1666                 num_slots = libevdev_get_num_slots(device->evdev);
1667                 active_slot = libevdev_get_current_slot(evdev);
1668         }
1669
1670         slots = zalloc(num_slots * sizeof(struct mt_slot));
1671
1672         for (slot = 0; slot < num_slots; ++slot) {
1673                 slots[slot].seat_slot = -1;
1674
1675                 if (evdev_need_mtdev(device))
1676                         continue;
1677
1678                 slots[slot].point.x = libevdev_get_slot_value(evdev,
1679                                                               slot,
1680                                                               ABS_MT_POSITION_X);
1681                 slots[slot].point.y = libevdev_get_slot_value(evdev,
1682                                                               slot,
1683                                                               ABS_MT_POSITION_Y);
1684                 slots[slot].area.major = libevdev_get_slot_value(evdev,
1685                                                               slot,
1686                                                               ABS_MT_TOUCH_MAJOR);
1687                 slots[slot].area.minor = libevdev_get_slot_value(evdev,
1688                                                               slot,
1689                                                               ABS_MT_TOUCH_MINOR);
1690                 slots[slot].area.orientation = libevdev_get_slot_value(evdev,
1691                                                               slot,
1692                                                               ABS_MT_ORIENTATION);
1693                 slots[slot].pressure = libevdev_get_slot_value(evdev,
1694                                                               slot,
1695                                                               ABS_MT_PRESSURE);
1696         }
1697         dispatch->mt.slots = slots;
1698         dispatch->mt.slots_len = num_slots;
1699         dispatch->mt.slot = active_slot;
1700         dispatch->mt.has_palm = libevdev_has_event_code(evdev,
1701                                                         EV_ABS,
1702                                                         ABS_MT_TOOL_TYPE);
1703
1704         dispatch->mt.aux_data_list = calloc(num_slots, sizeof(struct list));
1705         if (dispatch->mt.aux_data_list) {
1706                 int i;
1707                 for (i = 0; i < num_slots; i++) {
1708                         list_init(&dispatch->mt.aux_data_list[i]);
1709                 }
1710         }
1711         else
1712                 return -1;
1713
1714         if (device->abs.absinfo_x->fuzz || device->abs.absinfo_y->fuzz) {
1715                 dispatch->mt.want_hysteresis = true;
1716                 dispatch->mt.hysteresis_margin.x = device->abs.absinfo_x->fuzz/2;
1717                 dispatch->mt.hysteresis_margin.y = device->abs.absinfo_y->fuzz/2;
1718         }
1719
1720         return 0;
1721 }
1722
1723 static inline void
1724 fallback_dispatch_init_rel(struct fallback_dispatch *dispatch,
1725                            struct evdev_device *device)
1726 {
1727         dispatch->rel.x = 0;
1728         dispatch->rel.y = 0;
1729 }
1730
1731 static inline void
1732 fallback_dispatch_init_abs(struct fallback_dispatch *dispatch,
1733                            struct evdev_device *device)
1734 {
1735         if (!libevdev_has_event_code(device->evdev, EV_ABS, ABS_X))
1736                 return;
1737
1738         dispatch->abs.point.x = device->abs.absinfo_x->value;
1739         dispatch->abs.point.y = device->abs.absinfo_y->value;
1740         dispatch->abs.seat_slot = -1;
1741
1742         evdev_device_init_abs_range_warnings(device);
1743 }
1744
1745 static inline void
1746 fallback_dispatch_init_switch(struct fallback_dispatch *dispatch,
1747                               struct evdev_device *device)
1748 {
1749         int val;
1750
1751         list_init(&dispatch->lid.paired_keyboard_list);
1752
1753         if (device->tags & EVDEV_TAG_LID_SWITCH) {
1754                 dispatch->lid.reliability = evdev_read_switch_reliability_prop(device);
1755                 dispatch->lid.is_closed = false;
1756         }
1757
1758         if (device->tags & EVDEV_TAG_TABLET_MODE_SWITCH) {
1759                 val = libevdev_get_event_value(device->evdev,
1760                                                EV_SW,
1761                                                SW_TABLET_MODE);
1762                 dispatch->tablet_mode.sw.state = val;
1763         }
1764
1765         libinput_device_init_event_listener(&dispatch->tablet_mode.other.listener);
1766 }
1767
1768 static void
1769 fallback_arbitration_timeout(uint64_t now, void *data)
1770 {
1771         struct fallback_dispatch *dispatch = data;
1772
1773         if (dispatch->arbitration.in_arbitration)
1774                 dispatch->arbitration.in_arbitration = false;
1775 }
1776
1777 static void
1778 fallback_init_arbitration(struct fallback_dispatch *dispatch,
1779                           struct evdev_device *device)
1780 {
1781         char timer_name[64];
1782
1783         snprintf(timer_name,
1784                  sizeof(timer_name),
1785                   "%s arbitration",
1786                   evdev_device_get_sysname(device));
1787         libinput_timer_init(&dispatch->arbitration.arbitration_timer,
1788                             evdev_libinput_context(device),
1789                             timer_name,
1790                             fallback_arbitration_timeout,
1791                             dispatch);
1792         dispatch->arbitration.in_arbitration = false;
1793 }
1794
1795 struct evdev_dispatch *
1796 fallback_dispatch_create(struct libinput_device *libinput_device)
1797 {
1798         struct evdev_device *device = evdev_device(libinput_device);
1799         struct fallback_dispatch *dispatch;
1800
1801         dispatch = zalloc(sizeof *dispatch);
1802         dispatch->device = evdev_device(libinput_device);
1803         dispatch->base.dispatch_type = DISPATCH_FALLBACK;
1804         dispatch->base.interface = &fallback_interface;
1805         dispatch->pending_event = EVDEV_NONE;
1806         list_init(&dispatch->lid.paired_keyboard_list);
1807
1808         fallback_dispatch_init_rel(dispatch, device);
1809         fallback_dispatch_init_abs(dispatch, device);
1810         if (fallback_dispatch_init_slots(dispatch, device) == -1) {
1811                 free(dispatch);
1812                 return NULL;
1813         }
1814
1815         fallback_dispatch_init_switch(dispatch, device);
1816
1817         if (device->left_handed.want_enabled)
1818                 evdev_init_left_handed(device,
1819                                        fallback_change_to_left_handed);
1820
1821         if (device->scroll.want_button)
1822                 evdev_init_button_scroll(device,
1823                                          fallback_change_scroll_method);
1824
1825         if (device->scroll.natural_scrolling_enabled)
1826                 evdev_init_natural_scroll(device);
1827
1828         evdev_init_calibration(device, &dispatch->calibration);
1829         evdev_init_sendevents(device, &dispatch->base);
1830         fallback_init_rotation(dispatch, device);
1831
1832         /* BTN_MIDDLE is set on mice even when it's not present. So
1833          * we can only use the absence of BTN_MIDDLE to mean something, i.e.
1834          * we enable it by default on anything that only has L&R.
1835          * If we have L&R and no middle, we don't expose it as config
1836          * option */
1837         if (libevdev_has_event_code(device->evdev, EV_KEY, BTN_LEFT) &&
1838             libevdev_has_event_code(device->evdev, EV_KEY, BTN_RIGHT)) {
1839                 bool has_middle = libevdev_has_event_code(device->evdev,
1840                                                           EV_KEY,
1841                                                           BTN_MIDDLE);
1842                 bool want_config = has_middle;
1843                 bool enable_by_default = !has_middle;
1844
1845                 evdev_init_middlebutton(device,
1846                                         enable_by_default,
1847                                         want_config);
1848         }
1849
1850         fallback_init_wheel(dispatch, device);
1851         fallback_init_debounce(dispatch);
1852         fallback_init_arbitration(dispatch, device);
1853
1854         dispatch->base.device_interface = &fallback_device_interface;
1855
1856         return &dispatch->base;
1857 }