Merge "Build and package Layer Management service binaries." into tizen
[profile/ivi/layer-management.git] / LayerManagerPlugins / Renderers / Graphic / src / WindowSystems / WaylandEvdevInputEvent.cpp
1 /***************************************************************************
2 *
3 * Copyright 2010, 2011 BMW Car IT GmbH
4 * Copyright (C) 2011 DENSO CORPORATION and Robert Bosch Car Multimedia Gmbh
5 *
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 *        http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 *
20 * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
21 * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
22 * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
23 * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
24 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
25 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
26 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
27 *
28 ****************************************************************************/
29 #include <time.h>
30 #include <sys/time.h>
31 #include <sys/wait.h>
32 #include <linux/input.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <fcntl.h>
37 #include <unistd.h>
38 #include <libudev.h>
39 #include <mtdev.h>
40 #include <math.h>
41 #include "InputManager.h"
42 #include "WindowSystems/WaylandEvdevInputEvent.h"
43
44 #define ARRAY_LENGTH(a) (sizeof (a) / sizeof (a)[0])
45
46 #define WL_UNUSED(A) (A)=(A)
47 static const char default_seat[] = "seat0";
48
49 // copied from udev/extras/input_id/input_id.c
50 // we must use this kernel-compatible implementation
51 #define BITS_PER_LONG (sizeof(unsigned long) * 8)
52 #define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1)
53 #define OFF(x)  ((x)%BITS_PER_LONG)
54 #define BIT(x)  (1UL<<OFF(x))
55 #define LONG(x) ((x)/BITS_PER_LONG)
56 #define TEST_BIT(array, bit)    ((array[LONG(bit)] >> OFF(bit)) & 1)
57 // end copied
58
59 #define MAX_VELOCITY_DIFF    1.0
60 #define MOTION_TIMEOUT       300 // (ms)
61 #define NUM_POINTER_TRACKERS 16
62
63 struct evdev_dispatch_interface touchpad_interface = {
64     WaylandEvdevInputEvent::touchpadProcess,
65     WaylandEvdevInputEvent::touchpadDestroy,
66 };
67
68 struct evdev_dispatch_interface fallback_interface = {
69     WaylandEvdevInputEvent::fallbackProcess,
70     WaylandEvdevInputEvent::fallbackDestroy,
71 };
72
73 // Function prototypes
74 void acceleratorFilter(struct motion_filter *, struct motion_params *, void *, uint32_t);
75 void acceleratorDestroy(struct motion_filter *);
76
77 struct motion_filter_interface accelerator_interface = {
78     acceleratorFilter,
79     acceleratorDestroy,
80 };
81
82 static struct touchpad_model_spec touchpad_spec_table[] = {
83     {0x0002, 0x0007, TOUCHPAD_MODEL_SYNAPTICS},
84     {0x0002, 0x0008, TOUCHPAD_MODEL_ALPS},
85     {0x05ac, 0x0000, TOUCHPAD_MODEL_APPLETOUCH},
86     {0x0002, 0x000e, TOUCHPAD_MODEL_ELANTECH},
87     {0x0000, 0x0000, TOUCHPAD_MODEL_UNKNOWN}
88 };
89
90 ////////////////////////////////////////////////////////////////////////////
91
92 static int
93 isMotionEvent(struct input_event *e)
94 {
95     switch (e->type)
96     {
97     case EV_REL:
98         switch (e->code)
99         {
100         case REL_X:
101         case REL_Y:
102             return 1;
103         }
104         break;
105     case EV_ABS:
106         switch (e->code)
107         {
108         case ABS_X:
109         case ABS_Y:
110         case ABS_MT_POSITION_X:
111         case ABS_MT_POSITION_Y:
112             return 1;
113         }
114         break;
115     }
116     return 0;
117 }
118
119 static enum touchpad_model
120 getTouchpadModel(struct evdev_input_device *device)
121 {
122     struct input_id id;
123     unsigned int i;
124
125     if (ioctl(device->fd, EVIOCGID, &id) < 0)
126         return TOUCHPAD_MODEL_UNKNOWN;
127
128     for (i = 0; i < sizeof(touchpad_spec_table); ++i)
129     {
130         if (touchpad_spec_table[i].vendor == id.vendor &&
131             (!touchpad_spec_table[i].product ||
132             touchpad_spec_table[i].product == id.product))
133         {
134             return touchpad_spec_table[i].model;
135         }
136     }
137
138     return TOUCHPAD_MODEL_UNKNOWN;
139 }
140
141 static void
142 configureTouchpadPressure(struct touchpad_dispatch *touchpad,
143                             int32_t pressure_min, int32_t pressure_max)
144 {
145     int32_t range = pressure_max - pressure_min + 1;
146     touchpad->has_pressure = 1;
147
148     // Magic numbers from xf86-input-synaptics
149     switch (touchpad->model)
150     {
151     case TOUCHPAD_MODEL_ELANTECH:
152         touchpad->pressure.touch_low = pressure_min + 1;
153         touchpad->pressure.touch_high = pressure_min + 1;
154         break;
155     default:
156         touchpad->pressure.touch_low = pressure_min + range * (25.0 / 256.0);
157         touchpad->pressure.touch_high = pressure_min + range * (30.0 / 256.0);
158         break;
159     }
160
161     touchpad->pressure.press = pressure_min + range;
162 }
163
164 static double
165 touchpadProfile(struct motion_filter *filter, void *data,
166                 double velocity, uint32_t time)
167 {
168     WL_UNUSED(filter);
169     WL_UNUSED(time);
170     struct touchpad_dispatch *touchpad = (struct touchpad_dispatch*)data;
171     double accel_factor;
172
173     accel_factor = velocity * touchpad->constant_accel_factor;
174
175     if (accel_factor > touchpad->max_accel_factor)
176         accel_factor = touchpad->max_accel_factor;
177     else if (accel_factor < touchpad->min_accel_factor)
178         accel_factor = touchpad->min_accel_factor;
179
180     return accel_factor;
181 }
182
183 static motion_filter*
184 createPointerAccelatorFilter(accel_profile_func_t profile)
185 {
186     struct pointer_accelerator *filter;
187
188     filter = (struct pointer_accelerator*)malloc(sizeof(*filter));
189     if (filter == NULL)
190         return NULL;
191
192     filter->base.interface = &accelerator_interface;
193     wl_list_init(&filter->base.link);
194
195     filter->profile = profile;
196     filter->last_velocity = 0.0;
197     filter->last_dx = 0;
198     filter->last_dy = 0;
199
200     filter->trackers = (struct pointer_tracker*)
201         calloc(NUM_POINTER_TRACKERS, sizeof(*filter->trackers));
202     filter->cur_tracker = 0;
203
204     return &filter->base;
205 }
206
207 static evdev_dispatch*
208 createFallbackDispatch()
209 {
210     struct evdev_dispatch *dispatch =
211         (struct evdev_dispatch*)malloc(sizeof(*dispatch));
212     if (dispatch == NULL)
213         return NULL;
214
215     dispatch->interface = &fallback_interface;
216
217     return dispatch;
218 }
219
220 ////////////////////////////////////////////////////////////////////////
221
222 static void
223 processTouch(struct evdev_input_device *device, struct input_event *e,
224                 int screen_width, int screen_height)
225 {
226     switch (e->code)
227     {
228     case ABS_MT_SLOT:
229         device->mt.slot = e->value;
230         break;
231     case ABS_MT_TRACKING_ID:
232         if (e->value >= 0)
233             device->pending_events |= EVDEV_ABSOLUTE_MT_DOWN;
234         else
235             device->pending_events |= EVDEV_ABSOLUTE_MT_UP;
236         break;
237     case ABS_MT_POSITION_X:
238         device->mt.x[device->mt.slot] =
239             (e->value - device->abs.min_x) * screen_width /
240             (device->abs.max_x - device->abs.min_x) +
241             0; //device->output->x;
242         device->pending_events |= EVDEV_ABSOLUTE_MT_MOTION;
243         break;
244     case ABS_MT_POSITION_Y:
245         device->mt.y[device->mt.slot] =
246             (e->value - device->abs.min_y) * screen_height /
247             (device->abs.max_y - device->abs.min_y) +
248             0; //device->output->y;
249         device->pending_events |= EVDEV_ABSOLUTE_MT_MOTION;
250         break;
251     }
252 }
253
254 static void
255 processAbsoluteMotion(struct evdev_input_device *device, struct input_event *e,
256                         int screen_width, int screen_height)
257 {
258     switch (e->code)
259     {
260     case ABS_X:
261         device->abs.x =
262             (e->value - device->abs.min_x) * screen_width /
263             (device->abs.max_x - device->abs.min_x) +
264             0; //device->output->x;
265         device->pending_events |= EVDEV_ABSOLUTE_MOTION;
266         break;
267     case ABS_Y:
268         device->abs.y =
269             (e->value - device->abs.min_y) * screen_height /
270             (device->abs.max_y - device->abs.min_y) +
271             0; //device->output->y;
272         device->abs.x = screen_width - device->abs.x;
273         device->pending_events |= EVDEV_ABSOLUTE_MOTION;
274         break;
275     // The following is the effective code only from a specific model
276     /****
277     case ABS_X:
278         device->abs.y = (e->value - device->abs.min_x) * screen_height /
279                         (device->abs.max_x - device->abs.min_x);
280         device->pending_events |= EVDEV_ABSOLUTE_MOTION;
281         break;
282     case ABS_Y:
283         device->abs.x = (e->value - device->abs.min_y) * screen_width /
284                         (device->abs.max_y - device->abs.min_y);
285         device->abs.x = screen_width - device->abs.x;
286         device->pending_events |= EVDEV_ABSOLUTE_MOTION;
287         break;
288      ****/
289     }
290 }
291
292 ////////////////////////////////////////////////////////////////////////
293
294 static int
295 hysteresis(int in, int center, int margin)
296 {
297     int diff = in - center;
298     if (abs(diff) <= margin)
299         return center;
300
301     if (diff > margin)
302         return center + diff - margin;
303     else if (diff < -margin)
304         return center + diff + margin;
305     return center + diff;
306 }
307
308 static inline struct touchpad_motion*
309 motionHistoryOffset(struct touchpad_dispatch *touchpad, int offset)
310 {
311     int offsetIndex =
312         (touchpad->motion_index - offset + TOUCHPAD_HISTORY_LENGTH) %
313         TOUCHPAD_HISTORY_LENGTH;
314
315     return &touchpad->motion_history[offsetIndex];
316 }
317
318 static double
319 estimateDelta(int x0, int x1, int x2, int x3)
320 {
321     return (x0 + x1 - x2 - x3) / 4;
322 }
323
324 static void
325 touchpadGetDelta(struct touchpad_dispatch *touchpad, double *dx, double *dy)
326 {
327     *dx = estimateDelta(motionHistoryOffset(touchpad, 0)->x,
328                         motionHistoryOffset(touchpad, 1)->x,
329                         motionHistoryOffset(touchpad, 2)->x,
330                         motionHistoryOffset(touchpad, 3)->x);
331     *dy = estimateDelta(motionHistoryOffset(touchpad, 0)->y,
332                         motionHistoryOffset(touchpad, 1)->y,
333                         motionHistoryOffset(touchpad, 2)->y,
334                         motionHistoryOffset(touchpad, 3)->y);
335 }
336
337 static void
338 filterDispatch(struct motion_filter *filter, struct motion_params *motion,
339                 void *data, uint32_t time)
340 {
341     filter->interface->filter(filter, motion, data, time);
342 }
343
344 static void
345 filterMotion(struct touchpad_dispatch *touchpad,
346                 double *dx, double *dy, uint32_t time)
347 {
348     struct motion_filter *filter;
349     struct motion_params  motion;
350
351     motion.dx = *dx;
352     motion.dy = *dy;
353
354     wl_list_for_each(filter, &touchpad->motion_filters, link)
355     {
356         filterDispatch(filter, &motion, touchpad, time);
357     }
358
359     *dx = motion.dx;
360     *dy = motion.dy;
361 }
362
363 static int
364 getDirection(int dx, int dy)
365 {
366     int dir = UNDEFINED_DIRECTION;
367     int d1;
368     int d2;
369     double r;
370
371     if (abs(dx) < 2 && abs(dy) < 2)
372     {
373         if (dx > 0 && dy > 0)
374             dir = S | SE | E;
375         else if (dx > 0 && dy < 0)
376             dir = N | NE | E;
377         else if (dx < 0 && dy > 0)
378             dir = S | SW | W;
379         else if (dx < 0 && dy < 0)
380             dir = N | NW | W;
381         else if (dx > 0)
382             dir = NW | W | SW;
383         else if (dx < 0)
384             dir = NE | E | SE;
385         else if (dy > 0)
386             dir = SE | S | SW;
387         else if (dy < 0)
388             dir = NE | N | NW;
389     }
390     else
391     {
392         // Calculate r within the interval  [0 to 8)
393         //
394         // r = [0 .. 2Ï€] where 0 is North
395         // d_f = r / 2Ï€  ([0 .. 1))
396         // d_8 = 8 * d_f
397         //
398         r = atan2(dy, dx);
399         r = fmod(r + 2.5*M_PI, 2*M_PI);
400         r *= 4*M_1_PI;
401
402         // Mark one or two close enough octants
403         d1 = (int)(r + 0.9) % 8;
404         d2 = (int)(r + 0.1) % 8;
405
406         dir = (1 << d1) | (1 << d2);
407     }
408
409     return dir;
410 }
411
412 static void
413 feedTrackers(struct pointer_accelerator *accel,
414                 double dx, double dy, uint32_t time)
415 {
416     int i;
417     int current;
418     struct pointer_tracker *trackers = accel->trackers;
419
420     for (i = 0; i < NUM_POINTER_TRACKERS; ++i)
421     {
422         trackers[i].dx += dx;
423         trackers[i].dy += dy;
424     }
425
426     current = (accel->cur_tracker + 1) % NUM_POINTER_TRACKERS;
427     accel->cur_tracker = current;
428
429     trackers[current].dx = 0.0;
430     trackers[current].dy = 0.0;
431     trackers[current].time = time;
432     trackers[current].dir = getDirection(dx, dy);
433 }
434
435 static struct pointer_tracker*
436 trackerByOffset(struct pointer_accelerator *accel, unsigned int offset)
437 {
438     unsigned int index =
439         (accel->cur_tracker + NUM_POINTER_TRACKERS - offset)
440         % NUM_POINTER_TRACKERS;
441     return &accel->trackers[index];
442 }
443
444 static double
445 calculateTrackerVelocity(struct pointer_tracker *tracker, uint32_t time)
446 {
447     int dx;
448     int dy;
449     double distance;
450
451     dx = tracker->dx;
452     dy = tracker->dy;
453     distance = sqrt(dx*dx + dy*dy);
454     return distance / (double)(time - tracker->time);
455 }
456
457 static double
458 calculateVelocity(struct pointer_accelerator *accel, uint32_t time)
459 {
460     struct pointer_tracker *tracker;
461     double velocity;
462     double result = 0.0;
463     double initial_velocity;
464     double velocity_diff;
465     unsigned int offset;
466
467     unsigned int dir = trackerByOffset(accel, 0)->dir;
468
469     // Find first velocity
470     for (offset = 1; offset < NUM_POINTER_TRACKERS; offset++)
471     {
472         tracker = trackerByOffset(accel, offset);
473
474         if (time <= tracker->time)
475             continue;
476
477         result = initial_velocity =
478             calculateTrackerVelocity(tracker, time);
479         if (initial_velocity > 0.0)
480             break;
481     }
482
483     // Find least recent vector within a timelimit, maximum velocity diff
484     // and direction threshold.
485     for (; offset < NUM_POINTER_TRACKERS; offset++)
486     {
487         tracker = trackerByOffset(accel, offset);
488
489         // Stop if too far away in time
490         if (time - tracker->time > MOTION_TIMEOUT ||
491             tracker->time > time)
492             break;
493
494         // Stop if direction changed
495         dir &= tracker->dir;
496         if (dir == 0)
497             break;
498
499         velocity = calculateTrackerVelocity(tracker, time);
500
501         // Stop if velocity differs too much from initial
502         velocity_diff = fabs(initial_velocity - velocity);
503         if (velocity_diff > MAX_VELOCITY_DIFF)
504             break;
505
506         result = velocity;
507     }
508
509     return result;
510 }
511
512 static double
513 accelerationProfile(struct pointer_accelerator *accel,
514                     void *data, double velocity, uint32_t time)
515 {
516     return accel->profile(&accel->base, data, velocity, time);
517 }
518
519 static double
520 calculateAcceleration(struct pointer_accelerator *accel,
521                         void *data, double velocity, uint32_t time)
522 {
523     double factor;
524
525     factor = accelerationProfile(accel, data, velocity, time);
526     factor += accelerationProfile(accel, data, accel->last_velocity, time);
527     factor += 4.0 *
528                     accelerationProfile(accel, data,
529                                     (accel->last_velocity + velocity) / 2,
530                                     time);
531     factor = factor / 6.0;
532     return factor;
533 }
534
535 static double
536 softenDelta(double lastDelta, double delta)
537 {
538     if (delta < -1.0 || delta > 1.0)
539     {
540         if (delta > lastDelta)
541             return delta - 0.5;
542         else if (delta < lastDelta)
543             return delta + 0.5;
544     }
545     return delta;
546 }
547
548 static void
549 applySoftening(struct pointer_accelerator *accel,
550                 struct motion_params *motion)
551 {
552     motion->dx = softenDelta(accel->last_dx, motion->dx);
553     motion->dy = softenDelta(accel->last_dy, motion->dy);
554 }
555
556 void
557 acceleratorFilter(struct motion_filter *filter, struct motion_params *motion,
558                     void *data, uint32_t time)
559 {
560     struct pointer_accelerator *accel = (struct pointer_accelerator*)filter;
561     double velocity;
562     double accel_value;
563
564     feedTrackers(accel, motion->dx, motion->dy, time);
565     velocity = calculateVelocity(accel, time);
566     accel_value = calculateAcceleration(accel, data, velocity, time);
567
568     motion->dx = accel_value * motion->dx;
569     motion->dy = accel_value * motion->dy;
570
571     applySoftening(accel, motion);
572
573     accel->last_dx = motion->dx;
574     accel->last_dy = motion->dy;
575
576     accel->last_velocity = velocity;
577 }
578
579 void
580 acceleratorDestroy(struct motion_filter *filter)
581 {
582     struct pointer_accelerator *accel = (struct pointer_accelerator*)filter;
583
584     free(accel->trackers);
585     free(accel);
586 }
587
588 /// WaylandEvdevInputEvent /////////////////////////////////////////////////
589
590 WaylandEvdevInputEvent::WaylandEvdevInputEvent(WaylandBaseWindowSystem* windowSystem)
591 : WaylandInputEvent(windowSystem)
592 , m_udev(NULL)
593 , m_screenWidth(0)
594 , m_screenHeight(0)
595 {
596     wl_list_init(&m_deviceList);
597 }
598
599 WaylandEvdevInputEvent::~WaylandEvdevInputEvent()
600 {
601     if (m_udev)
602     {
603         udev_unref(m_udev);
604     }
605
606     struct evdev_input_device *device, *next;
607
608     wl_list_for_each_safe(device, next, &m_deviceList, link)
609     {
610         removeDevice(device);
611     }
612 }
613
614 void
615 WaylandEvdevInputEvent::removeDevice(struct evdev_input_device *device)
616 {
617     struct evdev_dispatch *dispatch = device->dispatch;
618
619     if (dispatch)
620         dispatch->interface->destroy(dispatch);
621
622     wl_event_source_remove(device->source);
623     wl_list_remove(&device->link);
624     if (device->mtdev)
625         mtdev_close_delete(device->mtdev);
626     close(device->fd);
627     free(device->devnode);
628     free(device);
629 }
630
631 void
632 WaylandEvdevInputEvent::setupInputEvent()
633 {
634     LOG_INFO("WaylandEvdevInputEvent", "setupInputEvent IN");
635
636     WaylandInputEvent::setupInputEvent();
637
638     m_screenWidth = m_windowSystem->getWindowWidth();
639     m_screenHeight = m_windowSystem->getWindowHeight();
640
641     do {
642         bool bRet = addDevices();
643         if (!bRet)
644         {
645             break;
646         }
647     } while (0);
648
649     LOG_INFO("WaylandEvdevInputEvent", "setupInputEvent OUT");
650 }
651
652 bool
653 WaylandEvdevInputEvent::addDevices()
654 {
655     if (!m_udev)
656         m_udev = udev_new();
657     if (!m_udev)
658     {
659         LOG_ERROR("WaylandEvdevInputEvent", "Failed to initialize udev context");
660         return false;
661     }
662
663     struct udev_enumerate *e = udev_enumerate_new(m_udev);
664     udev_enumerate_add_match_subsystem(e, "input");
665     udev_enumerate_scan_devices(e);
666
667     struct udev_list_entry *entry;
668     const char *path, *sysname;
669     struct udev_device *device;
670     udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(e))
671     {
672         path = udev_list_entry_get_name(entry);
673         device = udev_device_new_from_syspath(m_udev, path);
674
675         sysname = udev_device_get_sysname(device);
676         if (strncmp("event", sysname, 5) != 0)
677         {
678             udev_device_unref(device);
679             continue;
680         }
681
682         addDevice(device);
683         udev_device_unref(device);
684     }
685     udev_enumerate_unref(e);
686
687     notifyKeyboardFocus();
688
689     if (wl_list_empty(&m_deviceList))
690     {
691         LOG_WARNING("WaylandEvdevInputEvent", "No input devices on entering service");
692     }
693
694     return true;
695 }
696
697 void
698 WaylandEvdevInputEvent::addDevice(struct udev_device *udevDevice)
699 {
700     const char *devnode;
701     const char *device_seat;
702
703     device_seat = udev_device_get_property_value(udevDevice, "ID_SEAT");
704     if (!device_seat)
705         device_seat = default_seat;
706
707     devnode = udev_device_get_devnode(udevDevice);
708     createInputDevice(m_windowSystem->getNativeDisplayHandle(), devnode);
709 }
710
711 void
712 WaylandEvdevInputEvent::createInputDevice(struct wl_display *display, const char *path)
713 {
714     struct evdev_input_device *device;
715     struct wl_event_loop      *eventLoop;
716
717     device = (struct evdev_input_device*)malloc(sizeof(*device));
718     if (device == NULL)
719     {
720         return;
721     }
722
723     device->master = this;
724     device->isMt = 0;
725     device->mtdev = NULL;
726     device->devnode = strdup(path);
727     device->mt.slot = -1;
728     device->rel.dx = 0;
729     device->rel.dy = 0;
730     device->dispatch = NULL;
731
732     device->fd = open(path, O_RDWR | O_NONBLOCK);
733     if (device->fd < 0)
734     {
735         goto err0;
736     }
737
738     if (configureDevice(device) < 0)
739     {
740         goto err1;
741     }
742
743     // If the dispatch was not set up use the fallback
744     if (device->dispatch == NULL)
745         device->dispatch = createFallbackDispatch();
746     if (device->dispatch == NULL)
747         goto err1;
748
749     if (device->isMt)
750     {
751         device->mtdev = mtdev_new_open(device->fd);
752         if (!device->mtdev)
753         {
754             LOG_WARNING("WaylandEvdevInputEvent", "mtdev failed to open for " << path);
755         }
756     }
757
758     eventLoop = wl_display_get_event_loop(display);
759     device->source = wl_event_loop_add_fd(eventLoop, device->fd, WL_EVENT_READABLE,
760                                             WaylandEvdevInputEvent::handleInputEvent,
761                                             device);
762     if (device->source == NULL)
763     {
764         goto err2;
765     }
766
767     wl_list_insert(m_deviceList.prev, &(device->link));
768
769     return;
770
771 err2:
772     device->dispatch->interface->destroy(device->dispatch);
773 err1:
774     close(device->fd);
775 err0:
776     free(device->devnode);
777     free(device);
778     return;
779 }
780
781 int
782 WaylandEvdevInputEvent::configureDevice(struct evdev_input_device *device)
783 {
784     struct input_absinfo absinfo;
785     unsigned long ev_bits[NBITS(EV_MAX)];
786     unsigned long abs_bits[NBITS(ABS_MAX)];
787     unsigned long rel_bits[NBITS(ABS_MAX)];
788     unsigned long key_bits[NBITS(KEY_MAX)];
789
790     int hasKey = 0;
791     int hasAbs = 0;
792     int i;
793     device->caps = 0;
794
795     ioctl(device->fd, EVIOCGBIT(0, sizeof(ev_bits)), ev_bits);
796     if (TEST_BIT(ev_bits, EV_ABS))
797     {
798         hasAbs = 1;
799
800         ioctl(device->fd, EVIOCGBIT(EV_ABS, sizeof(abs_bits)), abs_bits);
801         if (TEST_BIT(abs_bits, ABS_X))
802         {
803             ioctl(device->fd, EVIOCGABS(ABS_X), &absinfo);
804             device->abs.min_x = absinfo.minimum;
805             device->abs.max_x = absinfo.maximum;
806             device->caps |= EVDEV_MOTION_ABS;
807         }
808         if (TEST_BIT(abs_bits, ABS_Y))
809         {
810             ioctl(device->fd, EVIOCGABS(ABS_Y), &absinfo);
811             device->abs.min_y = absinfo.minimum;
812             device->abs.max_y = absinfo.maximum;
813             device->caps |= EVDEV_MOTION_ABS;
814         }
815         if (TEST_BIT(abs_bits, ABS_MT_SLOT))
816         {
817             device->isMt = 1;
818             device->mt.slot = 0;
819             device->caps |= EVDEV_TOUCH;
820         }
821     }
822     if (TEST_BIT(ev_bits, EV_REL))
823     {
824         ioctl(device->fd, EVIOCGBIT(EV_REL, sizeof(rel_bits)), rel_bits);
825         if (TEST_BIT(rel_bits, REL_X) || TEST_BIT(rel_bits, REL_Y))
826         {
827             device->caps |= EVDEV_MOTION_REL;
828         }
829     }
830     if (TEST_BIT(ev_bits, EV_KEY))
831     {
832         hasKey = 1;
833         ioctl(device->fd, EVIOCGBIT(EV_KEY, sizeof(key_bits)), key_bits);
834         if (TEST_BIT(key_bits, BTN_TOOL_FINGER) &&
835             !TEST_BIT(key_bits, BTN_TOOL_PEN) && hasAbs)
836         {
837             device->dispatch = createTouchpad(device);
838         }
839
840         for (i = KEY_ESC; i < KEY_MAX; ++i)
841         {
842             if (i >= BTN_MISC && i < KEY_OK)
843                 continue;
844             if (TEST_BIT(key_bits, i))
845             {
846                 device->caps |= EVDEV_KEYBOARD;
847                 break;
848             }
849         }
850         for (i = BTN_MISC; i < KEY_OK; ++i)
851         {
852             if (TEST_BIT(key_bits, i))
853             {
854                 device->caps |= EVDEV_BUTTON;
855                 break;
856             }
857         }
858     }
859     if (TEST_BIT(ev_bits, EV_LED))
860     {
861         device->caps |= EVDEV_KEYBOARD;
862     }
863
864     // This rule tries to catch accelerometer devices and opt out. We may
865     // want to adjust the protocol later adding a proper event for dealing
866     // with accelerometers and implement here accordingly
867     if (hasAbs && !hasKey && !device->isMt)
868         return -1;
869
870 #if 0
871     fprintf(stdout, "DEVICE: [%s] information\n", device->devnode);
872     fprintf(stdout, "        capabilities: EVDEV_KEYBOARD   %s\n"
873                     "                      EVDEV_BUTTON     %s\n"
874                     "                      EVDEV_MOTION_ABS %s\n"
875                     "                      EVDEV_MOTION_REL %s\n"
876                     "                      EVDEV_TOUCH      %s\n",
877             (device->caps & EVDEV_KEYBOARD)   ? "TRUE" : "FALSE",
878             (device->caps & EVDEV_BUTTON)     ? "TRUE" : "FALSE",
879             (device->caps & EVDEV_MOTION_ABS) ? "TRUE" : "FALSE",
880             (device->caps & EVDEV_MOTION_REL) ? "TRUE" : "FALSE",
881             (device->caps & EVDEV_TOUCH)      ? "TRUE" : "FALSE");
882     if (device->caps & EVDEV_MOTION_ABS)
883     {
884         fprintf(stdout, "        abs: min_x(%4d), min_y(%4d)\n", device->abs.min_x, device->abs.min_y);
885         fprintf(stdout, "             max_x(%4d), max_y(%4d)\n", device->abs.max_x, device->abs.max_y);
886         fprintf(stdout, "                 x(%4d),     y(%4d)\n", device->abs.x, device->abs.y);
887     }
888     fprintf(stdout, "\n");
889 #endif
890
891     if ((device->caps & (EVDEV_MOTION_ABS | EVDEV_MOTION_REL | EVDEV_BUTTON)))
892     {
893         initPointerDevice();
894     }
895     if ((device->caps & (EVDEV_KEYBOARD)))
896     {
897         initKeyboardDevice(NULL);
898     }
899     if ((device->caps & (EVDEV_TOUCH)))
900     {
901         initTouchDevice();
902     }
903
904     return 0;
905 }
906
907 void
908 WaylandEvdevInputEvent::notifyKeyboardFocus()
909 {
910     struct evdev_input_device *device;
911     struct wl_array keys;
912     char evdev_keys[(KEY_CNT + 7) / 8];
913     char all_keys[(KEY_CNT + 7) / 8];
914     uint32_t *k;
915     unsigned int i, set;
916     int ret;
917
918     memset(all_keys, 0, sizeof(all_keys));
919     wl_list_for_each(device, &m_deviceList, link)
920     {
921         memset(evdev_keys, 0, sizeof(evdev_keys));
922         ret = ioctl(device->fd, EVIOCGKEY(sizeof(evdev_keys)), evdev_keys);
923         if (ret < 0)
924         {
925             LOG_WARNING("WaylandEvdevInputEvent", "Failed to get keys for device: " <<
926                         device->devnode);
927             continue;
928         }
929         for (i = 0; i < ARRAY_LENGTH(evdev_keys); ++i)
930         {
931             all_keys[i] |= evdev_keys[i];
932         }
933     }
934
935     wl_array_init(&keys);
936     for (i = 0; i < KEY_CNT; ++i)
937     {
938         set = all_keys[i >> 3] & (1 << (i & 7));
939         if (set)
940         {
941             k = (uint32_t*)wl_array_add(&keys, sizeof(*k));
942             *k = i;
943         }
944     }
945
946     notifyKeyboardFocusIn(&keys, STATE_UPDATE_AUTOMATIC);
947
948     wl_array_release(&keys);
949 }
950
951 void
952 WaylandEvdevInputEvent::notifyKeyboardFocusIn(struct wl_array *keys,
953                                                 enum key_state_update updateState)
954 {
955     struct wl_seat *wlSeat;
956     uint32_t *k;
957     uint32_t serial;
958
959     if ((wlSeat = m_inputDevice->seat()) == NULL)
960     {
961         return;
962     }
963     /**
964      * @todo Port to Wayland 1.3.
965      */
966     // if (!wlSeat->keyboard)
967     // {
968     //     return;
969     // }
970     serial = wl_display_next_serial(m_inputDevice->display());
971     /**
972      * @todo Port to Wayland 1.3.
973      */
974     // wl_array_init(&wlSeat->keyboard->keys);
975     // wl_array_copy(&wlSeat->keyboard->keys, keys);
976
977     /**
978      * @todo Port to Wayland 1.3.
979      */
980     struct wl_array *array = NULL; // &wlSeat->keyboard->keys;
981     for (k = (uint32_t*)array->data;
982         (const char*)k < (const char*)array->data + array->size;
983         ++k)
984     {
985         if (updateState == STATE_UPDATE_AUTOMATIC)
986         {
987             updateModifierState(wlSeat, serial, *k, WL_KEYBOARD_KEY_STATE_PRESSED);
988         }
989     }
990 }
991
992 void
993 WaylandEvdevInputEvent::updateModifierState(struct wl_seat *wlSeat, uint32_t serial,
994                                             uint32_t key, enum wl_keyboard_key_state state)
995 {
996     enum xkb_key_direction direction;
997
998     if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
999         direction = XKB_KEY_DOWN;
1000     else
1001         direction = XKB_KEY_UP;
1002
1003     // Offset the keycode by 8, as the evdev XKB rules reflect X's
1004     // broken keycode system, which starts at 8.
1005     xkb_state_update_key(m_xkbState.state, key + 8, direction);
1006
1007     notifyModifiers(wlSeat, serial);
1008 }
1009
1010 struct evdev_dispatch*
1011 WaylandEvdevInputEvent::createTouchpad(struct evdev_input_device *device)
1012 {
1013     struct touchpad_dispatch *touchpad;
1014
1015     touchpad = (struct touchpad_dispatch*)malloc(sizeof(*touchpad));
1016     if (touchpad == NULL)
1017         return NULL;
1018
1019     touchpad->base.interface = &touchpad_interface;
1020
1021     touchpad->device = device;
1022     wl_list_init(&touchpad->motion_filters);
1023
1024     configureTouchpad(touchpad, device);
1025
1026     return &touchpad->base;
1027 }
1028
1029 void
1030 WaylandEvdevInputEvent::configureTouchpad(struct touchpad_dispatch *touchpad,
1031                                             struct evdev_input_device *device)
1032 {
1033     struct motion_filter *accel;
1034
1035     struct input_absinfo absinfo;
1036     unsigned long abs_bits[NBITS(ABS_MAX)];
1037
1038     double width;
1039     double height;
1040     double diagonal;
1041
1042     // Detect model
1043     touchpad->model = getTouchpadModel(device);
1044
1045     // Configure pressure
1046     ioctl(device->fd, EVIOCGBIT(EV_ABS, sizeof(abs_bits)), abs_bits);
1047     if (TEST_BIT(abs_bits, ABS_PRESSURE))
1048     {
1049         ioctl(device->fd, EVIOCGABS(ABS_PRESSURE), &absinfo);
1050         configureTouchpadPressure(touchpad,
1051                                 absinfo.minimum,
1052                                 absinfo.maximum);
1053     }
1054
1055     // Configure acceleration factor
1056     width = abs(device->abs.max_x - device->abs.min_x);
1057     height = abs(device->abs.max_y - device->abs.min_y);
1058     diagonal = sqrt(width*width + height*height);
1059
1060     touchpad->constant_accel_factor =
1061         DEFAULT_CONSTANT_ACCEL_NUMERATOR / diagonal;
1062
1063     touchpad->min_accel_factor = DEFAULT_MIN_ACCEL_FACTOR;
1064     touchpad->max_accel_factor = DEFAULT_MAX_ACCEL_FACTOR;
1065
1066     touchpad->hysteresis.margin_x = diagonal / DEFAULT_HYSTERESIS_MARGIN_DENOMINATOR;
1067     touchpad->hysteresis.margin_y = diagonal / DEFAULT_HYSTERESIS_MARGIN_DENOMINATOR;
1068     touchpad->hysteresis.center_x = 0;
1069     touchpad->hysteresis.center_y = 0;
1070
1071     // Configure acceleration profile
1072     accel = createPointerAccelatorFilter(touchpadProfile);
1073     wl_list_insert(&touchpad->motion_filters, &accel->link);
1074
1075     // Setup initial state
1076     touchpad->reset = 1;
1077
1078     memset(touchpad->motion_history, 0, sizeof touchpad->motion_history);
1079     touchpad->motion_index = 0;
1080     touchpad->motion_count = 0;
1081
1082     touchpad->state = TOUCHPAD_STATE_NONE;
1083     touchpad->last_finger_state = 0;
1084     touchpad->finger_state = 0;
1085 }
1086
1087 int
1088 WaylandEvdevInputEvent::handleInputEvent(int fd, uint32_t mask, void *data)
1089 {
1090     WL_UNUSED(mask);
1091
1092     struct evdev_input_device *device = (evdev_input_device*)data;
1093     struct input_event ev[32];
1094     int len;
1095     do {
1096         if (device->mtdev)
1097         {
1098             len = mtdev_get(device->mtdev, fd, ev,
1099                 ARRAY_LENGTH(ev)) * sizeof(struct input_event);
1100         }
1101         else
1102         {
1103             len = read(fd, &ev, sizeof(ev));
1104         }
1105
1106         if (len < 0 || len % sizeof(ev[0]) != 0)
1107         {
1108             return 1;
1109         }
1110
1111         WaylandEvdevInputEvent::processEvents(device, ev, len / sizeof(ev[0]));
1112     } while (len > 0);
1113
1114     return 1;
1115 }
1116
1117 void
1118 WaylandEvdevInputEvent::processEvents(struct evdev_input_device *device,
1119                                         struct input_event *ev,
1120                                         int count)
1121 {
1122     struct evdev_dispatch *dispatch = device->dispatch;
1123     struct input_event *e, *end;
1124     uint32_t time = 0;
1125
1126     device->pending_events = 0;
1127
1128     e = ev;
1129     end = e + count;
1130     for (; e < end; ++e)
1131     {
1132         time = e->time.tv_sec * 1000 + e->time.tv_usec / 1000;
1133
1134         if (!isMotionEvent(e))
1135         {
1136             WaylandEvdevInputEvent::flushMotion(device, time);
1137         }
1138
1139         dispatch->interface->process(dispatch, device, e, time);
1140     }
1141
1142     WaylandEvdevInputEvent::flushMotion(device, time);
1143 }
1144
1145 void
1146 WaylandEvdevInputEvent::flushMotion(struct evdev_input_device *device,
1147                                     uint32_t time)
1148 {
1149     if (!device->pending_events)
1150         return;
1151
1152     WaylandEvdevInputEvent *inputEvent = static_cast<WaylandEvdevInputEvent*>(device->master);
1153     if (!inputEvent)
1154         return;
1155
1156     if (device->pending_events & EVDEV_RELATIVE_MOTION)
1157     {
1158         struct wl_seat *wlSeat = inputEvent->inputDevice().seat();
1159         if (wlSeat)
1160         {
1161             // notify_motion
1162             /**
1163              * @todo Port to Wayland 1.3.
1164              */
1165             // notifyMotion(device, time,
1166             //             wlSeat->pointer->x + device->rel.dx,
1167             //             wlSeat->pointer->y + device->rel.dy);
1168         }
1169         device->pending_events &= ~EVDEV_RELATIVE_MOTION;
1170         device->rel.dx = 0;
1171         device->rel.dy = 0;
1172     }
1173     if (device->pending_events & EVDEV_ABSOLUTE_MT_DOWN)
1174     {
1175         // notify_touch
1176         notifyTouch(device);
1177         device->pending_events &= ~EVDEV_ABSOLUTE_MT_DOWN;
1178         device->pending_events &= ~EVDEV_ABSOLUTE_MT_MOTION;
1179     }
1180     if (device->pending_events & EVDEV_ABSOLUTE_MT_MOTION)
1181     {
1182         // notify_touch
1183         notifyTouch(device);
1184         device->pending_events &= ~EVDEV_ABSOLUTE_MT_DOWN;
1185         device->pending_events &= ~EVDEV_ABSOLUTE_MT_MOTION;
1186     }
1187     if (device->pending_events & EVDEV_ABSOLUTE_MT_UP)
1188     {
1189         // notify_touch
1190         notifyTouch(device);
1191         device->pending_events &= ~EVDEV_ABSOLUTE_MT_UP;
1192     }
1193     if (device->pending_events & EVDEV_ABSOLUTE_MOTION)
1194     {
1195         // notify_motion
1196         notifyMotion(device, time,
1197                     wl_fixed_from_int(device->abs.x),
1198                     wl_fixed_from_int(device->abs.y));
1199         device->pending_events &= ~EVDEV_ABSOLUTE_MOTION;
1200     }
1201 }
1202
1203 /// Default event handler //////////////////////////////////////////////////
1204
1205 void
1206 WaylandEvdevInputEvent::fallbackProcess(struct evdev_dispatch *dispatch,
1207                                         struct evdev_input_device *device,
1208                                         struct input_event *e,
1209                                         uint32_t time)
1210 {
1211     WL_UNUSED(dispatch);
1212
1213     switch (e->type)
1214     {
1215     case EV_REL:
1216         evdevProcessRelative(device, time, e);
1217         break;
1218     case EV_ABS:
1219         evdevProcessAbsolute(device, e);
1220         break;
1221     case EV_KEY:
1222         evdevProcessKey(device, time, e);
1223         break;
1224     }
1225 }
1226
1227 void
1228 WaylandEvdevInputEvent::fallbackDestroy(struct evdev_dispatch *dispatch)
1229 {
1230     if (dispatch) free(dispatch);
1231 }
1232
1233 void
1234 WaylandEvdevInputEvent::evdevProcessRelative(struct evdev_input_device *device,
1235                                             uint32_t /*time*/, struct input_event *e)
1236 {
1237     switch (e->code)
1238     {
1239     case REL_X:
1240         device->rel.dx += wl_fixed_from_int(e->value);
1241         device->pending_events |= EVDEV_RELATIVE_MOTION;
1242         break;
1243     case REL_Y:
1244         device->rel.dy += wl_fixed_from_int(e->value);
1245         device->pending_events |= EVDEV_RELATIVE_MOTION;
1246         break;
1247     case REL_WHEEL:
1248     case REL_HWHEEL:
1249         // not supported
1250         break;
1251     }
1252 }
1253
1254 void
1255 WaylandEvdevInputEvent::evdevProcessAbsolute(struct evdev_input_device *device,
1256                                              struct input_event *e)
1257 {
1258     WaylandEvdevInputEvent *inputEvent = static_cast<WaylandEvdevInputEvent*>(device->master);
1259     if (!inputEvent)
1260         return;
1261
1262     int w = inputEvent->m_screenWidth;
1263     int h = inputEvent->m_screenHeight;
1264
1265     if (device->isMt)
1266     {
1267         processTouch(device, e, w, h);
1268     }
1269     else
1270     {
1271         processAbsoluteMotion(device, e, w, h);
1272     }
1273 }
1274
1275 void
1276 WaylandEvdevInputEvent::evdevProcessKey(struct evdev_input_device *device,
1277                                         uint32_t time, struct input_event *e)
1278 {
1279     if (e->value == 2)
1280         return;
1281
1282     switch (e->code)
1283     {
1284     case BTN_LEFT:
1285     case BTN_RIGHT:
1286     case BTN_MIDDLE:
1287     case BTN_SIDE:
1288     case BTN_EXTRA:
1289     case BTN_FORWARD:
1290     case BTN_BACK:
1291     case BTN_TASK:
1292     case BTN_TOUCH:
1293         // notify_button
1294         notifyButton(device, time, e->code,
1295                      e->value ? WL_POINTER_BUTTON_STATE_PRESSED
1296                               : WL_POINTER_BUTTON_STATE_RELEASED);
1297         break;
1298     default:
1299         // notify_key
1300         notifyKey(device, time, e->code,
1301                   e->value ? WL_KEYBOARD_KEY_STATE_PRESSED
1302                            : WL_KEYBOARD_KEY_STATE_RELEASED,
1303                   true);
1304         break;
1305     }
1306 }
1307
1308 /// Multi-touch event handler //////////////////////////////////////////////
1309
1310 void
1311 WaylandEvdevInputEvent::touchpadProcess(struct evdev_dispatch *dispatch,
1312                                         struct evdev_input_device *device,
1313                                         struct input_event *e,
1314                                         uint32_t time)
1315 {
1316     struct touchpad_dispatch *touchpad = (struct touchpad_dispatch*)dispatch;
1317
1318     switch (e->type)
1319     {
1320     case EV_SYN:
1321         if (e->code == SYN_REPORT)
1322             touchpad->event_mask |= TOUCHPAD_EVENT_REPORT;
1323         break;
1324     case EV_ABS:
1325         touchpadProcessAbsolute(touchpad, device, e);
1326         break;
1327     case EV_KEY:
1328         touchpadProcessKey(touchpad, device, e, time);
1329         break;
1330     }
1331
1332     touchpadUpdateState(touchpad, time);
1333 }
1334
1335 void
1336 WaylandEvdevInputEvent::touchpadDestroy(struct evdev_dispatch *dispatch)
1337 {
1338     struct touchpad_dispatch *touchpad = (struct touchpad_dispatch*)dispatch;
1339     struct motion_filter *filter;
1340     struct motion_filter *next;
1341
1342     wl_list_for_each_safe(filter, next, &touchpad->motion_filters, link)
1343     {
1344         filter->interface->destroy(filter);
1345     }
1346
1347     if (dispatch) free(dispatch);
1348 }
1349
1350 void
1351 WaylandEvdevInputEvent::touchpadProcessAbsolute(struct touchpad_dispatch *touchpad,
1352                                                 struct evdev_input_device *device,
1353                                                 struct input_event *e)
1354 {
1355     WL_UNUSED(device);
1356
1357     switch (e->code)
1358     {
1359     case ABS_PRESSURE:
1360         if (e->value > touchpad->pressure.press)
1361             touchpad->state = TOUCHPAD_STATE_PRESS;
1362         else if (e->value > touchpad->pressure.touch_high)
1363             touchpad->state = TOUCHPAD_STATE_TOUCH;
1364         else if (e->value < touchpad->pressure.touch_low)
1365         {
1366             if (touchpad->state > TOUCHPAD_STATE_NONE)
1367                 touchpad->reset = 1;
1368             touchpad->state = TOUCHPAD_STATE_NONE;
1369         }
1370         break;
1371     case ABS_X:
1372         if (touchpad->state >= TOUCHPAD_STATE_TOUCH)
1373         {
1374             touchpad->hw_abs.x = e->value;
1375             touchpad->event_mask |= TOUCHPAD_EVENT_ABSOLUTE_ANY;
1376             touchpad->event_mask |= TOUCHPAD_EVENT_ABSOLUTE_X;
1377         }
1378         break;
1379     case ABS_Y:
1380         if (touchpad->state >= TOUCHPAD_STATE_TOUCH)
1381         {
1382             touchpad->hw_abs.y = e->value;
1383             touchpad->event_mask |= TOUCHPAD_EVENT_ABSOLUTE_ANY;
1384             touchpad->event_mask |= TOUCHPAD_EVENT_ABSOLUTE_Y;
1385         }
1386         break;
1387     }
1388 }
1389
1390 void
1391 WaylandEvdevInputEvent::touchpadProcessKey(struct touchpad_dispatch *touchpad,
1392                                            struct evdev_input_device * device,
1393                                            struct input_event *e,
1394                                            uint32_t time)
1395 {
1396     switch (e->code)
1397     {
1398     case BTN_TOUCH:
1399         if (!touchpad->has_pressure)
1400         {
1401             if (!e->value)
1402             {
1403                 touchpad->state = TOUCHPAD_STATE_NONE;
1404                 touchpad->reset = 1;
1405             }
1406             else
1407             {
1408                 touchpad->state = e->value ? TOUCHPAD_STATE_TOUCH
1409                                            : TOUCHPAD_STATE_NONE;
1410             }
1411         }
1412         break;
1413     case BTN_LEFT:
1414     case BTN_RIGHT:
1415     case BTN_MIDDLE:
1416     case BTN_SIDE:
1417     case BTN_EXTRA:
1418     case BTN_FORWARD:
1419     case BTN_BACK:
1420     case BTN_TASK:
1421         // notify_button
1422         notifyButton(device, time, e->code,
1423                      e->value ? WL_POINTER_BUTTON_STATE_PRESSED
1424                               : WL_POINTER_BUTTON_STATE_RELEASED);
1425         break;
1426     case BTN_TOOL_PEN:
1427     case BTN_TOOL_RUBBER:
1428     case BTN_TOOL_BRUSH:
1429     case BTN_TOOL_PENCIL:
1430     case BTN_TOOL_AIRBRUSH:
1431     case BTN_TOOL_MOUSE:
1432     case BTN_TOOL_LENS:
1433         touchpad->reset = 1;
1434         break;
1435     case BTN_TOOL_FINGER:
1436         touchpad->finger_state =
1437             ~TOUCHPAD_FINGERS_ONE | e->value ? TOUCHPAD_FINGERS_ONE : 0;
1438         break;
1439     case BTN_TOOL_DOUBLETAP:
1440         touchpad->finger_state =
1441             ~TOUCHPAD_FINGERS_TWO | e->value ? TOUCHPAD_FINGERS_TWO : 0;
1442         break;
1443     case BTN_TOOL_TRIPLETAP:
1444         touchpad->finger_state =
1445             ~TOUCHPAD_FINGERS_THREE | e->value ? TOUCHPAD_FINGERS_THREE : 0;
1446         break;
1447     }
1448 }
1449
1450 void
1451 WaylandEvdevInputEvent::touchpadUpdateState(struct touchpad_dispatch *touchpad,
1452                                             uint32_t time)
1453 {
1454     int motion_index;
1455     int center_x;
1456     int center_y;
1457     double dx;
1458     double dy;
1459
1460     if (touchpad->reset ||
1461         touchpad->last_finger_state != touchpad->finger_state)
1462     {
1463         touchpad->reset = 0;
1464         touchpad->motion_count = 0;
1465         touchpad->event_mask = TOUCHPAD_EVENT_NONE;
1466         touchpad->event_mask_filter =
1467             TOUCHPAD_EVENT_ABSOLUTE_X | TOUCHPAD_EVENT_ABSOLUTE_Y;
1468
1469         touchpad->last_finger_state = touchpad->finger_state;
1470
1471         return;
1472     }
1473     touchpad->last_finger_state = touchpad->finger_state;
1474
1475     if (!(touchpad->event_mask & TOUCHPAD_EVENT_REPORT))
1476         return;
1477     else
1478         touchpad->event_mask &= ~TOUCHPAD_EVENT_REPORT;
1479
1480     if ((touchpad->event_mask & touchpad->event_mask_filter) !=
1481         touchpad->event_mask_filter)
1482         return;
1483
1484     touchpad->event_mask_filter = TOUCHPAD_EVENT_ABSOLUTE_ANY;
1485     touchpad->event_mask = 0;
1486
1487     // Avoid noice by moving center only when delta reaches a threshold
1488     // distance from the old center
1489     if (touchpad->motion_count > 0)
1490     {
1491         center_x = hysteresis(touchpad->hw_abs.x,
1492                       touchpad->hysteresis.center_x,
1493                       touchpad->hysteresis.margin_x);
1494         center_y = hysteresis(touchpad->hw_abs.y,
1495                       touchpad->hysteresis.center_y,
1496                       touchpad->hysteresis.margin_y);
1497     }
1498     else
1499     {
1500         center_x = touchpad->hw_abs.x;
1501         center_y = touchpad->hw_abs.y;
1502     }
1503     touchpad->hysteresis.center_x = center_x;
1504     touchpad->hysteresis.center_y = center_y;
1505     touchpad->hw_abs.x = center_x;
1506     touchpad->hw_abs.y = center_y;
1507
1508     // Update motion history tracker
1509     motion_index = (touchpad->motion_index + 1) % TOUCHPAD_HISTORY_LENGTH;
1510     touchpad->motion_index = motion_index;
1511     touchpad->motion_history[motion_index].x = touchpad->hw_abs.x;
1512     touchpad->motion_history[motion_index].y = touchpad->hw_abs.y;
1513     if (touchpad->motion_count < 4)
1514         touchpad->motion_count++;
1515
1516     if (touchpad->motion_count >= 4)
1517     {
1518         touchpadGetDelta(touchpad, &dx, &dy);
1519
1520         filterMotion(touchpad, &dx, &dy, time);
1521
1522         touchpad->device->rel.dx = wl_fixed_from_double(dx);
1523         touchpad->device->rel.dy = wl_fixed_from_double(dy);
1524         touchpad->device->pending_events |= EVDEV_RELATIVE_MOTION;
1525     }
1526 }
1527
1528 /// Notifier ///////////////////////////////////////////////////////////////
1529
1530 void
1531 WaylandEvdevInputEvent::notifyButton(struct evdev_input_device *device,
1532                                      uint32_t time, int32_t button,
1533                                      enum wl_pointer_button_state state)
1534 {
1535     WLEvent         wlEvent;
1536     struct wl_seat *wlSeat = NULL;
1537     uint32_t        serial;
1538
1539     WaylandEvdevInputEvent *inputEvent = static_cast<WaylandEvdevInputEvent*>(device->master);
1540     if (!inputEvent)
1541         return;
1542
1543     wlSeat = inputEvent->inputDevice().seat();
1544     serial = wl_display_next_serial(inputEvent->inputDevice().display());
1545
1546     /**
1547      * @todo Port to Wayland 1.3.
1548      */
1549     // if (state == WL_POINTER_BUTTON_STATE_PRESSED)
1550     // {
1551     //     if (wlSeat->pointer->button_count == 0)
1552     //     {
1553     //         wlSeat->pointer->grab_button = button;
1554     //         wlSeat->pointer->grab_time = time;
1555     //         wlSeat->pointer->grab_x = wlSeat->pointer->x;
1556     //         wlSeat->pointer->grab_y = wlSeat->pointer->y;
1557     //     }
1558     //     ++wlSeat->pointer->button_count;
1559     // }
1560     // else
1561     // {
1562     //     --wlSeat->pointer->button_count;
1563     // }
1564     // wlEvent.x = wl_fixed_to_int(wlSeat->pointer->x);
1565     // wlEvent.y = wl_fixed_to_int(wlSeat->pointer->y);
1566     // wlEvent.buttonState = state;
1567     // wlEvent.serial = serial;
1568
1569     // inputEvent->windowSystem().manageWLInputEvent(INPUT_DEVICE_POINTER,
1570     //     state == WL_POINTER_BUTTON_STATE_PRESSED ? INPUT_STATE_PRESSED :
1571     //     INPUT_STATE_RELEASED, &wlEvent);
1572
1573     // if (wlSeat->pointer->button_count == 1)
1574     // {
1575     //     wlSeat->pointer->grab_serial =
1576     //         wl_display_get_serial(inputEvent->inputDevice().display());
1577     // }
1578 }
1579
1580 void
1581 WaylandEvdevInputEvent::notifyMotion(struct evdev_input_device *device,
1582                                      uint32_t time,
1583                                      wl_fixed_t fx, wl_fixed_t fy)
1584 {
1585     WL_UNUSED(time);
1586
1587     WLEvent         wlEvent;
1588     struct wl_seat *wlSeat = NULL;
1589     int             x;
1590     int             y;
1591     //int             old_x, old_y;
1592     int             w;
1593     int             h;
1594
1595     WaylandEvdevInputEvent *inputEvent = static_cast<WaylandEvdevInputEvent*>(device->master);
1596     if (!inputEvent)
1597         return;
1598
1599     wlSeat = inputEvent->inputDevice().seat();
1600     w = inputEvent->m_screenWidth;
1601     h = inputEvent->m_screenHeight;
1602
1603     x = wl_fixed_to_int(fx);
1604     y = wl_fixed_to_int(fy);
1605     //old_x = wl_fixed_to_int(wlSeat->pointer->x);
1606     //old_y = wl_fixed_to_int(wlSeat->pointer->y);
1607     if (x < 0) x = 0;
1608     if (x > w) x = w;
1609     if (y < 0) y = 0;
1610     if (y > h) y = h;
1611
1612     /**
1613      * @todo Port to Wayland 1.3.
1614      */
1615     // wlSeat->pointer->x = wl_fixed_from_int(x);
1616     // wlSeat->pointer->y = wl_fixed_from_int(y);
1617
1618     wlEvent.x = x;
1619     wlEvent.y = y;
1620
1621     inputEvent->windowSystem().manageWLInputEvent(
1622         INPUT_DEVICE_POINTER, INPUT_STATE_MOTION, &wlEvent);
1623 }
1624
1625 void
1626 WaylandEvdevInputEvent::notifyKey(struct evdev_input_device *device,
1627                                   uint32_t time, uint32_t key,
1628                                   enum wl_keyboard_key_state state,
1629                                   bool bUpdateAutomatic)
1630 {
1631     WL_UNUSED(bUpdateAutomatic);
1632
1633     WLEvent wlEvent;
1634     struct wl_seat *wlSeat = NULL;
1635     uint32_t *k;
1636     uint32_t *end;
1637
1638     WaylandEvdevInputEvent *inputEvent = static_cast<WaylandEvdevInputEvent*>(device->master);
1639     if (!inputEvent)
1640         return;
1641
1642     wlSeat = inputEvent->inputDevice().seat();
1643     if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
1644     {
1645         /**
1646          * @todo Port to Wayland 1.3.
1647          */
1648         // wlSeat->keyboard->grab_key = key;
1649         // wlSeat->keyboard->grab_time = time;
1650     }
1651
1652     /**
1653      * @todo Port to Wayland 1.3.
1654      */
1655     // end = (uint32_t*)(((unsigned char*)wlSeat->keyboard->keys.data) + wlSeat->keyboard->keys.size);
1656     // for (k = (uint32_t*)wlSeat->keyboard->keys.data; k < end; ++k)
1657     // {
1658     //     if (*k == key)
1659     //     {
1660     //         // Ignore server-generated repeats
1661     //         if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
1662     //             return;
1663     //         *k = *--end;
1664     //     }
1665     // }
1666     // wlSeat->keyboard->keys.size = end - (uint32_t*)wlSeat->keyboard->keys.data;
1667     // if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
1668     // {
1669     //     k = (uint32_t*)wl_array_add(&wlSeat->keyboard->keys, sizeof(*k));
1670     //     *k = key;
1671     // }
1672
1673     wlEvent.keyCode = key;
1674     wlEvent.keyState = state;
1675
1676     inputEvent->windowSystem().manageWLInputEvent(INPUT_DEVICE_KEYBOARD,
1677         state == WL_KEYBOARD_KEY_STATE_PRESSED ? INPUT_STATE_PRESSED
1678                                                : INPUT_STATE_RELEASED, &wlEvent);
1679 }
1680
1681 void
1682 WaylandEvdevInputEvent::notifyTouch(struct evdev_input_device *device)
1683 {
1684     WLEvent         wlEvent;
1685     InputEventState eventState = INPUT_STATE_OTHER;
1686
1687     WaylandEvdevInputEvent *inputEvent = static_cast<WaylandEvdevInputEvent*>(device->master);
1688     if (!inputEvent)
1689         return;
1690
1691     if (device->pending_events & EVDEV_ABSOLUTE_MT_DOWN)
1692     {
1693         wlEvent.x = (int)wl_fixed_from_int(device->mt.x[device->mt.slot]);
1694         wlEvent.y = (int)wl_fixed_from_int(device->mt.y[device->mt.slot]);
1695         wlEvent.touchId = device->mt.slot;
1696         wlEvent.touchType = WL_TOUCH_DOWN;
1697         eventState = INPUT_STATE_PRESSED;
1698     }
1699     else if (device->pending_events & EVDEV_ABSOLUTE_MT_MOTION)
1700     {
1701         wlEvent.x = (int)wl_fixed_from_int(device->mt.x[device->mt.slot]);
1702         wlEvent.y = (int)wl_fixed_from_int(device->mt.y[device->mt.slot]);
1703         wlEvent.touchId = device->mt.slot;
1704         wlEvent.touchType = WL_TOUCH_MOTION;
1705         eventState = INPUT_STATE_MOTION;
1706     }
1707     else if (device->pending_events & EVDEV_ABSOLUTE_MT_UP)
1708     {
1709         wlEvent.x = 0;
1710         wlEvent.y = 0;
1711         wlEvent.touchId = device->mt.slot;
1712         wlEvent.touchType = WL_TOUCH_UP;
1713         eventState = INPUT_STATE_RELEASED;
1714     }
1715     else
1716     {
1717         return;
1718     }
1719
1720     inputEvent->windowSystem().manageWLInputEvent(INPUT_DEVICE_TOUCH, eventState, &wlEvent);
1721 }
1722
1723 void
1724 WaylandEvdevInputEvent::notifyModifiers(struct wl_seat *wlSeat, uint32_t serial)
1725 {
1726     uint32_t mods_depressed;
1727     uint32_t mods_latched;
1728     uint32_t mods_locked;
1729     uint32_t group;
1730     uint32_t mods_lookup;
1731     int changed = 0;
1732
1733     mods_depressed = xkb_state_serialize_mods(m_xkbState.state, (xkb_state_component)XKB_STATE_DEPRESSED);
1734     mods_latched = xkb_state_serialize_mods(m_xkbState.state, (xkb_state_component)XKB_STATE_LATCHED);
1735     mods_locked = xkb_state_serialize_mods(m_xkbState.state, (xkb_state_component)XKB_STATE_LOCKED);
1736     group = xkb_state_serialize_mods(m_xkbState.state, (xkb_state_component)XKB_STATE_EFFECTIVE);
1737
1738     /**
1739      * @todo Port to Wayland 1.3.
1740      */
1741     // if (mods_depressed != wlSeat->keyboard->modifiers.mods_depressed ||
1742     //     mods_latched != wlSeat->keyboard->modifiers.mods_latched ||
1743     //     mods_locked != wlSeat->keyboard->modifiers.mods_locked ||
1744     //     group != wlSeat->keyboard->modifiers.group)
1745     // {
1746     //     changed = 1;
1747     // }
1748
1749     // wlSeat->keyboard->modifiers.mods_depressed = mods_depressed;
1750     // wlSeat->keyboard->modifiers.mods_latched = mods_latched;
1751     // wlSeat->keyboard->modifiers.mods_locked = mods_locked;
1752     // wlSeat->keyboard->modifiers.group = group;
1753
1754     // And update the modifier_state for bindings
1755     mods_lookup = mods_depressed | mods_latched;
1756     m_modifierState = 0;
1757     if (mods_lookup & (1 << m_xkbInfo.ctrl_mod))  m_modifierState |= MODIFIER_CTRL;
1758     if (mods_lookup & (1 << m_xkbInfo.alt_mod))   m_modifierState |= MODIFIER_ALT;
1759     if (mods_lookup & (1 << m_xkbInfo.super_mod)) m_modifierState |= MODIFIER_SUPER;
1760     if (mods_lookup & (1 << m_xkbInfo.shift_mod)) m_modifierState |= MODIFIER_SHIFT;
1761
1762     if (changed)
1763     {
1764         m_inputDevice->sendModifiers(serial);
1765     }
1766 }