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