LayerManagement: fixed style warnings triggered by style script update
[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     if (!wlSeat->keyboard)
964     {
965         return;
966     }
967     serial = wl_display_next_serial(m_inputDevice->display());
968     wl_array_init(&wlSeat->keyboard->keys);
969     wl_array_copy(&wlSeat->keyboard->keys, keys);
970
971     struct wl_array *array = &wlSeat->keyboard->keys;
972     for (k = (uint32_t*)array->data;
973         (const char*)k < (const char*)array->data + array->size;
974         ++k)
975     {
976         if (updateState == STATE_UPDATE_AUTOMATIC)
977         {
978             updateModifierState(wlSeat, serial, *k, WL_KEYBOARD_KEY_STATE_PRESSED);
979         }
980     }
981 }
982
983 void
984 WaylandEvdevInputEvent::updateModifierState(struct wl_seat *wlSeat, uint32_t serial,
985                                             uint32_t key, enum wl_keyboard_key_state state)
986 {
987     enum xkb_key_direction direction;
988
989     if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
990         direction = XKB_KEY_DOWN;
991     else
992         direction = XKB_KEY_UP;
993
994     // Offset the keycode by 8, as the evdev XKB rules reflect X's
995     // broken keycode system, which starts at 8.
996     xkb_state_update_key(m_xkbState.state, key + 8, direction);
997
998     notifyModifiers(wlSeat, serial);
999 }
1000
1001 struct evdev_dispatch*
1002 WaylandEvdevInputEvent::createTouchpad(struct evdev_input_device *device)
1003 {
1004     struct touchpad_dispatch *touchpad;
1005
1006     touchpad = (struct touchpad_dispatch*)malloc(sizeof(*touchpad));
1007     if (touchpad == NULL)
1008         return NULL;
1009
1010     touchpad->base.interface = &touchpad_interface;
1011
1012     touchpad->device = device;
1013     wl_list_init(&touchpad->motion_filters);
1014
1015     configureTouchpad(touchpad, device);
1016
1017     return &touchpad->base;
1018 }
1019
1020 void
1021 WaylandEvdevInputEvent::configureTouchpad(struct touchpad_dispatch *touchpad,
1022                                             struct evdev_input_device *device)
1023 {
1024     struct motion_filter *accel;
1025
1026     struct input_absinfo absinfo;
1027     unsigned long abs_bits[NBITS(ABS_MAX)];
1028
1029     double width;
1030     double height;
1031     double diagonal;
1032
1033     // Detect model
1034     touchpad->model = getTouchpadModel(device);
1035
1036     // Configure pressure
1037     ioctl(device->fd, EVIOCGBIT(EV_ABS, sizeof(abs_bits)), abs_bits);
1038     if (TEST_BIT(abs_bits, ABS_PRESSURE))
1039     {
1040         ioctl(device->fd, EVIOCGABS(ABS_PRESSURE), &absinfo);
1041         configureTouchpadPressure(touchpad,
1042                                 absinfo.minimum,
1043                                 absinfo.maximum);
1044     }
1045
1046     // Configure acceleration factor
1047     width = abs(device->abs.max_x - device->abs.min_x);
1048     height = abs(device->abs.max_y - device->abs.min_y);
1049     diagonal = sqrt(width*width + height*height);
1050
1051     touchpad->constant_accel_factor =
1052         DEFAULT_CONSTANT_ACCEL_NUMERATOR / diagonal;
1053
1054     touchpad->min_accel_factor = DEFAULT_MIN_ACCEL_FACTOR;
1055     touchpad->max_accel_factor = DEFAULT_MAX_ACCEL_FACTOR;
1056
1057     touchpad->hysteresis.margin_x = diagonal / DEFAULT_HYSTERESIS_MARGIN_DENOMINATOR;
1058     touchpad->hysteresis.margin_y = diagonal / DEFAULT_HYSTERESIS_MARGIN_DENOMINATOR;
1059     touchpad->hysteresis.center_x = 0;
1060     touchpad->hysteresis.center_y = 0;
1061
1062     // Configure acceleration profile
1063     accel = createPointerAccelatorFilter(touchpadProfile);
1064     wl_list_insert(&touchpad->motion_filters, &accel->link);
1065
1066     // Setup initial state
1067     touchpad->reset = 1;
1068
1069     memset(touchpad->motion_history, 0, sizeof touchpad->motion_history);
1070     touchpad->motion_index = 0;
1071     touchpad->motion_count = 0;
1072
1073     touchpad->state = TOUCHPAD_STATE_NONE;
1074     touchpad->last_finger_state = 0;
1075     touchpad->finger_state = 0;
1076 }
1077
1078 int
1079 WaylandEvdevInputEvent::handleInputEvent(int fd, uint32_t mask, void *data)
1080 {
1081     WL_UNUSED(mask);
1082
1083     struct evdev_input_device *device = (evdev_input_device*)data;
1084     struct input_event ev[32];
1085     int len;
1086     do {
1087         if (device->mtdev)
1088         {
1089             len = mtdev_get(device->mtdev, fd, ev,
1090                 ARRAY_LENGTH(ev)) * sizeof(struct input_event);
1091         }
1092         else
1093         {
1094             len = read(fd, &ev, sizeof(ev));
1095         }
1096
1097         if (len < 0 || len % sizeof(ev[0]) != 0)
1098         {
1099             return 1;
1100         }
1101
1102         WaylandEvdevInputEvent::processEvents(device, ev, len / sizeof(ev[0]));
1103     } while (len > 0);
1104
1105     return 1;
1106 }
1107
1108 void
1109 WaylandEvdevInputEvent::processEvents(struct evdev_input_device *device,
1110                                         struct input_event *ev,
1111                                         int count)
1112 {
1113     struct evdev_dispatch *dispatch = device->dispatch;
1114     struct input_event *e, *end;
1115     uint32_t time = 0;
1116
1117     device->pending_events = 0;
1118
1119     e = ev;
1120     end = e + count;
1121     for (; e < end; ++e)
1122     {
1123         time = e->time.tv_sec * 1000 + e->time.tv_usec / 1000;
1124
1125         if (!isMotionEvent(e))
1126         {
1127             WaylandEvdevInputEvent::flushMotion(device, time);
1128         }
1129
1130         dispatch->interface->process(dispatch, device, e, time);
1131     }
1132
1133     WaylandEvdevInputEvent::flushMotion(device, time);
1134 }
1135
1136 void
1137 WaylandEvdevInputEvent::flushMotion(struct evdev_input_device *device,
1138                                     uint32_t time)
1139 {
1140     if (!device->pending_events)
1141         return;
1142
1143     WaylandEvdevInputEvent *inputEvent = static_cast<WaylandEvdevInputEvent*>(device->master);
1144     if (!inputEvent)
1145         return;
1146
1147     if (device->pending_events & EVDEV_RELATIVE_MOTION)
1148     {
1149         struct wl_seat *wlSeat = inputEvent->inputDevice().seat();
1150         if (wlSeat)
1151         {
1152             // notify_motion
1153             notifyMotion(device, time,
1154                         wlSeat->pointer->x + device->rel.dx,
1155                         wlSeat->pointer->y + device->rel.dy);
1156         }
1157         device->pending_events &= ~EVDEV_RELATIVE_MOTION;
1158         device->rel.dx = 0;
1159         device->rel.dy = 0;
1160     }
1161     if (device->pending_events & EVDEV_ABSOLUTE_MT_DOWN)
1162     {
1163         // notify_touch
1164         notifyTouch(device);
1165         device->pending_events &= ~EVDEV_ABSOLUTE_MT_DOWN;
1166         device->pending_events &= ~EVDEV_ABSOLUTE_MT_MOTION;
1167     }
1168     if (device->pending_events & EVDEV_ABSOLUTE_MT_MOTION)
1169     {
1170         // notify_touch
1171         notifyTouch(device);
1172         device->pending_events &= ~EVDEV_ABSOLUTE_MT_DOWN;
1173         device->pending_events &= ~EVDEV_ABSOLUTE_MT_MOTION;
1174     }
1175     if (device->pending_events & EVDEV_ABSOLUTE_MT_UP)
1176     {
1177         // notify_touch
1178         notifyTouch(device);
1179         device->pending_events &= ~EVDEV_ABSOLUTE_MT_UP;
1180     }
1181     if (device->pending_events & EVDEV_ABSOLUTE_MOTION)
1182     {
1183         // notify_motion
1184         notifyMotion(device, time,
1185                     wl_fixed_from_int(device->abs.x),
1186                     wl_fixed_from_int(device->abs.y));
1187         device->pending_events &= ~EVDEV_ABSOLUTE_MOTION;
1188     }
1189 }
1190
1191 /// Default event handler //////////////////////////////////////////////////
1192
1193 void
1194 WaylandEvdevInputEvent::fallbackProcess(struct evdev_dispatch *dispatch,
1195                                         struct evdev_input_device *device,
1196                                         struct input_event *e,
1197                                         uint32_t time)
1198 {
1199     WL_UNUSED(dispatch);
1200
1201     switch (e->type)
1202     {
1203     case EV_REL:
1204         evdevProcessRelative(device, time, e);
1205         break;
1206     case EV_ABS:
1207         evdevProcessAbsolute(device, e);
1208         break;
1209     case EV_KEY:
1210         evdevProcessKey(device, time, e);
1211         break;
1212     }
1213 }
1214
1215 void
1216 WaylandEvdevInputEvent::fallbackDestroy(struct evdev_dispatch *dispatch)
1217 {
1218     if (dispatch) free(dispatch);
1219 }
1220
1221 void
1222 WaylandEvdevInputEvent::evdevProcessRelative(struct evdev_input_device *device,
1223                                             uint32_t /*time*/, struct input_event *e)
1224 {
1225     switch (e->code)
1226     {
1227     case REL_X:
1228         device->rel.dx += wl_fixed_from_int(e->value);
1229         device->pending_events |= EVDEV_RELATIVE_MOTION;
1230         break;
1231     case REL_Y:
1232         device->rel.dy += wl_fixed_from_int(e->value);
1233         device->pending_events |= EVDEV_RELATIVE_MOTION;
1234         break;
1235     case REL_WHEEL:
1236     case REL_HWHEEL:
1237         // not supported
1238         break;
1239     }
1240 }
1241
1242 void
1243 WaylandEvdevInputEvent::evdevProcessAbsolute(struct evdev_input_device *device,
1244                                              struct input_event *e)
1245 {
1246     WaylandEvdevInputEvent *inputEvent = static_cast<WaylandEvdevInputEvent*>(device->master);
1247     if (!inputEvent)
1248         return;
1249
1250     int w = inputEvent->m_screenWidth;
1251     int h = inputEvent->m_screenHeight;
1252
1253     if (device->isMt)
1254     {
1255         processTouch(device, e, w, h);
1256     }
1257     else
1258     {
1259         processAbsoluteMotion(device, e, w, h);
1260     }
1261 }
1262
1263 void
1264 WaylandEvdevInputEvent::evdevProcessKey(struct evdev_input_device *device,
1265                                         uint32_t time, struct input_event *e)
1266 {
1267     if (e->value == 2)
1268         return;
1269
1270     switch (e->code)
1271     {
1272     case BTN_LEFT:
1273     case BTN_RIGHT:
1274     case BTN_MIDDLE:
1275     case BTN_SIDE:
1276     case BTN_EXTRA:
1277     case BTN_FORWARD:
1278     case BTN_BACK:
1279     case BTN_TASK:
1280     case BTN_TOUCH:
1281         // notify_button
1282         notifyButton(device, time, e->code,
1283                      e->value ? WL_POINTER_BUTTON_STATE_PRESSED
1284                               : WL_POINTER_BUTTON_STATE_RELEASED);
1285         break;
1286     default:
1287         // notify_key
1288         notifyKey(device, time, e->code,
1289                   e->value ? WL_KEYBOARD_KEY_STATE_PRESSED
1290                            : WL_KEYBOARD_KEY_STATE_RELEASED,
1291                   true);
1292         break;
1293     }
1294 }
1295
1296 /// Multi-touch event handler //////////////////////////////////////////////
1297
1298 void
1299 WaylandEvdevInputEvent::touchpadProcess(struct evdev_dispatch *dispatch,
1300                                         struct evdev_input_device *device,
1301                                         struct input_event *e,
1302                                         uint32_t time)
1303 {
1304     struct touchpad_dispatch *touchpad = (struct touchpad_dispatch*)dispatch;
1305
1306     switch (e->type)
1307     {
1308     case EV_SYN:
1309         if (e->code == SYN_REPORT)
1310             touchpad->event_mask |= TOUCHPAD_EVENT_REPORT;
1311         break;
1312     case EV_ABS:
1313         touchpadProcessAbsolute(touchpad, device, e);
1314         break;
1315     case EV_KEY:
1316         touchpadProcessKey(touchpad, device, e, time);
1317         break;
1318     }
1319
1320     touchpadUpdateState(touchpad, time);
1321 }
1322
1323 void
1324 WaylandEvdevInputEvent::touchpadDestroy(struct evdev_dispatch *dispatch)
1325 {
1326     struct touchpad_dispatch *touchpad = (struct touchpad_dispatch*)dispatch;
1327     struct motion_filter *filter;
1328     struct motion_filter *next;
1329
1330     wl_list_for_each_safe(filter, next, &touchpad->motion_filters, link)
1331     {
1332         filter->interface->destroy(filter);
1333     }
1334
1335     if (dispatch) free(dispatch);
1336 }
1337
1338 void
1339 WaylandEvdevInputEvent::touchpadProcessAbsolute(struct touchpad_dispatch *touchpad,
1340                                                 struct evdev_input_device *device,
1341                                                 struct input_event *e)
1342 {
1343     WL_UNUSED(device);
1344
1345     switch (e->code)
1346     {
1347     case ABS_PRESSURE:
1348         if (e->value > touchpad->pressure.press)
1349             touchpad->state = TOUCHPAD_STATE_PRESS;
1350         else if (e->value > touchpad->pressure.touch_high)
1351             touchpad->state = TOUCHPAD_STATE_TOUCH;
1352         else if (e->value < touchpad->pressure.touch_low)
1353         {
1354             if (touchpad->state > TOUCHPAD_STATE_NONE)
1355                 touchpad->reset = 1;
1356             touchpad->state = TOUCHPAD_STATE_NONE;
1357         }
1358         break;
1359     case ABS_X:
1360         if (touchpad->state >= TOUCHPAD_STATE_TOUCH)
1361         {
1362             touchpad->hw_abs.x = e->value;
1363             touchpad->event_mask |= TOUCHPAD_EVENT_ABSOLUTE_ANY;
1364             touchpad->event_mask |= TOUCHPAD_EVENT_ABSOLUTE_X;
1365         }
1366         break;
1367     case ABS_Y:
1368         if (touchpad->state >= TOUCHPAD_STATE_TOUCH)
1369         {
1370             touchpad->hw_abs.y = e->value;
1371             touchpad->event_mask |= TOUCHPAD_EVENT_ABSOLUTE_ANY;
1372             touchpad->event_mask |= TOUCHPAD_EVENT_ABSOLUTE_Y;
1373         }
1374         break;
1375     }
1376 }
1377
1378 void
1379 WaylandEvdevInputEvent::touchpadProcessKey(struct touchpad_dispatch *touchpad,
1380                                            struct evdev_input_device * device,
1381                                            struct input_event *e,
1382                                            uint32_t time)
1383 {
1384     switch (e->code)
1385     {
1386     case BTN_TOUCH:
1387         if (!touchpad->has_pressure)
1388         {
1389             if (!e->value)
1390             {
1391                 touchpad->state = TOUCHPAD_STATE_NONE;
1392                 touchpad->reset = 1;
1393             }
1394             else
1395             {
1396                 touchpad->state = e->value ? TOUCHPAD_STATE_TOUCH
1397                                            : TOUCHPAD_STATE_NONE;
1398             }
1399         }
1400         break;
1401     case BTN_LEFT:
1402     case BTN_RIGHT:
1403     case BTN_MIDDLE:
1404     case BTN_SIDE:
1405     case BTN_EXTRA:
1406     case BTN_FORWARD:
1407     case BTN_BACK:
1408     case BTN_TASK:
1409         // notify_button
1410         notifyButton(device, time, e->code,
1411                      e->value ? WL_POINTER_BUTTON_STATE_PRESSED
1412                               : WL_POINTER_BUTTON_STATE_RELEASED);
1413         break;
1414     case BTN_TOOL_PEN:
1415     case BTN_TOOL_RUBBER:
1416     case BTN_TOOL_BRUSH:
1417     case BTN_TOOL_PENCIL:
1418     case BTN_TOOL_AIRBRUSH:
1419     case BTN_TOOL_MOUSE:
1420     case BTN_TOOL_LENS:
1421         touchpad->reset = 1;
1422         break;
1423     case BTN_TOOL_FINGER:
1424         touchpad->finger_state =
1425             ~TOUCHPAD_FINGERS_ONE | e->value ? TOUCHPAD_FINGERS_ONE : 0;
1426         break;
1427     case BTN_TOOL_DOUBLETAP:
1428         touchpad->finger_state =
1429             ~TOUCHPAD_FINGERS_TWO | e->value ? TOUCHPAD_FINGERS_TWO : 0;
1430         break;
1431     case BTN_TOOL_TRIPLETAP:
1432         touchpad->finger_state =
1433             ~TOUCHPAD_FINGERS_THREE | e->value ? TOUCHPAD_FINGERS_THREE : 0;
1434         break;
1435     }
1436 }
1437
1438 void
1439 WaylandEvdevInputEvent::touchpadUpdateState(struct touchpad_dispatch *touchpad,
1440                                             uint32_t time)
1441 {
1442     int motion_index;
1443     int center_x;
1444     int center_y;
1445     double dx;
1446     double dy;
1447
1448     if (touchpad->reset ||
1449         touchpad->last_finger_state != touchpad->finger_state)
1450     {
1451         touchpad->reset = 0;
1452         touchpad->motion_count = 0;
1453         touchpad->event_mask = TOUCHPAD_EVENT_NONE;
1454         touchpad->event_mask_filter =
1455             TOUCHPAD_EVENT_ABSOLUTE_X | TOUCHPAD_EVENT_ABSOLUTE_Y;
1456
1457         touchpad->last_finger_state = touchpad->finger_state;
1458
1459         return;
1460     }
1461     touchpad->last_finger_state = touchpad->finger_state;
1462
1463     if (!(touchpad->event_mask & TOUCHPAD_EVENT_REPORT))
1464         return;
1465     else
1466         touchpad->event_mask &= ~TOUCHPAD_EVENT_REPORT;
1467
1468     if ((touchpad->event_mask & touchpad->event_mask_filter) !=
1469         touchpad->event_mask_filter)
1470         return;
1471
1472     touchpad->event_mask_filter = TOUCHPAD_EVENT_ABSOLUTE_ANY;
1473     touchpad->event_mask = 0;
1474
1475     // Avoid noice by moving center only when delta reaches a threshold
1476     // distance from the old center
1477     if (touchpad->motion_count > 0)
1478     {
1479         center_x = hysteresis(touchpad->hw_abs.x,
1480                       touchpad->hysteresis.center_x,
1481                       touchpad->hysteresis.margin_x);
1482         center_y = hysteresis(touchpad->hw_abs.y,
1483                       touchpad->hysteresis.center_y,
1484                       touchpad->hysteresis.margin_y);
1485     }
1486     else
1487     {
1488         center_x = touchpad->hw_abs.x;
1489         center_y = touchpad->hw_abs.y;
1490     }
1491     touchpad->hysteresis.center_x = center_x;
1492     touchpad->hysteresis.center_y = center_y;
1493     touchpad->hw_abs.x = center_x;
1494     touchpad->hw_abs.y = center_y;
1495
1496     // Update motion history tracker
1497     motion_index = (touchpad->motion_index + 1) % TOUCHPAD_HISTORY_LENGTH;
1498     touchpad->motion_index = motion_index;
1499     touchpad->motion_history[motion_index].x = touchpad->hw_abs.x;
1500     touchpad->motion_history[motion_index].y = touchpad->hw_abs.y;
1501     if (touchpad->motion_count < 4)
1502         touchpad->motion_count++;
1503
1504     if (touchpad->motion_count >= 4)
1505     {
1506         touchpadGetDelta(touchpad, &dx, &dy);
1507
1508         filterMotion(touchpad, &dx, &dy, time);
1509
1510         touchpad->device->rel.dx = wl_fixed_from_double(dx);
1511         touchpad->device->rel.dy = wl_fixed_from_double(dy);
1512         touchpad->device->pending_events |= EVDEV_RELATIVE_MOTION;
1513     }
1514 }
1515
1516 /// Notifier ///////////////////////////////////////////////////////////////
1517
1518 void
1519 WaylandEvdevInputEvent::notifyButton(struct evdev_input_device *device,
1520                                      uint32_t time, int32_t button,
1521                                      enum wl_pointer_button_state state)
1522 {
1523     WLEvent         wlEvent;
1524     struct wl_seat *wlSeat = NULL;
1525     uint32_t        serial;
1526
1527     WaylandEvdevInputEvent *inputEvent = static_cast<WaylandEvdevInputEvent*>(device->master);
1528     if (!inputEvent)
1529         return;
1530
1531     wlSeat = inputEvent->inputDevice().seat();
1532     serial = wl_display_next_serial(inputEvent->inputDevice().display());
1533
1534     if (state == WL_POINTER_BUTTON_STATE_PRESSED)
1535     {
1536         if (wlSeat->pointer->button_count == 0)
1537         {
1538             wlSeat->pointer->grab_button = button;
1539             wlSeat->pointer->grab_time = time;
1540             wlSeat->pointer->grab_x = wlSeat->pointer->x;
1541             wlSeat->pointer->grab_y = wlSeat->pointer->y;
1542         }
1543         ++wlSeat->pointer->button_count;
1544     }
1545     else
1546     {
1547         --wlSeat->pointer->button_count;
1548     }
1549     wlEvent.x = wl_fixed_to_int(wlSeat->pointer->x);
1550     wlEvent.y = wl_fixed_to_int(wlSeat->pointer->y);
1551     wlEvent.buttonState = state;
1552     wlEvent.serial = serial;
1553
1554     inputEvent->windowSystem().manageWLInputEvent(INPUT_DEVICE_POINTER,
1555         state == WL_POINTER_BUTTON_STATE_PRESSED ? INPUT_STATE_PRESSED :
1556         INPUT_STATE_RELEASED, &wlEvent);
1557
1558     if (wlSeat->pointer->button_count == 1)
1559     {
1560         wlSeat->pointer->grab_serial =
1561             wl_display_get_serial(inputEvent->inputDevice().display());
1562     }
1563 }
1564
1565 void
1566 WaylandEvdevInputEvent::notifyMotion(struct evdev_input_device *device,
1567                                      uint32_t time,
1568                                      wl_fixed_t fx, wl_fixed_t fy)
1569 {
1570     WL_UNUSED(time);
1571
1572     WLEvent         wlEvent;
1573     struct wl_seat *wlSeat = NULL;
1574     int             x;
1575     int             y;
1576     //int             old_x, old_y;
1577     int             w;
1578     int             h;
1579
1580     WaylandEvdevInputEvent *inputEvent = static_cast<WaylandEvdevInputEvent*>(device->master);
1581     if (!inputEvent)
1582         return;
1583
1584     wlSeat = inputEvent->inputDevice().seat();
1585     w = inputEvent->m_screenWidth;
1586     h = inputEvent->m_screenHeight;
1587
1588     x = wl_fixed_to_int(fx);
1589     y = wl_fixed_to_int(fy);
1590     //old_x = wl_fixed_to_int(wlSeat->pointer->x);
1591     //old_y = wl_fixed_to_int(wlSeat->pointer->y);
1592     if (x < 0) x = 0;
1593     if (x > w) x = w;
1594     if (y < 0) y = 0;
1595     if (y > h) y = h;
1596
1597     wlSeat->pointer->x = wl_fixed_from_int(x);
1598     wlSeat->pointer->y = wl_fixed_from_int(y);
1599
1600     wlEvent.x = x;
1601     wlEvent.y = y;
1602
1603     inputEvent->windowSystem().manageWLInputEvent(
1604         INPUT_DEVICE_POINTER, INPUT_STATE_MOTION, &wlEvent);
1605 }
1606
1607 void
1608 WaylandEvdevInputEvent::notifyKey(struct evdev_input_device *device,
1609                                   uint32_t time, uint32_t key,
1610                                   enum wl_keyboard_key_state state,
1611                                   bool bUpdateAutomatic)
1612 {
1613     WL_UNUSED(bUpdateAutomatic);
1614
1615     WLEvent wlEvent;
1616     struct wl_seat *wlSeat = NULL;
1617     uint32_t *k;
1618     uint32_t *end;
1619
1620     WaylandEvdevInputEvent *inputEvent = static_cast<WaylandEvdevInputEvent*>(device->master);
1621     if (!inputEvent)
1622         return;
1623
1624     wlSeat = inputEvent->inputDevice().seat();
1625     if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
1626     {
1627         wlSeat->keyboard->grab_key = key;
1628         wlSeat->keyboard->grab_time = time;
1629     }
1630
1631     end = (uint32_t*)(((unsigned char*)wlSeat->keyboard->keys.data) + wlSeat->keyboard->keys.size);
1632     for (k = (uint32_t*)wlSeat->keyboard->keys.data; k < end; ++k)
1633     {
1634         if (*k == key)
1635         {
1636             // Ignore server-generated repeats
1637             if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
1638                 return;
1639             *k = *--end;
1640         }
1641     }
1642     wlSeat->keyboard->keys.size = end - (uint32_t*)wlSeat->keyboard->keys.data;
1643     if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
1644     {
1645         k = (uint32_t*)wl_array_add(&wlSeat->keyboard->keys, sizeof(*k));
1646         *k = key;
1647     }
1648
1649     wlEvent.keyCode = key;
1650     wlEvent.keyState = state;
1651
1652     inputEvent->windowSystem().manageWLInputEvent(INPUT_DEVICE_KEYBOARD,
1653         state == WL_KEYBOARD_KEY_STATE_PRESSED ? INPUT_STATE_PRESSED
1654                                                : INPUT_STATE_RELEASED, &wlEvent);
1655 }
1656
1657 void
1658 WaylandEvdevInputEvent::notifyTouch(struct evdev_input_device *device)
1659 {
1660     WLEvent         wlEvent;
1661     InputEventState eventState = INPUT_STATE_OTHER;
1662
1663     WaylandEvdevInputEvent *inputEvent = static_cast<WaylandEvdevInputEvent*>(device->master);
1664     if (!inputEvent)
1665         return;
1666
1667     if (device->pending_events & EVDEV_ABSOLUTE_MT_DOWN)
1668     {
1669         wlEvent.x = (int)wl_fixed_from_int(device->mt.x[device->mt.slot]);
1670         wlEvent.y = (int)wl_fixed_from_int(device->mt.y[device->mt.slot]);
1671         wlEvent.touchId = device->mt.slot;
1672         wlEvent.touchType = WL_TOUCH_DOWN;
1673         eventState = INPUT_STATE_PRESSED;
1674     }
1675     else if (device->pending_events & EVDEV_ABSOLUTE_MT_MOTION)
1676     {
1677         wlEvent.x = (int)wl_fixed_from_int(device->mt.x[device->mt.slot]);
1678         wlEvent.y = (int)wl_fixed_from_int(device->mt.y[device->mt.slot]);
1679         wlEvent.touchId = device->mt.slot;
1680         wlEvent.touchType = WL_TOUCH_MOTION;
1681         eventState = INPUT_STATE_MOTION;
1682     }
1683     else if (device->pending_events & EVDEV_ABSOLUTE_MT_UP)
1684     {
1685         wlEvent.x = 0;
1686         wlEvent.y = 0;
1687         wlEvent.touchId = device->mt.slot;
1688         wlEvent.touchType = WL_TOUCH_UP;
1689         eventState = INPUT_STATE_RELEASED;
1690     }
1691     else
1692     {
1693         return;
1694     }
1695
1696     inputEvent->windowSystem().manageWLInputEvent(INPUT_DEVICE_TOUCH, eventState, &wlEvent);
1697 }
1698
1699 void
1700 WaylandEvdevInputEvent::notifyModifiers(struct wl_seat *wlSeat, uint32_t serial)
1701 {
1702     uint32_t mods_depressed;
1703     uint32_t mods_latched;
1704     uint32_t mods_locked;
1705     uint32_t group;
1706     uint32_t mods_lookup;
1707     int changed = 0;
1708
1709     mods_depressed = xkb_state_serialize_mods(m_xkbState.state, (xkb_state_component)XKB_STATE_DEPRESSED);
1710     mods_latched = xkb_state_serialize_mods(m_xkbState.state, (xkb_state_component)XKB_STATE_LATCHED);
1711     mods_locked = xkb_state_serialize_mods(m_xkbState.state, (xkb_state_component)XKB_STATE_LOCKED);
1712     group = xkb_state_serialize_mods(m_xkbState.state, (xkb_state_component)XKB_STATE_EFFECTIVE);
1713
1714     if (mods_depressed != wlSeat->keyboard->modifiers.mods_depressed ||
1715         mods_latched != wlSeat->keyboard->modifiers.mods_latched ||
1716         mods_locked != wlSeat->keyboard->modifiers.mods_locked ||
1717         group != wlSeat->keyboard->modifiers.group)
1718     {
1719         changed = 1;
1720     }
1721
1722     wlSeat->keyboard->modifiers.mods_depressed = mods_depressed;
1723     wlSeat->keyboard->modifiers.mods_latched = mods_latched;
1724     wlSeat->keyboard->modifiers.mods_locked = mods_locked;
1725     wlSeat->keyboard->modifiers.group = group;
1726
1727     // And update the modifier_state for bindings
1728     mods_lookup = mods_depressed | mods_latched;
1729     m_modifierState = 0;
1730     if (mods_lookup & (1 << m_xkbInfo.ctrl_mod))  m_modifierState |= MODIFIER_CTRL;
1731     if (mods_lookup & (1 << m_xkbInfo.alt_mod))   m_modifierState |= MODIFIER_ALT;
1732     if (mods_lookup & (1 << m_xkbInfo.super_mod)) m_modifierState |= MODIFIER_SUPER;
1733     if (mods_lookup & (1 << m_xkbInfo.shift_mod)) m_modifierState |= MODIFIER_SHIFT;
1734
1735     if (changed)
1736     {
1737         m_inputDevice->sendModifiers(serial);
1738     }
1739 }