libweston: Introduce input-timestamps support
[platform/upstream/weston.git] / libweston / input.c
1 /*
2  * Copyright © 2013 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining
5  * a copy of this software and associated documentation files (the
6  * "Software"), to deal in the Software without restriction, including
7  * without limitation the rights to use, copy, modify, merge, publish,
8  * distribute, sublicense, and/or sell copies of the Software, and to
9  * permit persons to whom the Software is furnished to do so, subject to
10  * the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the
13  * next paragraph) shall be included in all copies or substantial
14  * portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
20  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
21  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23  * SOFTWARE.
24  */
25
26 #include "config.h"
27
28 #include <stdbool.h>
29 #include <stdlib.h>
30 #include <stdint.h>
31 #include <string.h>
32 #include <sys/mman.h>
33 #include <assert.h>
34 #include <unistd.h>
35 #include <values.h>
36 #include <fcntl.h>
37 #include <limits.h>
38
39 #include "shared/helpers.h"
40 #include "shared/os-compatibility.h"
41 #include "shared/timespec-util.h"
42 #include "compositor.h"
43 #include "relative-pointer-unstable-v1-server-protocol.h"
44 #include "pointer-constraints-unstable-v1-server-protocol.h"
45 #include "input-timestamps-unstable-v1-server-protocol.h"
46
47 enum pointer_constraint_type {
48         POINTER_CONSTRAINT_TYPE_LOCK,
49         POINTER_CONSTRAINT_TYPE_CONFINE,
50 };
51
52 enum motion_direction {
53         MOTION_DIRECTION_POSITIVE_X = 1 << 0,
54         MOTION_DIRECTION_NEGATIVE_X = 1 << 1,
55         MOTION_DIRECTION_POSITIVE_Y = 1 << 2,
56         MOTION_DIRECTION_NEGATIVE_Y = 1 << 3,
57 };
58
59 struct vec2d {
60         double x, y;
61 };
62
63 struct line {
64         struct vec2d a;
65         struct vec2d b;
66 };
67
68 struct border {
69         struct line line;
70         enum motion_direction blocking_dir;
71 };
72
73 static void
74 maybe_warp_confined_pointer(struct weston_pointer_constraint *constraint);
75
76 static void
77 empty_region(pixman_region32_t *region)
78 {
79         pixman_region32_fini(region);
80         pixman_region32_init(region);
81 }
82
83 static void
84 region_init_infinite(pixman_region32_t *region)
85 {
86         pixman_region32_init_rect(region, INT32_MIN, INT32_MIN,
87                                   UINT32_MAX, UINT32_MAX);
88 }
89
90 static struct weston_pointer_client *
91 weston_pointer_client_create(struct wl_client *client)
92 {
93         struct weston_pointer_client *pointer_client;
94
95         pointer_client = zalloc(sizeof *pointer_client);
96         if (!pointer_client)
97                 return NULL;
98
99         pointer_client->client = client;
100         wl_list_init(&pointer_client->pointer_resources);
101         wl_list_init(&pointer_client->relative_pointer_resources);
102
103         return pointer_client;
104 }
105
106 static void
107 weston_pointer_client_destroy(struct weston_pointer_client *pointer_client)
108 {
109         struct wl_resource *resource;
110
111         wl_resource_for_each(resource, &pointer_client->pointer_resources) {
112                 wl_resource_set_user_data(resource, NULL);
113         }
114
115         wl_resource_for_each(resource,
116                              &pointer_client->relative_pointer_resources) {
117                 wl_resource_set_user_data(resource, NULL);
118         }
119
120         wl_list_remove(&pointer_client->pointer_resources);
121         wl_list_remove(&pointer_client->relative_pointer_resources);
122         free(pointer_client);
123 }
124
125 static bool
126 weston_pointer_client_is_empty(struct weston_pointer_client *pointer_client)
127 {
128         return (wl_list_empty(&pointer_client->pointer_resources) &&
129                 wl_list_empty(&pointer_client->relative_pointer_resources));
130 }
131
132 static struct weston_pointer_client *
133 weston_pointer_get_pointer_client(struct weston_pointer *pointer,
134                                   struct wl_client *client)
135 {
136         struct weston_pointer_client *pointer_client;
137
138         wl_list_for_each(pointer_client, &pointer->pointer_clients, link) {
139                 if (pointer_client->client == client)
140                         return pointer_client;
141         }
142
143         return NULL;
144 }
145
146 static struct weston_pointer_client *
147 weston_pointer_ensure_pointer_client(struct weston_pointer *pointer,
148                                      struct wl_client *client)
149 {
150         struct weston_pointer_client *pointer_client;
151
152         pointer_client = weston_pointer_get_pointer_client(pointer, client);
153         if (pointer_client)
154                 return pointer_client;
155
156         pointer_client = weston_pointer_client_create(client);
157         wl_list_insert(&pointer->pointer_clients, &pointer_client->link);
158
159         if (pointer->focus &&
160             pointer->focus->surface->resource &&
161             wl_resource_get_client(pointer->focus->surface->resource) == client) {
162                 pointer->focus_client = pointer_client;
163         }
164
165         return pointer_client;
166 }
167
168 static void
169 weston_pointer_cleanup_pointer_client(struct weston_pointer *pointer,
170                                       struct weston_pointer_client *pointer_client)
171 {
172         if (weston_pointer_client_is_empty(pointer_client)) {
173                 if (pointer->focus_client == pointer_client)
174                         pointer->focus_client = NULL;
175                 wl_list_remove(&pointer_client->link);
176                 weston_pointer_client_destroy(pointer_client);
177         }
178 }
179
180 static void
181 unbind_pointer_client_resource(struct wl_resource *resource)
182 {
183         struct weston_pointer *pointer = wl_resource_get_user_data(resource);
184         struct wl_client *client = wl_resource_get_client(resource);
185         struct weston_pointer_client *pointer_client;
186
187         wl_list_remove(wl_resource_get_link(resource));
188
189         if (pointer) {
190                 pointer_client = weston_pointer_get_pointer_client(pointer,
191                                                                    client);
192                 assert(pointer_client);
193                 weston_pointer_cleanup_pointer_client(pointer, pointer_client);
194         }
195 }
196
197 static void unbind_resource(struct wl_resource *resource)
198 {
199         wl_list_remove(wl_resource_get_link(resource));
200 }
201
202 WL_EXPORT void
203 weston_pointer_motion_to_abs(struct weston_pointer *pointer,
204                              struct weston_pointer_motion_event *event,
205                              wl_fixed_t *x, wl_fixed_t *y)
206 {
207         if (event->mask & WESTON_POINTER_MOTION_ABS) {
208                 *x = wl_fixed_from_double(event->x);
209                 *y = wl_fixed_from_double(event->y);
210         } else if (event->mask & WESTON_POINTER_MOTION_REL) {
211                 *x = pointer->x + wl_fixed_from_double(event->dx);
212                 *y = pointer->y + wl_fixed_from_double(event->dy);
213         } else {
214                 assert(!"invalid motion event");
215                 *x = *y = 0;
216         }
217 }
218
219 static bool
220 weston_pointer_motion_to_rel(struct weston_pointer *pointer,
221                              struct weston_pointer_motion_event *event,
222                              double *dx, double *dy,
223                              double *dx_unaccel, double *dy_unaccel)
224 {
225         if (event->mask & WESTON_POINTER_MOTION_REL &&
226             event->mask & WESTON_POINTER_MOTION_REL_UNACCEL) {
227                 *dx = event->dx;
228                 *dy = event->dy;
229                 *dx_unaccel = event->dx_unaccel;
230                 *dy_unaccel = event->dy_unaccel;
231                 return true;
232         } else if (event->mask & WESTON_POINTER_MOTION_REL) {
233                 *dx_unaccel = *dx = event->dx;
234                 *dy_unaccel = *dy = event->dy;
235                 return true;
236         } else if (event->mask & WESTON_POINTER_MOTION_REL_UNACCEL) {
237                 *dx_unaccel = *dx = event->dx_unaccel;
238                 *dy_unaccel = *dy = event->dy_unaccel;
239                 return true;
240         } else {
241                 return false;
242         }
243 }
244
245 WL_EXPORT void
246 weston_seat_repick(struct weston_seat *seat)
247 {
248         const struct weston_pointer *pointer = weston_seat_get_pointer(seat);
249
250         if (!pointer)
251                 return;
252
253         pointer->grab->interface->focus(pointer->grab);
254 }
255
256 static void
257 weston_compositor_idle_inhibit(struct weston_compositor *compositor)
258 {
259         weston_compositor_wake(compositor);
260         compositor->idle_inhibit++;
261 }
262
263 static void
264 weston_compositor_idle_release(struct weston_compositor *compositor)
265 {
266         compositor->idle_inhibit--;
267         weston_compositor_wake(compositor);
268 }
269
270 static void
271 pointer_focus_view_destroyed(struct wl_listener *listener, void *data)
272 {
273         struct weston_pointer *pointer =
274                 container_of(listener, struct weston_pointer,
275                              focus_view_listener);
276
277         weston_pointer_clear_focus(pointer);
278 }
279
280 static void
281 pointer_focus_resource_destroyed(struct wl_listener *listener, void *data)
282 {
283         struct weston_pointer *pointer =
284                 container_of(listener, struct weston_pointer,
285                              focus_resource_listener);
286
287         weston_pointer_clear_focus(pointer);
288 }
289
290 static void
291 keyboard_focus_resource_destroyed(struct wl_listener *listener, void *data)
292 {
293         struct weston_keyboard *keyboard =
294                 container_of(listener, struct weston_keyboard,
295                              focus_resource_listener);
296
297         weston_keyboard_set_focus(keyboard, NULL);
298 }
299
300 static void
301 touch_focus_view_destroyed(struct wl_listener *listener, void *data)
302 {
303         struct weston_touch *touch =
304                 container_of(listener, struct weston_touch,
305                              focus_view_listener);
306
307         weston_touch_set_focus(touch, NULL);
308 }
309
310 static void
311 touch_focus_resource_destroyed(struct wl_listener *listener, void *data)
312 {
313         struct weston_touch *touch =
314                 container_of(listener, struct weston_touch,
315                              focus_resource_listener);
316
317         weston_touch_set_focus(touch, NULL);
318 }
319
320 static void
321 move_resources(struct wl_list *destination, struct wl_list *source)
322 {
323         wl_list_insert_list(destination, source);
324         wl_list_init(source);
325 }
326
327 static void
328 move_resources_for_client(struct wl_list *destination,
329                           struct wl_list *source,
330                           struct wl_client *client)
331 {
332         struct wl_resource *resource, *tmp;
333         wl_resource_for_each_safe(resource, tmp, source) {
334                 if (wl_resource_get_client(resource) == client) {
335                         wl_list_remove(wl_resource_get_link(resource));
336                         wl_list_insert(destination,
337                                        wl_resource_get_link(resource));
338                 }
339         }
340 }
341
342 static void
343 default_grab_pointer_focus(struct weston_pointer_grab *grab)
344 {
345         struct weston_pointer *pointer = grab->pointer;
346         struct weston_view *view;
347         wl_fixed_t sx, sy;
348
349         if (pointer->button_count > 0)
350                 return;
351
352         view = weston_compositor_pick_view(pointer->seat->compositor,
353                                            pointer->x, pointer->y,
354                                            &sx, &sy);
355
356         if (pointer->focus != view || pointer->sx != sx || pointer->sy != sy)
357                 weston_pointer_set_focus(pointer, view, sx, sy);
358 }
359
360 static void
361 pointer_send_relative_motion(struct weston_pointer *pointer,
362                              const struct timespec *time,
363                              struct weston_pointer_motion_event *event)
364 {
365         uint64_t time_usec;
366         double dx, dy, dx_unaccel, dy_unaccel;
367         wl_fixed_t dxf, dyf, dxf_unaccel, dyf_unaccel;
368         struct wl_list *resource_list;
369         struct wl_resource *resource;
370
371         if (!pointer->focus_client)
372                 return;
373
374         if (!weston_pointer_motion_to_rel(pointer, event,
375                                           &dx, &dy,
376                                           &dx_unaccel, &dy_unaccel))
377                 return;
378
379         resource_list = &pointer->focus_client->relative_pointer_resources;
380         time_usec = timespec_to_usec(&event->time);
381         if (time_usec == 0)
382                 time_usec = timespec_to_usec(time);
383
384         dxf = wl_fixed_from_double(dx);
385         dyf = wl_fixed_from_double(dy);
386         dxf_unaccel = wl_fixed_from_double(dx_unaccel);
387         dyf_unaccel = wl_fixed_from_double(dy_unaccel);
388
389         wl_resource_for_each(resource, resource_list) {
390                 zwp_relative_pointer_v1_send_relative_motion(
391                         resource,
392                         (uint32_t) (time_usec >> 32),
393                         (uint32_t) time_usec,
394                         dxf, dyf,
395                         dxf_unaccel, dyf_unaccel);
396         }
397 }
398
399 static void
400 pointer_send_motion(struct weston_pointer *pointer,
401                     const struct timespec *time,
402                     wl_fixed_t sx, wl_fixed_t sy)
403 {
404         struct wl_list *resource_list;
405         struct wl_resource *resource;
406         uint32_t msecs;
407
408         if (!pointer->focus_client)
409                 return;
410
411         resource_list = &pointer->focus_client->pointer_resources;
412         msecs = timespec_to_msec(time);
413         wl_resource_for_each(resource, resource_list)
414                 wl_pointer_send_motion(resource, msecs, sx, sy);
415 }
416
417 WL_EXPORT void
418 weston_pointer_send_motion(struct weston_pointer *pointer,
419                            const struct timespec *time,
420                            struct weston_pointer_motion_event *event)
421 {
422         wl_fixed_t x, y;
423         wl_fixed_t old_sx = pointer->sx;
424         wl_fixed_t old_sy = pointer->sy;
425
426         if (pointer->focus) {
427                 weston_pointer_motion_to_abs(pointer, event, &x, &y);
428                 weston_view_from_global_fixed(pointer->focus, x, y,
429                                               &pointer->sx, &pointer->sy);
430         }
431
432         weston_pointer_move(pointer, event);
433
434         if (old_sx != pointer->sx || old_sy != pointer->sy) {
435                 pointer_send_motion(pointer, time,
436                                     pointer->sx, pointer->sy);
437         }
438
439         pointer_send_relative_motion(pointer, time, event);
440 }
441
442 static void
443 default_grab_pointer_motion(struct weston_pointer_grab *grab,
444                             const struct timespec *time,
445                             struct weston_pointer_motion_event *event)
446 {
447         weston_pointer_send_motion(grab->pointer, time, event);
448 }
449
450 /** Check if the pointer has focused resources.
451  *
452  * \param pointer The pointer to check for focused resources.
453  * \return Whether or not this pointer has focused resources
454  */
455 WL_EXPORT bool
456 weston_pointer_has_focus_resource(struct weston_pointer *pointer)
457 {
458         if (!pointer->focus_client)
459                 return false;
460
461         if (wl_list_empty(&pointer->focus_client->pointer_resources))
462                 return false;
463
464         return true;
465 }
466
467 /** Send wl_pointer.button events to focused resources.
468  *
469  * \param pointer The pointer where the button events originates from.
470  * \param time The timestamp of the event
471  * \param button The button value of the event
472  * \param value The state enum value of the event
473  *
474  * For every resource that is currently in focus, send a wl_pointer.button event
475  * with the passed parameters. The focused resources are the wl_pointer
476  * resources of the client which currently has the surface with pointer focus.
477  */
478 WL_EXPORT void
479 weston_pointer_send_button(struct weston_pointer *pointer,
480                            const struct timespec *time, uint32_t button,
481                            enum wl_pointer_button_state state)
482 {
483         struct wl_display *display = pointer->seat->compositor->wl_display;
484         struct wl_list *resource_list;
485         struct wl_resource *resource;
486         uint32_t serial;
487         uint32_t msecs;
488
489         if (!weston_pointer_has_focus_resource(pointer))
490                 return;
491
492         resource_list = &pointer->focus_client->pointer_resources;
493         serial = wl_display_next_serial(display);
494         msecs = timespec_to_msec(time);
495         wl_resource_for_each(resource, resource_list)
496                 wl_pointer_send_button(resource, serial, msecs, button, state);
497 }
498
499 static void
500 default_grab_pointer_button(struct weston_pointer_grab *grab,
501                             const struct timespec *time, uint32_t button,
502                             enum wl_pointer_button_state state)
503 {
504         struct weston_pointer *pointer = grab->pointer;
505         struct weston_compositor *compositor = pointer->seat->compositor;
506         struct weston_view *view;
507         wl_fixed_t sx, sy;
508
509         weston_pointer_send_button(pointer, time, button, state);
510
511         if (pointer->button_count == 0 &&
512             state == WL_POINTER_BUTTON_STATE_RELEASED) {
513                 view = weston_compositor_pick_view(compositor,
514                                                    pointer->x, pointer->y,
515                                                    &sx, &sy);
516
517                 weston_pointer_set_focus(pointer, view, sx, sy);
518         }
519 }
520
521 /** Send wl_pointer.axis events to focused resources.
522  *
523  * \param pointer The pointer where the axis events originates from.
524  * \param time The timestamp of the event
525  * \param axis The axis enum value of the event
526  * \param value The axis value of the event
527  *
528  * For every resource that is currently in focus, send a wl_pointer.axis event
529  * with the passed parameters. The focused resources are the wl_pointer
530  * resources of the client which currently has the surface with pointer focus.
531  */
532 WL_EXPORT void
533 weston_pointer_send_axis(struct weston_pointer *pointer,
534                          const struct timespec *time,
535                          struct weston_pointer_axis_event *event)
536 {
537         struct wl_resource *resource;
538         struct wl_list *resource_list;
539         uint32_t msecs;
540
541         if (!weston_pointer_has_focus_resource(pointer))
542                 return;
543
544         resource_list = &pointer->focus_client->pointer_resources;
545         msecs = timespec_to_msec(time);
546         wl_resource_for_each(resource, resource_list) {
547                 if (event->has_discrete &&
548                     wl_resource_get_version(resource) >=
549                     WL_POINTER_AXIS_DISCRETE_SINCE_VERSION)
550                         wl_pointer_send_axis_discrete(resource, event->axis,
551                                                       event->discrete);
552
553                 if (event->value)
554                         wl_pointer_send_axis(resource, msecs,
555                                              event->axis,
556                                              wl_fixed_from_double(event->value));
557                 else if (wl_resource_get_version(resource) >=
558                          WL_POINTER_AXIS_STOP_SINCE_VERSION)
559                         wl_pointer_send_axis_stop(resource, msecs,
560                                                   event->axis);
561         }
562 }
563
564 /** Send wl_pointer.axis_source events to focused resources.
565  *
566  * \param pointer The pointer where the axis_source events originates from.
567  * \param source The axis_source enum value of the event
568  *
569  * For every resource that is currently in focus, send a wl_pointer.axis_source
570  * event with the passed parameter. The focused resources are the wl_pointer
571  * resources of the client which currently has the surface with pointer focus.
572  */
573 WL_EXPORT void
574 weston_pointer_send_axis_source(struct weston_pointer *pointer,
575                                 enum wl_pointer_axis_source source)
576 {
577         struct wl_resource *resource;
578         struct wl_list *resource_list;
579
580         if (!weston_pointer_has_focus_resource(pointer))
581                 return;
582
583         resource_list = &pointer->focus_client->pointer_resources;
584         wl_resource_for_each(resource, resource_list) {
585                 if (wl_resource_get_version(resource) >=
586                     WL_POINTER_AXIS_SOURCE_SINCE_VERSION) {
587                         wl_pointer_send_axis_source(resource, source);
588                 }
589         }
590 }
591
592 static void
593 pointer_send_frame(struct wl_resource *resource)
594 {
595         if (wl_resource_get_version(resource) >=
596             WL_POINTER_FRAME_SINCE_VERSION) {
597                 wl_pointer_send_frame(resource);
598         }
599 }
600
601 /** Send wl_pointer.frame events to focused resources.
602  *
603  * \param pointer The pointer where the frame events originates from.
604  *
605  * For every resource that is currently in focus, send a wl_pointer.frame event.
606  * The focused resources are the wl_pointer resources of the client which
607  * currently has the surface with pointer focus.
608  */
609 WL_EXPORT void
610 weston_pointer_send_frame(struct weston_pointer *pointer)
611 {
612         struct wl_resource *resource;
613         struct wl_list *resource_list;
614
615         if (!weston_pointer_has_focus_resource(pointer))
616                 return;
617
618         resource_list = &pointer->focus_client->pointer_resources;
619         wl_resource_for_each(resource, resource_list)
620                 pointer_send_frame(resource);
621 }
622
623 static void
624 default_grab_pointer_axis(struct weston_pointer_grab *grab,
625                           const struct timespec *time,
626                           struct weston_pointer_axis_event *event)
627 {
628         weston_pointer_send_axis(grab->pointer, time, event);
629 }
630
631 static void
632 default_grab_pointer_axis_source(struct weston_pointer_grab *grab,
633                                  enum wl_pointer_axis_source source)
634 {
635         weston_pointer_send_axis_source(grab->pointer, source);
636 }
637
638 static void
639 default_grab_pointer_frame(struct weston_pointer_grab *grab)
640 {
641         weston_pointer_send_frame(grab->pointer);
642 }
643
644 static void
645 default_grab_pointer_cancel(struct weston_pointer_grab *grab)
646 {
647 }
648
649 static const struct weston_pointer_grab_interface
650                                 default_pointer_grab_interface = {
651         default_grab_pointer_focus,
652         default_grab_pointer_motion,
653         default_grab_pointer_button,
654         default_grab_pointer_axis,
655         default_grab_pointer_axis_source,
656         default_grab_pointer_frame,
657         default_grab_pointer_cancel,
658 };
659
660 /** Check if the touch has focused resources.
661  *
662  * \param touch The touch to check for focused resources.
663  * \return Whether or not this touch has focused resources
664  */
665 WL_EXPORT bool
666 weston_touch_has_focus_resource(struct weston_touch *touch)
667 {
668         if (!touch->focus)
669                 return false;
670
671         if (wl_list_empty(&touch->focus_resource_list))
672                 return false;
673
674         return true;
675 }
676
677 /** Send wl_touch.down events to focused resources.
678  *
679  * \param touch The touch where the down events originates from.
680  * \param time The timestamp of the event
681  * \param touch_id The touch_id value of the event
682  * \param x The x value of the event
683  * \param y The y value of the event
684  *
685  * For every resource that is currently in focus, send a wl_touch.down event
686  * with the passed parameters. The focused resources are the wl_touch
687  * resources of the client which currently has the surface with touch focus.
688  */
689 WL_EXPORT void
690 weston_touch_send_down(struct weston_touch *touch, const struct timespec *time,
691                        int touch_id, wl_fixed_t x, wl_fixed_t y)
692 {
693         struct wl_display *display = touch->seat->compositor->wl_display;
694         uint32_t serial;
695         struct wl_resource *resource;
696         struct wl_list *resource_list;
697         wl_fixed_t sx, sy;
698         uint32_t msecs;
699
700         if (!weston_touch_has_focus_resource(touch))
701                 return;
702
703         weston_view_from_global_fixed(touch->focus, x, y, &sx, &sy);
704
705         resource_list = &touch->focus_resource_list;
706         serial = wl_display_next_serial(display);
707         msecs = timespec_to_msec(time);
708         wl_resource_for_each(resource, resource_list)
709                         wl_touch_send_down(resource, serial, msecs,
710                                            touch->focus->surface->resource,
711                                            touch_id, sx, sy);
712 }
713
714 static void
715 default_grab_touch_down(struct weston_touch_grab *grab,
716                         const struct timespec *time, int touch_id,
717                         wl_fixed_t x, wl_fixed_t y)
718 {
719         weston_touch_send_down(grab->touch, time, touch_id, x, y);
720 }
721
722 /** Send wl_touch.up events to focused resources.
723  *
724  * \param touch The touch where the up events originates from.
725  * \param time The timestamp of the event
726  * \param touch_id The touch_id value of the event
727  *
728  * For every resource that is currently in focus, send a wl_touch.up event
729  * with the passed parameters. The focused resources are the wl_touch
730  * resources of the client which currently has the surface with touch focus.
731  */
732 WL_EXPORT void
733 weston_touch_send_up(struct weston_touch *touch, const struct timespec *time,
734                      int touch_id)
735 {
736         struct wl_display *display = touch->seat->compositor->wl_display;
737         uint32_t serial;
738         struct wl_resource *resource;
739         struct wl_list *resource_list;
740         uint32_t msecs;
741
742         if (!weston_touch_has_focus_resource(touch))
743                 return;
744
745         resource_list = &touch->focus_resource_list;
746         serial = wl_display_next_serial(display);
747         msecs = timespec_to_msec(time);
748         wl_resource_for_each(resource, resource_list)
749                 wl_touch_send_up(resource, serial, msecs, touch_id);
750 }
751
752 static void
753 default_grab_touch_up(struct weston_touch_grab *grab,
754                       const struct timespec *time, int touch_id)
755 {
756         weston_touch_send_up(grab->touch, time, touch_id);
757 }
758
759 /** Send wl_touch.motion events to focused resources.
760  *
761  * \param touch The touch where the motion events originates from.
762  * \param time The timestamp of the event
763  * \param touch_id The touch_id value of the event
764  * \param x The x value of the event
765  * \param y The y value of the event
766  *
767  * For every resource that is currently in focus, send a wl_touch.motion event
768  * with the passed parameters. The focused resources are the wl_touch
769  * resources of the client which currently has the surface with touch focus.
770  */
771 WL_EXPORT void
772 weston_touch_send_motion(struct weston_touch *touch,
773                          const struct timespec *time, int touch_id,
774                          wl_fixed_t x, wl_fixed_t y)
775 {
776         struct wl_resource *resource;
777         struct wl_list *resource_list;
778         wl_fixed_t sx, sy;
779         uint32_t msecs;
780
781         if (!weston_touch_has_focus_resource(touch))
782                 return;
783
784         weston_view_from_global_fixed(touch->focus, x, y, &sx, &sy);
785
786         resource_list = &touch->focus_resource_list;
787         msecs = timespec_to_msec(time);
788         wl_resource_for_each(resource, resource_list) {
789                 wl_touch_send_motion(resource, msecs,
790                                      touch_id, sx, sy);
791         }
792 }
793
794 static void
795 default_grab_touch_motion(struct weston_touch_grab *grab,
796                           const struct timespec *time, int touch_id,
797                           wl_fixed_t x, wl_fixed_t y)
798 {
799         weston_touch_send_motion(grab->touch, time, touch_id, x, y);
800 }
801
802
803 /** Send wl_touch.frame events to focused resources.
804  *
805  * \param touch The touch where the frame events originates from.
806  *
807  * For every resource that is currently in focus, send a wl_touch.frame event.
808  * The focused resources are the wl_touch resources of the client which
809  * currently has the surface with touch focus.
810  */
811 WL_EXPORT void
812 weston_touch_send_frame(struct weston_touch *touch)
813 {
814         struct wl_resource *resource;
815
816         if (!weston_touch_has_focus_resource(touch))
817                 return;
818
819         wl_resource_for_each(resource, &touch->focus_resource_list)
820                 wl_touch_send_frame(resource);
821 }
822
823 static void
824 default_grab_touch_frame(struct weston_touch_grab *grab)
825 {
826         weston_touch_send_frame(grab->touch);
827 }
828
829 static void
830 default_grab_touch_cancel(struct weston_touch_grab *grab)
831 {
832 }
833
834 static const struct weston_touch_grab_interface default_touch_grab_interface = {
835         default_grab_touch_down,
836         default_grab_touch_up,
837         default_grab_touch_motion,
838         default_grab_touch_frame,
839         default_grab_touch_cancel,
840 };
841
842 /** Check if the keyboard has focused resources.
843  *
844  * \param keyboard The keyboard to check for focused resources.
845  * \return Whether or not this keyboard has focused resources
846  */
847 WL_EXPORT bool
848 weston_keyboard_has_focus_resource(struct weston_keyboard *keyboard)
849 {
850         if (!keyboard->focus)
851                 return false;
852
853         if (wl_list_empty(&keyboard->focus_resource_list))
854                 return false;
855
856         return true;
857 }
858
859 /** Send wl_keyboard.key events to focused resources.
860  *
861  * \param keyboard The keyboard where the key events originates from.
862  * \param time The timestamp of the event
863  * \param key The key value of the event
864  * \param state The state enum value of the event
865  *
866  * For every resource that is currently in focus, send a wl_keyboard.key event
867  * with the passed parameters. The focused resources are the wl_keyboard
868  * resources of the client which currently has the surface with keyboard focus.
869  */
870 WL_EXPORT void
871 weston_keyboard_send_key(struct weston_keyboard *keyboard,
872                          const struct timespec *time, uint32_t key,
873                          enum wl_keyboard_key_state state)
874 {
875         struct wl_resource *resource;
876         struct wl_display *display = keyboard->seat->compositor->wl_display;
877         uint32_t serial;
878         struct wl_list *resource_list;
879         uint32_t msecs;
880
881         if (!weston_keyboard_has_focus_resource(keyboard))
882                 return;
883
884         resource_list = &keyboard->focus_resource_list;
885         serial = wl_display_next_serial(display);
886         msecs = timespec_to_msec(time);
887         wl_resource_for_each(resource, resource_list)
888                 wl_keyboard_send_key(resource, serial, msecs, key, state);
889 };
890
891 static void
892 default_grab_keyboard_key(struct weston_keyboard_grab *grab,
893                           const struct timespec *time, uint32_t key,
894                           uint32_t state)
895 {
896         weston_keyboard_send_key(grab->keyboard, time, key, state);
897 }
898
899 static void
900 send_modifiers_to_resource(struct weston_keyboard *keyboard,
901                            struct wl_resource *resource,
902                            uint32_t serial)
903 {
904         wl_keyboard_send_modifiers(resource,
905                                    serial,
906                                    keyboard->modifiers.mods_depressed,
907                                    keyboard->modifiers.mods_latched,
908                                    keyboard->modifiers.mods_locked,
909                                    keyboard->modifiers.group);
910 }
911
912 static void
913 send_modifiers_to_client_in_list(struct wl_client *client,
914                                  struct wl_list *list,
915                                  uint32_t serial,
916                                  struct weston_keyboard *keyboard)
917 {
918         struct wl_resource *resource;
919
920         wl_resource_for_each(resource, list) {
921                 if (wl_resource_get_client(resource) == client)
922                         send_modifiers_to_resource(keyboard,
923                                                    resource,
924                                                    serial);
925         }
926 }
927
928 static struct weston_pointer_client *
929 find_pointer_client_for_surface(struct weston_pointer *pointer,
930                                 struct weston_surface *surface)
931 {
932         struct wl_client *client;
933
934         if (!surface)
935                 return NULL;
936
937         if (!surface->resource)
938                 return NULL;
939
940         client = wl_resource_get_client(surface->resource);
941         return weston_pointer_get_pointer_client(pointer, client);
942 }
943
944 static struct weston_pointer_client *
945 find_pointer_client_for_view(struct weston_pointer *pointer, struct weston_view *view)
946 {
947         if (!view)
948                 return NULL;
949
950         return find_pointer_client_for_surface(pointer, view->surface);
951 }
952
953 static struct wl_resource *
954 find_resource_for_surface(struct wl_list *list, struct weston_surface *surface)
955 {
956         if (!surface)
957                 return NULL;
958
959         if (!surface->resource)
960                 return NULL;
961
962         return wl_resource_find_for_client(list, wl_resource_get_client(surface->resource));
963 }
964
965 /** Send wl_keyboard.modifiers events to focused resources and pointer
966  *  focused resources.
967  *
968  * \param keyboard The keyboard where the modifiers events originates from.
969  * \param serial The serial of the event
970  * \param mods_depressed The mods_depressed value of the event
971  * \param mods_latched The mods_latched value of the event
972  * \param mods_locked The mods_locked value of the event
973  * \param group The group value of the event
974  *
975  * For every resource that is currently in focus, send a wl_keyboard.modifiers
976  * event with the passed parameters. The focused resources are the wl_keyboard
977  * resources of the client which currently has the surface with keyboard focus.
978  * This also sends wl_keyboard.modifiers events to the wl_keyboard resources of
979  * the client having pointer focus (if different from the keyboard focus client).
980  */
981 WL_EXPORT void
982 weston_keyboard_send_modifiers(struct weston_keyboard *keyboard,
983                                uint32_t serial, uint32_t mods_depressed,
984                                uint32_t mods_latched,
985                                uint32_t mods_locked, uint32_t group)
986 {
987         struct weston_pointer *pointer =
988                 weston_seat_get_pointer(keyboard->seat);
989
990         if (weston_keyboard_has_focus_resource(keyboard)) {
991                 struct wl_list *resource_list;
992                 struct wl_resource *resource;
993
994                 resource_list = &keyboard->focus_resource_list;
995                 wl_resource_for_each(resource, resource_list) {
996                         wl_keyboard_send_modifiers(resource, serial,
997                                                    mods_depressed, mods_latched,
998                                                    mods_locked, group);
999                 }
1000         }
1001
1002         if (pointer && pointer->focus && pointer->focus->surface->resource &&
1003             pointer->focus->surface != keyboard->focus) {
1004                 struct wl_client *pointer_client =
1005                         wl_resource_get_client(pointer->focus->surface->resource);
1006
1007                 send_modifiers_to_client_in_list(pointer_client,
1008                                                  &keyboard->resource_list,
1009                                                  serial,
1010                                                  keyboard);
1011         }
1012 }
1013
1014 static void
1015 default_grab_keyboard_modifiers(struct weston_keyboard_grab *grab,
1016                                 uint32_t serial, uint32_t mods_depressed,
1017                                 uint32_t mods_latched,
1018                                 uint32_t mods_locked, uint32_t group)
1019 {
1020         weston_keyboard_send_modifiers(grab->keyboard, serial, mods_depressed,
1021                                        mods_latched, mods_locked, group);
1022 }
1023
1024 static void
1025 default_grab_keyboard_cancel(struct weston_keyboard_grab *grab)
1026 {
1027 }
1028
1029 static const struct weston_keyboard_grab_interface
1030                                 default_keyboard_grab_interface = {
1031         default_grab_keyboard_key,
1032         default_grab_keyboard_modifiers,
1033         default_grab_keyboard_cancel,
1034 };
1035
1036 static void
1037 pointer_unmap_sprite(struct weston_pointer *pointer)
1038 {
1039         struct weston_surface *surface = pointer->sprite->surface;
1040
1041         if (weston_surface_is_mapped(surface))
1042                 weston_surface_unmap(surface);
1043
1044         wl_list_remove(&pointer->sprite_destroy_listener.link);
1045         surface->committed = NULL;
1046         surface->committed_private = NULL;
1047         weston_surface_set_label_func(surface, NULL);
1048         weston_view_destroy(pointer->sprite);
1049         pointer->sprite = NULL;
1050 }
1051
1052 static void
1053 pointer_handle_sprite_destroy(struct wl_listener *listener, void *data)
1054 {
1055         struct weston_pointer *pointer =
1056                 container_of(listener, struct weston_pointer,
1057                              sprite_destroy_listener);
1058
1059         pointer->sprite = NULL;
1060 }
1061
1062 static void
1063 weston_pointer_reset_state(struct weston_pointer *pointer)
1064 {
1065         pointer->button_count = 0;
1066 }
1067
1068 static void
1069 weston_pointer_handle_output_destroy(struct wl_listener *listener, void *data);
1070
1071 WL_EXPORT struct weston_pointer *
1072 weston_pointer_create(struct weston_seat *seat)
1073 {
1074         struct weston_pointer *pointer;
1075
1076         pointer = zalloc(sizeof *pointer);
1077         if (pointer == NULL)
1078                 return NULL;
1079
1080         wl_list_init(&pointer->pointer_clients);
1081         weston_pointer_set_default_grab(pointer,
1082                                         seat->compositor->default_pointer_grab);
1083         wl_list_init(&pointer->focus_resource_listener.link);
1084         pointer->focus_resource_listener.notify = pointer_focus_resource_destroyed;
1085         pointer->default_grab.pointer = pointer;
1086         pointer->grab = &pointer->default_grab;
1087         wl_signal_init(&pointer->motion_signal);
1088         wl_signal_init(&pointer->focus_signal);
1089         wl_list_init(&pointer->focus_view_listener.link);
1090         wl_signal_init(&pointer->destroy_signal);
1091
1092         pointer->sprite_destroy_listener.notify = pointer_handle_sprite_destroy;
1093
1094         /* FIXME: Pick better co-ords. */
1095         pointer->x = wl_fixed_from_int(100);
1096         pointer->y = wl_fixed_from_int(100);
1097
1098         pointer->output_destroy_listener.notify =
1099                 weston_pointer_handle_output_destroy;
1100         wl_signal_add(&seat->compositor->output_destroyed_signal,
1101                       &pointer->output_destroy_listener);
1102
1103         pointer->sx = wl_fixed_from_int(-1000000);
1104         pointer->sy = wl_fixed_from_int(-1000000);
1105
1106         return pointer;
1107 }
1108
1109 WL_EXPORT void
1110 weston_pointer_destroy(struct weston_pointer *pointer)
1111 {
1112         struct weston_pointer_client *pointer_client, *tmp;
1113
1114         wl_signal_emit(&pointer->destroy_signal, pointer);
1115
1116         if (pointer->sprite)
1117                 pointer_unmap_sprite(pointer);
1118
1119         wl_list_for_each_safe(pointer_client, tmp, &pointer->pointer_clients,
1120                               link) {
1121                 wl_list_remove(&pointer_client->link);
1122                 weston_pointer_client_destroy(pointer_client);
1123         }
1124
1125         wl_list_remove(&pointer->focus_resource_listener.link);
1126         wl_list_remove(&pointer->focus_view_listener.link);
1127         wl_list_remove(&pointer->output_destroy_listener.link);
1128         free(pointer);
1129 }
1130
1131 void
1132 weston_pointer_set_default_grab(struct weston_pointer *pointer,
1133                 const struct weston_pointer_grab_interface *interface)
1134 {
1135         if (interface)
1136                 pointer->default_grab.interface = interface;
1137         else
1138                 pointer->default_grab.interface =
1139                         &default_pointer_grab_interface;
1140 }
1141
1142 WL_EXPORT struct weston_keyboard *
1143 weston_keyboard_create(void)
1144 {
1145         struct weston_keyboard *keyboard;
1146
1147         keyboard = zalloc(sizeof *keyboard);
1148         if (keyboard == NULL)
1149             return NULL;
1150
1151         wl_list_init(&keyboard->resource_list);
1152         wl_list_init(&keyboard->focus_resource_list);
1153         wl_list_init(&keyboard->focus_resource_listener.link);
1154         keyboard->focus_resource_listener.notify = keyboard_focus_resource_destroyed;
1155         wl_array_init(&keyboard->keys);
1156         keyboard->default_grab.interface = &default_keyboard_grab_interface;
1157         keyboard->default_grab.keyboard = keyboard;
1158         keyboard->grab = &keyboard->default_grab;
1159         wl_signal_init(&keyboard->focus_signal);
1160
1161         return keyboard;
1162 }
1163
1164 static void
1165 weston_xkb_info_destroy(struct weston_xkb_info *xkb_info);
1166
1167 WL_EXPORT void
1168 weston_keyboard_destroy(struct weston_keyboard *keyboard)
1169 {
1170         struct wl_resource *resource;
1171
1172         wl_resource_for_each(resource, &keyboard->resource_list) {
1173                 wl_resource_set_user_data(resource, NULL);
1174         }
1175
1176         wl_resource_for_each(resource, &keyboard->focus_resource_list) {
1177                 wl_resource_set_user_data(resource, NULL);
1178         }
1179
1180         wl_list_remove(&keyboard->resource_list);
1181         wl_list_remove(&keyboard->focus_resource_list);
1182
1183         xkb_state_unref(keyboard->xkb_state.state);
1184         if (keyboard->xkb_info)
1185                 weston_xkb_info_destroy(keyboard->xkb_info);
1186         xkb_keymap_unref(keyboard->pending_keymap);
1187
1188         wl_array_release(&keyboard->keys);
1189         wl_list_remove(&keyboard->focus_resource_listener.link);
1190         free(keyboard);
1191 }
1192
1193 static void
1194 weston_touch_reset_state(struct weston_touch *touch)
1195 {
1196         touch->num_tp = 0;
1197 }
1198
1199 WL_EXPORT struct weston_touch *
1200 weston_touch_create(void)
1201 {
1202         struct weston_touch *touch;
1203
1204         touch = zalloc(sizeof *touch);
1205         if (touch == NULL)
1206                 return NULL;
1207
1208         wl_list_init(&touch->resource_list);
1209         wl_list_init(&touch->focus_resource_list);
1210         wl_list_init(&touch->focus_view_listener.link);
1211         touch->focus_view_listener.notify = touch_focus_view_destroyed;
1212         wl_list_init(&touch->focus_resource_listener.link);
1213         touch->focus_resource_listener.notify = touch_focus_resource_destroyed;
1214         touch->default_grab.interface = &default_touch_grab_interface;
1215         touch->default_grab.touch = touch;
1216         touch->grab = &touch->default_grab;
1217         wl_signal_init(&touch->focus_signal);
1218
1219         return touch;
1220 }
1221
1222 WL_EXPORT void
1223 weston_touch_destroy(struct weston_touch *touch)
1224 {
1225         struct wl_resource *resource;
1226
1227         wl_resource_for_each(resource, &touch->resource_list) {
1228                 wl_resource_set_user_data(resource, NULL);
1229         }
1230
1231         wl_resource_for_each(resource, &touch->focus_resource_list) {
1232                 wl_resource_set_user_data(resource, NULL);
1233         }
1234
1235         wl_list_remove(&touch->resource_list);
1236         wl_list_remove(&touch->focus_resource_list);
1237         wl_list_remove(&touch->focus_view_listener.link);
1238         wl_list_remove(&touch->focus_resource_listener.link);
1239         free(touch);
1240 }
1241
1242 static void
1243 seat_send_updated_caps(struct weston_seat *seat)
1244 {
1245         enum wl_seat_capability caps = 0;
1246         struct wl_resource *resource;
1247
1248         if (seat->pointer_device_count > 0)
1249                 caps |= WL_SEAT_CAPABILITY_POINTER;
1250         if (seat->keyboard_device_count > 0)
1251                 caps |= WL_SEAT_CAPABILITY_KEYBOARD;
1252         if (seat->touch_device_count > 0)
1253                 caps |= WL_SEAT_CAPABILITY_TOUCH;
1254
1255         wl_resource_for_each(resource, &seat->base_resource_list) {
1256                 wl_seat_send_capabilities(resource, caps);
1257         }
1258         wl_signal_emit(&seat->updated_caps_signal, seat);
1259 }
1260
1261
1262 /** Clear the pointer focus
1263  *
1264  * \param pointer the pointer to clear focus for.
1265  *
1266  * This can be used to unset pointer focus and set the co-ordinates to the
1267  * arbitrary values we use for the no focus case.
1268  *
1269  * There's no requirement to use this function.  For example, passing the
1270  * results of a weston_compositor_pick_view() directly to
1271  * weston_pointer_set_focus() will do the right thing when no view is found.
1272  */
1273 WL_EXPORT void
1274 weston_pointer_clear_focus(struct weston_pointer *pointer)
1275 {
1276         weston_pointer_set_focus(pointer, NULL,
1277                                  wl_fixed_from_int(-1000000),
1278                                  wl_fixed_from_int(-1000000));
1279 }
1280
1281 WL_EXPORT void
1282 weston_pointer_set_focus(struct weston_pointer *pointer,
1283                          struct weston_view *view,
1284                          wl_fixed_t sx, wl_fixed_t sy)
1285 {
1286         struct weston_pointer_client *pointer_client;
1287         struct weston_keyboard *kbd = weston_seat_get_keyboard(pointer->seat);
1288         struct wl_resource *resource;
1289         struct wl_resource *surface_resource;
1290         struct wl_display *display = pointer->seat->compositor->wl_display;
1291         uint32_t serial;
1292         struct wl_list *focus_resource_list;
1293         int refocus = 0;
1294
1295         if ((!pointer->focus && view) ||
1296             (pointer->focus && !view) ||
1297             (pointer->focus && pointer->focus->surface != view->surface) ||
1298             pointer->sx != sx || pointer->sy != sy)
1299                 refocus = 1;
1300
1301         if (pointer->focus_client && refocus) {
1302                 focus_resource_list = &pointer->focus_client->pointer_resources;
1303                 if (!wl_list_empty(focus_resource_list)) {
1304                         serial = wl_display_next_serial(display);
1305                         surface_resource = pointer->focus->surface->resource;
1306                         wl_resource_for_each(resource, focus_resource_list) {
1307                                 wl_pointer_send_leave(resource, serial,
1308                                                       surface_resource);
1309                                 pointer_send_frame(resource);
1310                         }
1311                 }
1312
1313                 pointer->focus_client = NULL;
1314         }
1315
1316         pointer_client = find_pointer_client_for_view(pointer, view);
1317         if (pointer_client && refocus) {
1318                 struct wl_client *surface_client = pointer_client->client;
1319
1320                 serial = wl_display_next_serial(display);
1321
1322                 if (kbd && kbd->focus != view->surface)
1323                         send_modifiers_to_client_in_list(surface_client,
1324                                                          &kbd->resource_list,
1325                                                          serial,
1326                                                          kbd);
1327
1328                 pointer->focus_client = pointer_client;
1329
1330                 focus_resource_list = &pointer->focus_client->pointer_resources;
1331                 wl_resource_for_each(resource, focus_resource_list) {
1332                         wl_pointer_send_enter(resource,
1333                                               serial,
1334                                               view->surface->resource,
1335                                               sx, sy);
1336                         pointer_send_frame(resource);
1337                 }
1338
1339                 pointer->focus_serial = serial;
1340         }
1341
1342         wl_list_remove(&pointer->focus_view_listener.link);
1343         wl_list_init(&pointer->focus_view_listener.link);
1344         wl_list_remove(&pointer->focus_resource_listener.link);
1345         wl_list_init(&pointer->focus_resource_listener.link);
1346         if (view)
1347                 wl_signal_add(&view->destroy_signal, &pointer->focus_view_listener);
1348         if (view && view->surface->resource)
1349                 wl_resource_add_destroy_listener(view->surface->resource,
1350                                                  &pointer->focus_resource_listener);
1351
1352         pointer->focus = view;
1353         pointer->focus_view_listener.notify = pointer_focus_view_destroyed;
1354         pointer->sx = sx;
1355         pointer->sy = sy;
1356
1357         assert(view || sx == wl_fixed_from_int(-1000000));
1358         assert(view || sy == wl_fixed_from_int(-1000000));
1359
1360         wl_signal_emit(&pointer->focus_signal, pointer);
1361 }
1362
1363 static void
1364 send_enter_to_resource_list(struct wl_list *list,
1365                             struct weston_keyboard *keyboard,
1366                             struct weston_surface *surface,
1367                             uint32_t serial)
1368 {
1369         struct wl_resource *resource;
1370
1371         wl_resource_for_each(resource, list) {
1372                 send_modifiers_to_resource(keyboard, resource, serial);
1373                 wl_keyboard_send_enter(resource, serial,
1374                                        surface->resource,
1375                                        &keyboard->keys);
1376         }
1377 }
1378
1379 WL_EXPORT void
1380 weston_keyboard_set_focus(struct weston_keyboard *keyboard,
1381                           struct weston_surface *surface)
1382 {
1383         struct weston_seat *seat = keyboard->seat;
1384         struct wl_resource *resource;
1385         struct wl_display *display = keyboard->seat->compositor->wl_display;
1386         uint32_t serial;
1387         struct wl_list *focus_resource_list;
1388
1389         focus_resource_list = &keyboard->focus_resource_list;
1390
1391         if (!wl_list_empty(focus_resource_list) && keyboard->focus != surface) {
1392                 serial = wl_display_next_serial(display);
1393                 wl_resource_for_each(resource, focus_resource_list) {
1394                         wl_keyboard_send_leave(resource, serial,
1395                                         keyboard->focus->resource);
1396                 }
1397                 move_resources(&keyboard->resource_list, focus_resource_list);
1398         }
1399
1400         if (find_resource_for_surface(&keyboard->resource_list, surface) &&
1401             keyboard->focus != surface) {
1402                 struct wl_client *surface_client =
1403                         wl_resource_get_client(surface->resource);
1404
1405                 serial = wl_display_next_serial(display);
1406
1407                 move_resources_for_client(focus_resource_list,
1408                                           &keyboard->resource_list,
1409                                           surface_client);
1410                 send_enter_to_resource_list(focus_resource_list,
1411                                             keyboard,
1412                                             surface,
1413                                             serial);
1414                 keyboard->focus_serial = serial;
1415         }
1416
1417         if (seat->saved_kbd_focus) {
1418                 wl_list_remove(&seat->saved_kbd_focus_listener.link);
1419                 seat->saved_kbd_focus = NULL;
1420         }
1421
1422         wl_list_remove(&keyboard->focus_resource_listener.link);
1423         wl_list_init(&keyboard->focus_resource_listener.link);
1424         if (surface && surface->resource)
1425                 wl_resource_add_destroy_listener(surface->resource,
1426                                                  &keyboard->focus_resource_listener);
1427
1428         keyboard->focus = surface;
1429         wl_signal_emit(&keyboard->focus_signal, keyboard);
1430 }
1431
1432 /* Users of this function must manually manage the keyboard focus */
1433 WL_EXPORT void
1434 weston_keyboard_start_grab(struct weston_keyboard *keyboard,
1435                            struct weston_keyboard_grab *grab)
1436 {
1437         keyboard->grab = grab;
1438         grab->keyboard = keyboard;
1439 }
1440
1441 WL_EXPORT void
1442 weston_keyboard_end_grab(struct weston_keyboard *keyboard)
1443 {
1444         keyboard->grab = &keyboard->default_grab;
1445 }
1446
1447 static void
1448 weston_keyboard_cancel_grab(struct weston_keyboard *keyboard)
1449 {
1450         keyboard->grab->interface->cancel(keyboard->grab);
1451 }
1452
1453 WL_EXPORT void
1454 weston_pointer_start_grab(struct weston_pointer *pointer,
1455                           struct weston_pointer_grab *grab)
1456 {
1457         pointer->grab = grab;
1458         grab->pointer = pointer;
1459         pointer->grab->interface->focus(pointer->grab);
1460 }
1461
1462 WL_EXPORT void
1463 weston_pointer_end_grab(struct weston_pointer *pointer)
1464 {
1465         pointer->grab = &pointer->default_grab;
1466         pointer->grab->interface->focus(pointer->grab);
1467 }
1468
1469 static void
1470 weston_pointer_cancel_grab(struct weston_pointer *pointer)
1471 {
1472         pointer->grab->interface->cancel(pointer->grab);
1473 }
1474
1475 WL_EXPORT void
1476 weston_touch_start_grab(struct weston_touch *touch, struct weston_touch_grab *grab)
1477 {
1478         touch->grab = grab;
1479         grab->touch = touch;
1480 }
1481
1482 WL_EXPORT void
1483 weston_touch_end_grab(struct weston_touch *touch)
1484 {
1485         touch->grab = &touch->default_grab;
1486 }
1487
1488 static void
1489 weston_touch_cancel_grab(struct weston_touch *touch)
1490 {
1491         touch->grab->interface->cancel(touch->grab);
1492 }
1493
1494 static void
1495 weston_pointer_clamp_for_output(struct weston_pointer *pointer,
1496                                 struct weston_output *output,
1497                                 wl_fixed_t *fx, wl_fixed_t *fy)
1498 {
1499         int x, y;
1500
1501         x = wl_fixed_to_int(*fx);
1502         y = wl_fixed_to_int(*fy);
1503
1504         if (x < output->x)
1505                 *fx = wl_fixed_from_int(output->x);
1506         else if (x >= output->x + output->width)
1507                 *fx = wl_fixed_from_int(output->x +
1508                                         output->width - 1);
1509         if (y < output->y)
1510                 *fy = wl_fixed_from_int(output->y);
1511         else if (y >= output->y + output->height)
1512                 *fy = wl_fixed_from_int(output->y +
1513                                         output->height - 1);
1514 }
1515
1516 WL_EXPORT void
1517 weston_pointer_clamp(struct weston_pointer *pointer, wl_fixed_t *fx, wl_fixed_t *fy)
1518 {
1519         struct weston_compositor *ec = pointer->seat->compositor;
1520         struct weston_output *output, *prev = NULL;
1521         int x, y, old_x, old_y, valid = 0;
1522
1523         x = wl_fixed_to_int(*fx);
1524         y = wl_fixed_to_int(*fy);
1525         old_x = wl_fixed_to_int(pointer->x);
1526         old_y = wl_fixed_to_int(pointer->y);
1527
1528         wl_list_for_each(output, &ec->output_list, link) {
1529                 if (pointer->seat->output && pointer->seat->output != output)
1530                         continue;
1531                 if (pixman_region32_contains_point(&output->region,
1532                                                    x, y, NULL))
1533                         valid = 1;
1534                 if (pixman_region32_contains_point(&output->region,
1535                                                    old_x, old_y, NULL))
1536                         prev = output;
1537         }
1538
1539         if (!prev)
1540                 prev = pointer->seat->output;
1541
1542         if (prev && !valid)
1543                 weston_pointer_clamp_for_output(pointer, prev, fx, fy);
1544 }
1545
1546 static void
1547 weston_pointer_move_to(struct weston_pointer *pointer,
1548                        wl_fixed_t x, wl_fixed_t y)
1549 {
1550         int32_t ix, iy;
1551
1552         weston_pointer_clamp (pointer, &x, &y);
1553
1554         pointer->x = x;
1555         pointer->y = y;
1556
1557         ix = wl_fixed_to_int(x);
1558         iy = wl_fixed_to_int(y);
1559
1560         if (pointer->sprite) {
1561                 weston_view_set_position(pointer->sprite,
1562                                          ix - pointer->hotspot_x,
1563                                          iy - pointer->hotspot_y);
1564                 weston_view_schedule_repaint(pointer->sprite);
1565         }
1566
1567         pointer->grab->interface->focus(pointer->grab);
1568         wl_signal_emit(&pointer->motion_signal, pointer);
1569 }
1570
1571 WL_EXPORT void
1572 weston_pointer_move(struct weston_pointer *pointer,
1573                     struct weston_pointer_motion_event *event)
1574 {
1575         wl_fixed_t x, y;
1576
1577         weston_pointer_motion_to_abs(pointer, event, &x, &y);
1578         weston_pointer_move_to(pointer, x, y);
1579 }
1580
1581 /** Verify if the pointer is in a valid position and move it if it isn't.
1582  */
1583 static void
1584 weston_pointer_handle_output_destroy(struct wl_listener *listener, void *data)
1585 {
1586         struct weston_pointer *pointer;
1587         struct weston_compositor *ec;
1588         struct weston_output *output, *closest = NULL;
1589         int x, y, distance, min = INT_MAX;
1590         wl_fixed_t fx, fy;
1591
1592         pointer = container_of(listener, struct weston_pointer,
1593                                output_destroy_listener);
1594         ec = pointer->seat->compositor;
1595
1596         x = wl_fixed_to_int(pointer->x);
1597         y = wl_fixed_to_int(pointer->y);
1598
1599         wl_list_for_each(output, &ec->output_list, link) {
1600                 if (pixman_region32_contains_point(&output->region,
1601                                                    x, y, NULL))
1602                         return;
1603
1604                 /* Aproximante the distance from the pointer to the center of
1605                  * the output. */
1606                 distance = abs(output->x + output->width / 2 - x) +
1607                            abs(output->y + output->height / 2 - y);
1608                 if (distance < min) {
1609                         min = distance;
1610                         closest = output;
1611                 }
1612         }
1613
1614         /* Nothing to do if there's no output left. */
1615         if (!closest)
1616                 return;
1617
1618         fx = pointer->x;
1619         fy = pointer->y;
1620
1621         weston_pointer_clamp_for_output(pointer, closest, &fx, &fy);
1622         weston_pointer_move_to(pointer, fx, fy);
1623 }
1624
1625 WL_EXPORT void
1626 notify_motion(struct weston_seat *seat,
1627               const struct timespec *time,
1628               struct weston_pointer_motion_event *event)
1629 {
1630         struct weston_compositor *ec = seat->compositor;
1631         struct weston_pointer *pointer = weston_seat_get_pointer(seat);
1632
1633         weston_compositor_wake(ec);
1634         pointer->grab->interface->motion(pointer->grab, time, event);
1635 }
1636
1637 static void
1638 run_modifier_bindings(struct weston_seat *seat, uint32_t old, uint32_t new)
1639 {
1640         struct weston_compositor *compositor = seat->compositor;
1641         struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
1642         uint32_t diff;
1643         unsigned int i;
1644         struct {
1645                 uint32_t xkb;
1646                 enum weston_keyboard_modifier weston;
1647         } mods[] = {
1648                 { keyboard->xkb_info->ctrl_mod, MODIFIER_CTRL },
1649                 { keyboard->xkb_info->alt_mod, MODIFIER_ALT },
1650                 { keyboard->xkb_info->super_mod, MODIFIER_SUPER },
1651                 { keyboard->xkb_info->shift_mod, MODIFIER_SHIFT },
1652         };
1653
1654         diff = new & ~old;
1655         for (i = 0; i < ARRAY_LENGTH(mods); i++) {
1656                 if (diff & (1 << mods[i].xkb))
1657                         weston_compositor_run_modifier_binding(compositor,
1658                                                                keyboard,
1659                                                                mods[i].weston,
1660                                                                WL_KEYBOARD_KEY_STATE_PRESSED);
1661         }
1662
1663         diff = old & ~new;
1664         for (i = 0; i < ARRAY_LENGTH(mods); i++) {
1665                 if (diff & (1 << mods[i].xkb))
1666                         weston_compositor_run_modifier_binding(compositor,
1667                                                                keyboard,
1668                                                                mods[i].weston,
1669                                                                WL_KEYBOARD_KEY_STATE_RELEASED);
1670         }
1671 }
1672
1673 WL_EXPORT void
1674 notify_motion_absolute(struct weston_seat *seat, const struct timespec *time,
1675                        double x, double y)
1676 {
1677         struct weston_compositor *ec = seat->compositor;
1678         struct weston_pointer *pointer = weston_seat_get_pointer(seat);
1679         struct weston_pointer_motion_event event = { 0 };
1680
1681         weston_compositor_wake(ec);
1682
1683         event = (struct weston_pointer_motion_event) {
1684                 .mask = WESTON_POINTER_MOTION_ABS,
1685                 .x = x,
1686                 .y = y,
1687         };
1688
1689         pointer->grab->interface->motion(pointer->grab, time, &event);
1690 }
1691
1692 static unsigned int
1693 peek_next_activate_serial(struct weston_compositor *c)
1694 {
1695         unsigned serial = c->activate_serial + 1;
1696
1697         return serial == 0 ? 1 : serial;
1698 }
1699
1700 static void
1701 inc_activate_serial(struct weston_compositor *c)
1702 {
1703         c->activate_serial = peek_next_activate_serial (c);
1704 }
1705
1706 WL_EXPORT void
1707 weston_view_activate(struct weston_view *view,
1708                      struct weston_seat *seat,
1709                      uint32_t flags)
1710 {
1711         struct weston_compositor *compositor = seat->compositor;
1712
1713         if (flags & WESTON_ACTIVATE_FLAG_CLICKED) {
1714                 view->click_to_activate_serial =
1715                         peek_next_activate_serial(compositor);
1716         }
1717
1718         weston_seat_set_keyboard_focus(seat, view->surface);
1719 }
1720
1721 WL_EXPORT void
1722 notify_button(struct weston_seat *seat, const struct timespec *time,
1723               int32_t button, enum wl_pointer_button_state state)
1724 {
1725         struct weston_compositor *compositor = seat->compositor;
1726         struct weston_pointer *pointer = weston_seat_get_pointer(seat);
1727
1728         if (state == WL_POINTER_BUTTON_STATE_PRESSED) {
1729                 weston_compositor_idle_inhibit(compositor);
1730                 if (pointer->button_count == 0) {
1731                         pointer->grab_button = button;
1732                         pointer->grab_time = *time;
1733                         pointer->grab_x = pointer->x;
1734                         pointer->grab_y = pointer->y;
1735                 }
1736                 pointer->button_count++;
1737         } else {
1738                 weston_compositor_idle_release(compositor);
1739                 pointer->button_count--;
1740         }
1741
1742         weston_compositor_run_button_binding(compositor, pointer, time, button,
1743                                              state);
1744
1745         pointer->grab->interface->button(pointer->grab, time, button, state);
1746
1747         if (pointer->button_count == 1)
1748                 pointer->grab_serial =
1749                         wl_display_get_serial(compositor->wl_display);
1750 }
1751
1752 WL_EXPORT void
1753 notify_axis(struct weston_seat *seat, const struct timespec *time,
1754             struct weston_pointer_axis_event *event)
1755 {
1756         struct weston_compositor *compositor = seat->compositor;
1757         struct weston_pointer *pointer = weston_seat_get_pointer(seat);
1758
1759         weston_compositor_wake(compositor);
1760
1761         if (weston_compositor_run_axis_binding(compositor, pointer,
1762                                                time, event))
1763                 return;
1764
1765         pointer->grab->interface->axis(pointer->grab, time, event);
1766 }
1767
1768 WL_EXPORT void
1769 notify_axis_source(struct weston_seat *seat, uint32_t source)
1770 {
1771         struct weston_compositor *compositor = seat->compositor;
1772         struct weston_pointer *pointer = weston_seat_get_pointer(seat);
1773
1774         weston_compositor_wake(compositor);
1775
1776         pointer->grab->interface->axis_source(pointer->grab, source);
1777 }
1778
1779 WL_EXPORT void
1780 notify_pointer_frame(struct weston_seat *seat)
1781 {
1782         struct weston_compositor *compositor = seat->compositor;
1783         struct weston_pointer *pointer = weston_seat_get_pointer(seat);
1784
1785         weston_compositor_wake(compositor);
1786
1787         pointer->grab->interface->frame(pointer->grab);
1788 }
1789
1790 WL_EXPORT int
1791 weston_keyboard_set_locks(struct weston_keyboard *keyboard,
1792                           uint32_t mask, uint32_t value)
1793 {
1794         uint32_t serial;
1795         xkb_mod_mask_t mods_depressed, mods_latched, mods_locked, group;
1796         xkb_mod_mask_t num, caps;
1797
1798         /* We don't want the leds to go out of sync with the actual state
1799          * so if the backend has no way to change the leds don't try to
1800          * change the state */
1801         if (!keyboard->seat->led_update)
1802                 return -1;
1803
1804         mods_depressed = xkb_state_serialize_mods(keyboard->xkb_state.state,
1805                                                 XKB_STATE_DEPRESSED);
1806         mods_latched = xkb_state_serialize_mods(keyboard->xkb_state.state,
1807                                                 XKB_STATE_LATCHED);
1808         mods_locked = xkb_state_serialize_mods(keyboard->xkb_state.state,
1809                                                 XKB_STATE_LOCKED);
1810         group = xkb_state_serialize_group(keyboard->xkb_state.state,
1811                                       XKB_STATE_EFFECTIVE);
1812
1813         num = (1 << keyboard->xkb_info->mod2_mod);
1814         caps = (1 << keyboard->xkb_info->caps_mod);
1815         if (mask & WESTON_NUM_LOCK) {
1816                 if (value & WESTON_NUM_LOCK)
1817                         mods_locked |= num;
1818                 else
1819                         mods_locked &= ~num;
1820         }
1821         if (mask & WESTON_CAPS_LOCK) {
1822                 if (value & WESTON_CAPS_LOCK)
1823                         mods_locked |= caps;
1824                 else
1825                         mods_locked &= ~caps;
1826         }
1827
1828         xkb_state_update_mask(keyboard->xkb_state.state, mods_depressed,
1829                               mods_latched, mods_locked, 0, 0, group);
1830
1831         serial = wl_display_next_serial(
1832                                 keyboard->seat->compositor->wl_display);
1833         notify_modifiers(keyboard->seat, serial);
1834
1835         return 0;
1836 }
1837
1838 WL_EXPORT void
1839 notify_modifiers(struct weston_seat *seat, uint32_t serial)
1840 {
1841         struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
1842         struct weston_keyboard_grab *grab = keyboard->grab;
1843         uint32_t mods_depressed, mods_latched, mods_locked, group;
1844         uint32_t mods_lookup;
1845         enum weston_led leds = 0;
1846         int changed = 0;
1847
1848         /* Serialize and update our internal state, checking to see if it's
1849          * different to the previous state. */
1850         mods_depressed = xkb_state_serialize_mods(keyboard->xkb_state.state,
1851                                                   XKB_STATE_MODS_DEPRESSED);
1852         mods_latched = xkb_state_serialize_mods(keyboard->xkb_state.state,
1853                                                 XKB_STATE_MODS_LATCHED);
1854         mods_locked = xkb_state_serialize_mods(keyboard->xkb_state.state,
1855                                                XKB_STATE_MODS_LOCKED);
1856         group = xkb_state_serialize_layout(keyboard->xkb_state.state,
1857                                            XKB_STATE_LAYOUT_EFFECTIVE);
1858
1859         if (mods_depressed != keyboard->modifiers.mods_depressed ||
1860             mods_latched != keyboard->modifiers.mods_latched ||
1861             mods_locked != keyboard->modifiers.mods_locked ||
1862             group != keyboard->modifiers.group)
1863                 changed = 1;
1864
1865         run_modifier_bindings(seat, keyboard->modifiers.mods_depressed,
1866                               mods_depressed);
1867
1868         keyboard->modifiers.mods_depressed = mods_depressed;
1869         keyboard->modifiers.mods_latched = mods_latched;
1870         keyboard->modifiers.mods_locked = mods_locked;
1871         keyboard->modifiers.group = group;
1872
1873         /* And update the modifier_state for bindings. */
1874         mods_lookup = mods_depressed | mods_latched;
1875         seat->modifier_state = 0;
1876         if (mods_lookup & (1 << keyboard->xkb_info->ctrl_mod))
1877                 seat->modifier_state |= MODIFIER_CTRL;
1878         if (mods_lookup & (1 << keyboard->xkb_info->alt_mod))
1879                 seat->modifier_state |= MODIFIER_ALT;
1880         if (mods_lookup & (1 << keyboard->xkb_info->super_mod))
1881                 seat->modifier_state |= MODIFIER_SUPER;
1882         if (mods_lookup & (1 << keyboard->xkb_info->shift_mod))
1883                 seat->modifier_state |= MODIFIER_SHIFT;
1884
1885         /* Finally, notify the compositor that LEDs have changed. */
1886         if (xkb_state_led_index_is_active(keyboard->xkb_state.state,
1887                                           keyboard->xkb_info->num_led))
1888                 leds |= LED_NUM_LOCK;
1889         if (xkb_state_led_index_is_active(keyboard->xkb_state.state,
1890                                           keyboard->xkb_info->caps_led))
1891                 leds |= LED_CAPS_LOCK;
1892         if (xkb_state_led_index_is_active(keyboard->xkb_state.state,
1893                                           keyboard->xkb_info->scroll_led))
1894                 leds |= LED_SCROLL_LOCK;
1895         if (leds != keyboard->xkb_state.leds && seat->led_update)
1896                 seat->led_update(seat, leds);
1897         keyboard->xkb_state.leds = leds;
1898
1899         if (changed) {
1900                 grab->interface->modifiers(grab,
1901                                            serial,
1902                                            keyboard->modifiers.mods_depressed,
1903                                            keyboard->modifiers.mods_latched,
1904                                            keyboard->modifiers.mods_locked,
1905                                            keyboard->modifiers.group);
1906         }
1907 }
1908
1909 static void
1910 update_modifier_state(struct weston_seat *seat, uint32_t serial, uint32_t key,
1911                       enum wl_keyboard_key_state state)
1912 {
1913         struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
1914         enum xkb_key_direction direction;
1915
1916         if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
1917                 direction = XKB_KEY_DOWN;
1918         else
1919                 direction = XKB_KEY_UP;
1920
1921         /* Offset the keycode by 8, as the evdev XKB rules reflect X's
1922          * broken keycode system, which starts at 8. */
1923         xkb_state_update_key(keyboard->xkb_state.state, key + 8, direction);
1924
1925         notify_modifiers(seat, serial);
1926 }
1927
1928 static void
1929 send_keymap(struct wl_resource *resource, struct weston_xkb_info *xkb_info)
1930 {
1931         wl_keyboard_send_keymap(resource,
1932                                 WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1,
1933                                 xkb_info->keymap_fd,
1934                                 xkb_info->keymap_size);
1935 }
1936
1937 static void
1938 send_modifiers(struct wl_resource *resource, uint32_t serial, struct weston_keyboard *keyboard)
1939 {
1940         wl_keyboard_send_modifiers(resource, serial,
1941                                    keyboard->modifiers.mods_depressed,
1942                                    keyboard->modifiers.mods_latched,
1943                                    keyboard->modifiers.mods_locked,
1944                                    keyboard->modifiers.group);
1945 }
1946
1947 static struct weston_xkb_info *
1948 weston_xkb_info_create(struct xkb_keymap *keymap);
1949
1950 static void
1951 update_keymap(struct weston_seat *seat)
1952 {
1953         struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
1954         struct wl_resource *resource;
1955         struct weston_xkb_info *xkb_info;
1956         struct xkb_state *state;
1957         xkb_mod_mask_t latched_mods;
1958         xkb_mod_mask_t locked_mods;
1959
1960         xkb_info = weston_xkb_info_create(keyboard->pending_keymap);
1961
1962         xkb_keymap_unref(keyboard->pending_keymap);
1963         keyboard->pending_keymap = NULL;
1964
1965         if (!xkb_info) {
1966                 weston_log("failed to create XKB info\n");
1967                 return;
1968         }
1969
1970         state = xkb_state_new(xkb_info->keymap);
1971         if (!state) {
1972                 weston_log("failed to initialise XKB state\n");
1973                 weston_xkb_info_destroy(xkb_info);
1974                 return;
1975         }
1976
1977         latched_mods = xkb_state_serialize_mods(keyboard->xkb_state.state,
1978                                                 XKB_STATE_MODS_LATCHED);
1979         locked_mods = xkb_state_serialize_mods(keyboard->xkb_state.state,
1980                                                XKB_STATE_MODS_LOCKED);
1981         xkb_state_update_mask(state,
1982                               0, /* depressed */
1983                               latched_mods,
1984                               locked_mods,
1985                               0, 0, 0);
1986
1987         weston_xkb_info_destroy(keyboard->xkb_info);
1988         keyboard->xkb_info = xkb_info;
1989
1990         xkb_state_unref(keyboard->xkb_state.state);
1991         keyboard->xkb_state.state = state;
1992
1993         wl_resource_for_each(resource, &keyboard->resource_list)
1994                 send_keymap(resource, xkb_info);
1995         wl_resource_for_each(resource, &keyboard->focus_resource_list)
1996                 send_keymap(resource, xkb_info);
1997
1998         notify_modifiers(seat, wl_display_next_serial(seat->compositor->wl_display));
1999
2000         if (!latched_mods && !locked_mods)
2001                 return;
2002
2003         wl_resource_for_each(resource, &keyboard->resource_list)
2004                 send_modifiers(resource, wl_display_get_serial(seat->compositor->wl_display), keyboard);
2005         wl_resource_for_each(resource, &keyboard->focus_resource_list)
2006                 send_modifiers(resource, wl_display_get_serial(seat->compositor->wl_display), keyboard);
2007 }
2008
2009 WL_EXPORT void
2010 notify_key(struct weston_seat *seat, const struct timespec *time, uint32_t key,
2011            enum wl_keyboard_key_state state,
2012            enum weston_key_state_update update_state)
2013 {
2014         struct weston_compositor *compositor = seat->compositor;
2015         struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
2016         struct weston_keyboard_grab *grab = keyboard->grab;
2017         uint32_t *k, *end;
2018
2019         if (state == WL_KEYBOARD_KEY_STATE_PRESSED) {
2020                 weston_compositor_idle_inhibit(compositor);
2021         } else {
2022                 weston_compositor_idle_release(compositor);
2023         }
2024
2025         end = keyboard->keys.data + keyboard->keys.size;
2026         for (k = keyboard->keys.data; k < end; k++) {
2027                 if (*k == key) {
2028                         /* Ignore server-generated repeats. */
2029                         if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
2030                                 return;
2031                         *k = *--end;
2032                 }
2033         }
2034         keyboard->keys.size = (void *) end - keyboard->keys.data;
2035         if (state == WL_KEYBOARD_KEY_STATE_PRESSED) {
2036                 k = wl_array_add(&keyboard->keys, sizeof *k);
2037                 *k = key;
2038         }
2039
2040         if (grab == &keyboard->default_grab ||
2041             grab == &keyboard->input_method_grab) {
2042                 weston_compositor_run_key_binding(compositor, keyboard, time,
2043                                                   key, state);
2044                 grab = keyboard->grab;
2045         }
2046
2047         grab->interface->key(grab, time, key, state);
2048
2049         if (keyboard->pending_keymap &&
2050             keyboard->keys.size == 0)
2051                 update_keymap(seat);
2052
2053         if (update_state == STATE_UPDATE_AUTOMATIC) {
2054                 update_modifier_state(seat,
2055                                       wl_display_get_serial(compositor->wl_display),
2056                                       key,
2057                                       state);
2058         }
2059
2060         keyboard->grab_serial = wl_display_get_serial(compositor->wl_display);
2061         if (state == WL_KEYBOARD_KEY_STATE_PRESSED) {
2062                 keyboard->grab_time = *time;
2063                 keyboard->grab_key = key;
2064         }
2065 }
2066
2067 WL_EXPORT void
2068 notify_pointer_focus(struct weston_seat *seat, struct weston_output *output,
2069                      double x, double y)
2070 {
2071         struct weston_pointer *pointer = weston_seat_get_pointer(seat);
2072
2073         if (output) {
2074                 weston_pointer_move_to(pointer,
2075                                        wl_fixed_from_double(x),
2076                                        wl_fixed_from_double(y));
2077         } else {
2078                 /* FIXME: We should call weston_pointer_set_focus(seat,
2079                  * NULL) here, but somehow that breaks re-entry... */
2080         }
2081 }
2082
2083 static void
2084 destroy_device_saved_kbd_focus(struct wl_listener *listener, void *data)
2085 {
2086         struct weston_seat *ws;
2087
2088         ws = container_of(listener, struct weston_seat,
2089                           saved_kbd_focus_listener);
2090
2091         ws->saved_kbd_focus = NULL;
2092 }
2093
2094 WL_EXPORT void
2095 notify_keyboard_focus_in(struct weston_seat *seat, struct wl_array *keys,
2096                          enum weston_key_state_update update_state)
2097 {
2098         struct weston_compositor *compositor = seat->compositor;
2099         struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
2100         struct weston_surface *surface;
2101         uint32_t *k, serial;
2102
2103         serial = wl_display_next_serial(compositor->wl_display);
2104         wl_array_copy(&keyboard->keys, keys);
2105         wl_array_for_each(k, &keyboard->keys) {
2106                 weston_compositor_idle_inhibit(compositor);
2107                 if (update_state == STATE_UPDATE_AUTOMATIC)
2108                         update_modifier_state(seat, serial, *k,
2109                                               WL_KEYBOARD_KEY_STATE_PRESSED);
2110         }
2111
2112         surface = seat->saved_kbd_focus;
2113         if (surface) {
2114                 weston_keyboard_set_focus(keyboard, surface);
2115         }
2116 }
2117
2118 WL_EXPORT void
2119 notify_keyboard_focus_out(struct weston_seat *seat)
2120 {
2121         struct weston_compositor *compositor = seat->compositor;
2122         struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
2123         struct weston_pointer *pointer = weston_seat_get_pointer(seat);
2124         struct weston_surface *focus = keyboard->focus;
2125         uint32_t *k, serial;
2126
2127         serial = wl_display_next_serial(compositor->wl_display);
2128         wl_array_for_each(k, &keyboard->keys) {
2129                 weston_compositor_idle_release(compositor);
2130                 update_modifier_state(seat, serial, *k,
2131                                       WL_KEYBOARD_KEY_STATE_RELEASED);
2132         }
2133
2134         seat->modifier_state = 0;
2135
2136         weston_keyboard_set_focus(keyboard, NULL);
2137         weston_keyboard_cancel_grab(keyboard);
2138         if (pointer)
2139                 weston_pointer_cancel_grab(pointer);
2140
2141         if (focus) {
2142                 seat->saved_kbd_focus = focus;
2143                 seat->saved_kbd_focus_listener.notify =
2144                         destroy_device_saved_kbd_focus;
2145                 wl_signal_add(&focus->destroy_signal,
2146                               &seat->saved_kbd_focus_listener);
2147         }
2148 }
2149
2150 WL_EXPORT void
2151 weston_touch_set_focus(struct weston_touch *touch, struct weston_view *view)
2152 {
2153         struct wl_list *focus_resource_list;
2154
2155         focus_resource_list = &touch->focus_resource_list;
2156
2157         if (view && touch->focus &&
2158             touch->focus->surface == view->surface) {
2159                 touch->focus = view;
2160                 return;
2161         }
2162
2163         wl_list_remove(&touch->focus_resource_listener.link);
2164         wl_list_init(&touch->focus_resource_listener.link);
2165         wl_list_remove(&touch->focus_view_listener.link);
2166         wl_list_init(&touch->focus_view_listener.link);
2167
2168         if (!wl_list_empty(focus_resource_list)) {
2169                 move_resources(&touch->resource_list,
2170                                focus_resource_list);
2171         }
2172
2173         if (view) {
2174                 struct wl_client *surface_client;
2175
2176                 if (!view->surface->resource) {
2177                         touch->focus = NULL;
2178                         return;
2179                 }
2180
2181                 surface_client = wl_resource_get_client(view->surface->resource);
2182                 move_resources_for_client(focus_resource_list,
2183                                           &touch->resource_list,
2184                                           surface_client);
2185                 wl_resource_add_destroy_listener(view->surface->resource,
2186                                                  &touch->focus_resource_listener);
2187                 wl_signal_add(&view->destroy_signal, &touch->focus_view_listener);
2188         }
2189         touch->focus = view;
2190 }
2191
2192 /**
2193  * notify_touch - emulates button touches and notifies surfaces accordingly.
2194  *
2195  * It assumes always the correct cycle sequence until it gets here: touch_down
2196  * → touch_update → ... → touch_update → touch_end. The driver is responsible
2197  * for sending along such order.
2198  *
2199  */
2200 WL_EXPORT void
2201 notify_touch(struct weston_seat *seat, const struct timespec *time,
2202              int touch_id, double double_x, double double_y, int touch_type)
2203 {
2204         struct weston_compositor *ec = seat->compositor;
2205         struct weston_touch *touch = weston_seat_get_touch(seat);
2206         struct weston_touch_grab *grab = touch->grab;
2207         struct weston_view *ev;
2208         wl_fixed_t sx, sy;
2209         wl_fixed_t x = wl_fixed_from_double(double_x);
2210         wl_fixed_t y = wl_fixed_from_double(double_y);
2211
2212         /* Update grab's global coordinates. */
2213         if (touch_id == touch->grab_touch_id && touch_type != WL_TOUCH_UP) {
2214                 touch->grab_x = x;
2215                 touch->grab_y = y;
2216         }
2217
2218         switch (touch_type) {
2219         case WL_TOUCH_DOWN:
2220                 weston_compositor_idle_inhibit(ec);
2221
2222                 touch->num_tp++;
2223
2224                 /* the first finger down picks the view, and all further go
2225                  * to that view for the remainder of the touch session i.e.
2226                  * until all touch points are up again. */
2227                 if (touch->num_tp == 1) {
2228                         ev = weston_compositor_pick_view(ec, x, y, &sx, &sy);
2229                         weston_touch_set_focus(touch, ev);
2230                 } else if (!touch->focus) {
2231                         /* Unexpected condition: We have non-initial touch but
2232                          * there is no focused surface.
2233                          */
2234                         weston_log("touch event received with %d points down "
2235                                    "but no surface focused\n", touch->num_tp);
2236                         return;
2237                 }
2238
2239                 weston_compositor_run_touch_binding(ec, touch,
2240                                                     time, touch_type);
2241
2242                 grab->interface->down(grab, time, touch_id, x, y);
2243                 if (touch->num_tp == 1) {
2244                         touch->grab_serial =
2245                                 wl_display_get_serial(ec->wl_display);
2246                         touch->grab_touch_id = touch_id;
2247                         touch->grab_time = *time;
2248                         touch->grab_x = x;
2249                         touch->grab_y = y;
2250                 }
2251
2252                 break;
2253         case WL_TOUCH_MOTION:
2254                 ev = touch->focus;
2255                 if (!ev)
2256                         break;
2257
2258                 grab->interface->motion(grab, time, touch_id, x, y);
2259                 break;
2260         case WL_TOUCH_UP:
2261                 if (touch->num_tp == 0) {
2262                         /* This can happen if we start out with one or
2263                          * more fingers on the touch screen, in which
2264                          * case we didn't get the corresponding down
2265                          * event. */
2266                         weston_log("unmatched touch up event\n");
2267                         break;
2268                 }
2269                 weston_compositor_idle_release(ec);
2270                 touch->num_tp--;
2271
2272                 grab->interface->up(grab, time, touch_id);
2273                 if (touch->num_tp == 0)
2274                         weston_touch_set_focus(touch, NULL);
2275                 break;
2276         }
2277 }
2278
2279 WL_EXPORT void
2280 notify_touch_frame(struct weston_seat *seat)
2281 {
2282         struct weston_touch *touch = weston_seat_get_touch(seat);
2283         struct weston_touch_grab *grab = touch->grab;
2284
2285         grab->interface->frame(grab);
2286 }
2287
2288 WL_EXPORT void
2289 notify_touch_cancel(struct weston_seat *seat)
2290 {
2291         struct weston_touch *touch = weston_seat_get_touch(seat);
2292         struct weston_touch_grab *grab = touch->grab;
2293
2294         grab->interface->cancel(grab);
2295 }
2296
2297 static int
2298 pointer_cursor_surface_get_label(struct weston_surface *surface,
2299                                  char *buf, size_t len)
2300 {
2301         return snprintf(buf, len, "cursor");
2302 }
2303
2304 static void
2305 pointer_cursor_surface_committed(struct weston_surface *es,
2306                                  int32_t dx, int32_t dy)
2307 {
2308         struct weston_pointer *pointer = es->committed_private;
2309         int x, y;
2310
2311         if (es->width == 0)
2312                 return;
2313
2314         assert(es == pointer->sprite->surface);
2315
2316         pointer->hotspot_x -= dx;
2317         pointer->hotspot_y -= dy;
2318
2319         x = wl_fixed_to_int(pointer->x) - pointer->hotspot_x;
2320         y = wl_fixed_to_int(pointer->y) - pointer->hotspot_y;
2321
2322         weston_view_set_position(pointer->sprite, x, y);
2323
2324         empty_region(&es->pending.input);
2325         empty_region(&es->input);
2326
2327         if (!weston_surface_is_mapped(es)) {
2328                 weston_layer_entry_insert(&es->compositor->cursor_layer.view_list,
2329                                           &pointer->sprite->layer_link);
2330                 weston_view_update_transform(pointer->sprite);
2331                 es->is_mapped = true;
2332                 pointer->sprite->is_mapped = true;
2333         }
2334 }
2335
2336 static void
2337 pointer_set_cursor(struct wl_client *client, struct wl_resource *resource,
2338                    uint32_t serial, struct wl_resource *surface_resource,
2339                    int32_t x, int32_t y)
2340 {
2341         struct weston_pointer *pointer = wl_resource_get_user_data(resource);
2342         struct weston_surface *surface = NULL;
2343
2344         if (!pointer)
2345                 return;
2346
2347         if (surface_resource)
2348                 surface = wl_resource_get_user_data(surface_resource);
2349
2350         if (pointer->focus == NULL)
2351                 return;
2352         /* pointer->focus->surface->resource can be NULL. Surfaces like the
2353         black_surface used in shell.c for fullscreen don't have
2354         a resource, but can still have focus */
2355         if (pointer->focus->surface->resource == NULL)
2356                 return;
2357         if (wl_resource_get_client(pointer->focus->surface->resource) != client)
2358                 return;
2359         if (pointer->focus_serial - serial > UINT32_MAX / 2)
2360                 return;
2361
2362         if (!surface) {
2363                 if (pointer->sprite)
2364                         pointer_unmap_sprite(pointer);
2365                 return;
2366         }
2367
2368         if (pointer->sprite && pointer->sprite->surface == surface &&
2369             pointer->hotspot_x == x && pointer->hotspot_y == y)
2370                 return;
2371
2372         if (!pointer->sprite || pointer->sprite->surface != surface) {
2373                 if (weston_surface_set_role(surface, "wl_pointer-cursor",
2374                                             resource,
2375                                             WL_POINTER_ERROR_ROLE) < 0)
2376                         return;
2377
2378                 if (pointer->sprite)
2379                         pointer_unmap_sprite(pointer);
2380
2381                 wl_signal_add(&surface->destroy_signal,
2382                               &pointer->sprite_destroy_listener);
2383
2384                 surface->committed = pointer_cursor_surface_committed;
2385                 surface->committed_private = pointer;
2386                 weston_surface_set_label_func(surface,
2387                                             pointer_cursor_surface_get_label);
2388                 pointer->sprite = weston_view_create(surface);
2389         }
2390
2391         pointer->hotspot_x = x;
2392         pointer->hotspot_y = y;
2393
2394         if (surface->buffer_ref.buffer) {
2395                 pointer_cursor_surface_committed(surface, 0, 0);
2396                 weston_view_schedule_repaint(pointer->sprite);
2397         }
2398 }
2399
2400 static void
2401 pointer_release(struct wl_client *client, struct wl_resource *resource)
2402 {
2403         wl_resource_destroy(resource);
2404 }
2405
2406 static const struct wl_pointer_interface pointer_interface = {
2407         pointer_set_cursor,
2408         pointer_release
2409 };
2410
2411 static void
2412 seat_get_pointer(struct wl_client *client, struct wl_resource *resource,
2413                  uint32_t id)
2414 {
2415         struct weston_seat *seat = wl_resource_get_user_data(resource);
2416         /* We use the pointer_state directly, which means we'll
2417          * give a wl_pointer if the seat has ever had one - even though
2418          * the spec explicitly states that this request only takes effect
2419          * if the seat has the pointer capability.
2420          *
2421          * This prevents a race between the compositor sending new
2422          * capabilities and the client trying to use the old ones.
2423          */
2424         struct weston_pointer *pointer = seat ? seat->pointer_state : NULL;
2425         struct wl_resource *cr;
2426         struct weston_pointer_client *pointer_client;
2427
2428         cr = wl_resource_create(client, &wl_pointer_interface,
2429                                 wl_resource_get_version(resource), id);
2430         if (cr == NULL) {
2431                 wl_client_post_no_memory(client);
2432                 return;
2433         }
2434
2435         wl_list_init(wl_resource_get_link(cr));
2436         wl_resource_set_implementation(cr, &pointer_interface, pointer,
2437                                        unbind_pointer_client_resource);
2438
2439         /* If we don't have a pointer_state, the resource is inert, so there
2440          * is nothing more to set up */
2441         if (!pointer)
2442                 return;
2443
2444         pointer_client = weston_pointer_ensure_pointer_client(pointer, client);
2445         if (!pointer_client) {
2446                 wl_client_post_no_memory(client);
2447                 return;
2448         }
2449
2450         wl_list_insert(&pointer_client->pointer_resources,
2451                        wl_resource_get_link(cr));
2452
2453         if (pointer->focus && pointer->focus->surface->resource &&
2454             wl_resource_get_client(pointer->focus->surface->resource) == client) {
2455                 wl_fixed_t sx, sy;
2456
2457                 weston_view_from_global_fixed(pointer->focus,
2458                                               pointer->x,
2459                                               pointer->y,
2460                                               &sx, &sy);
2461
2462                 wl_pointer_send_enter(cr,
2463                                       pointer->focus_serial,
2464                                       pointer->focus->surface->resource,
2465                                       sx, sy);
2466                 pointer_send_frame(cr);
2467         }
2468 }
2469
2470 static void
2471 keyboard_release(struct wl_client *client, struct wl_resource *resource)
2472 {
2473         wl_resource_destroy(resource);
2474 }
2475
2476 static const struct wl_keyboard_interface keyboard_interface = {
2477         keyboard_release
2478 };
2479
2480 static bool
2481 should_send_modifiers_to_client(struct weston_seat *seat,
2482                                 struct wl_client *client)
2483 {
2484         struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
2485         struct weston_pointer *pointer = weston_seat_get_pointer(seat);
2486
2487         if (keyboard &&
2488             keyboard->focus &&
2489             keyboard->focus->resource &&
2490             wl_resource_get_client(keyboard->focus->resource) == client)
2491                 return true;
2492
2493         if (pointer &&
2494             pointer->focus &&
2495             pointer->focus->surface->resource &&
2496             wl_resource_get_client(pointer->focus->surface->resource) == client)
2497                 return true;
2498
2499         return false;
2500 }
2501
2502 static void
2503 seat_get_keyboard(struct wl_client *client, struct wl_resource *resource,
2504                   uint32_t id)
2505 {
2506         struct weston_seat *seat = wl_resource_get_user_data(resource);
2507         /* We use the keyboard_state directly, which means we'll
2508          * give a wl_keyboard if the seat has ever had one - even though
2509          * the spec explicitly states that this request only takes effect
2510          * if the seat has the keyboard capability.
2511          *
2512          * This prevents a race between the compositor sending new
2513          * capabilities and the client trying to use the old ones.
2514          */
2515         struct weston_keyboard *keyboard = seat ? seat->keyboard_state : NULL;
2516         struct wl_resource *cr;
2517
2518         cr = wl_resource_create(client, &wl_keyboard_interface,
2519                                 wl_resource_get_version(resource), id);
2520         if (cr == NULL) {
2521                 wl_client_post_no_memory(client);
2522                 return;
2523         }
2524
2525         wl_list_init(wl_resource_get_link(cr));
2526         wl_resource_set_implementation(cr, &keyboard_interface,
2527                                        keyboard, unbind_resource);
2528
2529         /* If we don't have a keyboard_state, the resource is inert, so there
2530          * is nothing more to set up */
2531         if (!keyboard)
2532                 return;
2533
2534         /* May be moved to focused list later by either
2535          * weston_keyboard_set_focus or directly if this client is already
2536          * focused */
2537         wl_list_insert(&keyboard->resource_list, wl_resource_get_link(cr));
2538
2539         if (wl_resource_get_version(cr) >= WL_KEYBOARD_REPEAT_INFO_SINCE_VERSION) {
2540                 wl_keyboard_send_repeat_info(cr,
2541                                              seat->compositor->kb_repeat_rate,
2542                                              seat->compositor->kb_repeat_delay);
2543         }
2544
2545         wl_keyboard_send_keymap(cr, WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1,
2546                                 keyboard->xkb_info->keymap_fd,
2547                                 keyboard->xkb_info->keymap_size);
2548
2549         if (should_send_modifiers_to_client(seat, client)) {
2550                 send_modifiers_to_resource(keyboard,
2551                                            cr,
2552                                            keyboard->focus_serial);
2553         }
2554
2555         if (keyboard->focus && keyboard->focus->resource &&
2556             wl_resource_get_client(keyboard->focus->resource) == client) {
2557                 struct weston_surface *surface =
2558                         (struct weston_surface *)keyboard->focus;
2559
2560                 wl_list_remove(wl_resource_get_link(cr));
2561                 wl_list_insert(&keyboard->focus_resource_list,
2562                                wl_resource_get_link(cr));
2563                 wl_keyboard_send_enter(cr,
2564                                        keyboard->focus_serial,
2565                                        surface->resource,
2566                                        &keyboard->keys);
2567
2568                 /* If this is the first keyboard resource for this
2569                  * client... */
2570                 if (keyboard->focus_resource_list.prev ==
2571                     wl_resource_get_link(cr))
2572                         wl_data_device_set_keyboard_focus(seat);
2573         }
2574 }
2575
2576 static void
2577 touch_release(struct wl_client *client, struct wl_resource *resource)
2578 {
2579         wl_resource_destroy(resource);
2580 }
2581
2582 static const struct wl_touch_interface touch_interface = {
2583         touch_release
2584 };
2585
2586 static void
2587 seat_get_touch(struct wl_client *client, struct wl_resource *resource,
2588                uint32_t id)
2589 {
2590         struct weston_seat *seat = wl_resource_get_user_data(resource);
2591         /* We use the touch_state directly, which means we'll
2592          * give a wl_touch if the seat has ever had one - even though
2593          * the spec explicitly states that this request only takes effect
2594          * if the seat has the touch capability.
2595          *
2596          * This prevents a race between the compositor sending new
2597          * capabilities and the client trying to use the old ones.
2598          */
2599         struct weston_touch *touch = seat ? seat->touch_state : NULL;
2600         struct wl_resource *cr;
2601
2602         cr = wl_resource_create(client, &wl_touch_interface,
2603                                 wl_resource_get_version(resource), id);
2604         if (cr == NULL) {
2605                 wl_client_post_no_memory(client);
2606                 return;
2607         }
2608
2609         wl_list_init(wl_resource_get_link(cr));
2610         wl_resource_set_implementation(cr, &touch_interface,
2611                                        touch, unbind_resource);
2612
2613         /* If we don't have a touch_state, the resource is inert, so there
2614          * is nothing more to set up */
2615         if (!touch)
2616                 return;
2617
2618         if (touch->focus &&
2619             wl_resource_get_client(touch->focus->surface->resource) == client) {
2620                 wl_list_insert(&touch->focus_resource_list,
2621                                wl_resource_get_link(cr));
2622         } else {
2623                 wl_list_insert(&touch->resource_list,
2624                                wl_resource_get_link(cr));
2625         }
2626 }
2627
2628 static void
2629 seat_release(struct wl_client *client, struct wl_resource *resource)
2630 {
2631         wl_resource_destroy(resource);
2632 }
2633
2634 static const struct wl_seat_interface seat_interface = {
2635         seat_get_pointer,
2636         seat_get_keyboard,
2637         seat_get_touch,
2638         seat_release,
2639 };
2640
2641 static void
2642 bind_seat(struct wl_client *client, void *data, uint32_t version, uint32_t id)
2643 {
2644         struct weston_seat *seat = data;
2645         struct wl_resource *resource;
2646         enum wl_seat_capability caps = 0;
2647
2648         resource = wl_resource_create(client,
2649                                       &wl_seat_interface, version, id);
2650         wl_list_insert(&seat->base_resource_list, wl_resource_get_link(resource));
2651         wl_resource_set_implementation(resource, &seat_interface, data,
2652                                        unbind_resource);
2653
2654         if (weston_seat_get_pointer(seat))
2655                 caps |= WL_SEAT_CAPABILITY_POINTER;
2656         if (weston_seat_get_keyboard(seat))
2657                 caps |= WL_SEAT_CAPABILITY_KEYBOARD;
2658         if (weston_seat_get_touch(seat))
2659                 caps |= WL_SEAT_CAPABILITY_TOUCH;
2660
2661         wl_seat_send_capabilities(resource, caps);
2662         if (version >= WL_SEAT_NAME_SINCE_VERSION)
2663                 wl_seat_send_name(resource, seat->seat_name);
2664 }
2665
2666 static void
2667 relative_pointer_destroy(struct wl_client *client,
2668                          struct wl_resource *resource)
2669 {
2670         wl_resource_destroy(resource);
2671 }
2672
2673 static const struct zwp_relative_pointer_v1_interface relative_pointer_interface = {
2674         relative_pointer_destroy
2675 };
2676
2677 static void
2678 relative_pointer_manager_destroy(struct wl_client *client,
2679                                  struct wl_resource *resource)
2680 {
2681         wl_resource_destroy(resource);
2682 }
2683
2684 static void
2685 relative_pointer_manager_get_relative_pointer(struct wl_client *client,
2686                                               struct wl_resource *resource,
2687                                               uint32_t id,
2688                                               struct wl_resource *pointer_resource)
2689 {
2690         struct weston_pointer *pointer =
2691                 wl_resource_get_user_data(pointer_resource);
2692         struct weston_pointer_client *pointer_client;
2693         struct wl_resource *cr;
2694
2695         cr = wl_resource_create(client, &zwp_relative_pointer_v1_interface,
2696                                 wl_resource_get_version(resource), id);
2697         if (cr == NULL) {
2698                 wl_client_post_no_memory(client);
2699                 return;
2700         }
2701
2702         pointer_client = weston_pointer_ensure_pointer_client(pointer, client);
2703         if (!pointer_client) {
2704                 wl_client_post_no_memory(client);
2705                 return;
2706         }
2707
2708         wl_list_insert(&pointer_client->relative_pointer_resources,
2709                        wl_resource_get_link(cr));
2710         wl_resource_set_implementation(cr, &relative_pointer_interface,
2711                                        pointer,
2712                                        unbind_pointer_client_resource);
2713 }
2714
2715 static const struct zwp_relative_pointer_manager_v1_interface relative_pointer_manager = {
2716         relative_pointer_manager_destroy,
2717         relative_pointer_manager_get_relative_pointer,
2718 };
2719
2720 static void
2721 bind_relative_pointer_manager(struct wl_client *client, void *data,
2722                               uint32_t version, uint32_t id)
2723 {
2724         struct weston_compositor *compositor = data;
2725         struct wl_resource *resource;
2726
2727         resource = wl_resource_create(client,
2728                                       &zwp_relative_pointer_manager_v1_interface,
2729                                       1, id);
2730
2731         wl_resource_set_implementation(resource, &relative_pointer_manager,
2732                                        compositor,
2733                                        NULL);
2734 }
2735
2736 WL_EXPORT int
2737 weston_compositor_set_xkb_rule_names(struct weston_compositor *ec,
2738                                      struct xkb_rule_names *names)
2739 {
2740         if (ec->xkb_context == NULL) {
2741                 ec->xkb_context = xkb_context_new(0);
2742                 if (ec->xkb_context == NULL) {
2743                         weston_log("failed to create XKB context\n");
2744                         return -1;
2745                 }
2746         }
2747
2748         if (names)
2749                 ec->xkb_names = *names;
2750         if (!ec->xkb_names.rules)
2751                 ec->xkb_names.rules = strdup("evdev");
2752         if (!ec->xkb_names.model)
2753                 ec->xkb_names.model = strdup("pc105");
2754         if (!ec->xkb_names.layout)
2755                 ec->xkb_names.layout = strdup("us");
2756
2757         return 0;
2758 }
2759
2760 static void
2761 weston_xkb_info_destroy(struct weston_xkb_info *xkb_info)
2762 {
2763         if (--xkb_info->ref_count > 0)
2764                 return;
2765
2766         xkb_keymap_unref(xkb_info->keymap);
2767
2768         if (xkb_info->keymap_area)
2769                 munmap(xkb_info->keymap_area, xkb_info->keymap_size);
2770         if (xkb_info->keymap_fd >= 0)
2771                 close(xkb_info->keymap_fd);
2772         free(xkb_info);
2773 }
2774
2775 void
2776 weston_compositor_xkb_destroy(struct weston_compositor *ec)
2777 {
2778         free((char *) ec->xkb_names.rules);
2779         free((char *) ec->xkb_names.model);
2780         free((char *) ec->xkb_names.layout);
2781         free((char *) ec->xkb_names.variant);
2782         free((char *) ec->xkb_names.options);
2783
2784         if (ec->xkb_info)
2785                 weston_xkb_info_destroy(ec->xkb_info);
2786         xkb_context_unref(ec->xkb_context);
2787 }
2788
2789 static struct weston_xkb_info *
2790 weston_xkb_info_create(struct xkb_keymap *keymap)
2791 {
2792         struct weston_xkb_info *xkb_info = zalloc(sizeof *xkb_info);
2793         if (xkb_info == NULL)
2794                 return NULL;
2795
2796         xkb_info->keymap = xkb_keymap_ref(keymap);
2797         xkb_info->ref_count = 1;
2798
2799         char *keymap_str;
2800
2801         xkb_info->shift_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
2802                                                        XKB_MOD_NAME_SHIFT);
2803         xkb_info->caps_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
2804                                                       XKB_MOD_NAME_CAPS);
2805         xkb_info->ctrl_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
2806                                                       XKB_MOD_NAME_CTRL);
2807         xkb_info->alt_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
2808                                                      XKB_MOD_NAME_ALT);
2809         xkb_info->mod2_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
2810                                                       "Mod2");
2811         xkb_info->mod3_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
2812                                                       "Mod3");
2813         xkb_info->super_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
2814                                                        XKB_MOD_NAME_LOGO);
2815         xkb_info->mod5_mod = xkb_keymap_mod_get_index(xkb_info->keymap,
2816                                                       "Mod5");
2817
2818         xkb_info->num_led = xkb_keymap_led_get_index(xkb_info->keymap,
2819                                                      XKB_LED_NAME_NUM);
2820         xkb_info->caps_led = xkb_keymap_led_get_index(xkb_info->keymap,
2821                                                       XKB_LED_NAME_CAPS);
2822         xkb_info->scroll_led = xkb_keymap_led_get_index(xkb_info->keymap,
2823                                                         XKB_LED_NAME_SCROLL);
2824
2825         keymap_str = xkb_keymap_get_as_string(xkb_info->keymap,
2826                                               XKB_KEYMAP_FORMAT_TEXT_V1);
2827         if (keymap_str == NULL) {
2828                 weston_log("failed to get string version of keymap\n");
2829                 goto err_keymap;
2830         }
2831         xkb_info->keymap_size = strlen(keymap_str) + 1;
2832
2833         xkb_info->keymap_fd = os_create_anonymous_file(xkb_info->keymap_size);
2834         if (xkb_info->keymap_fd < 0) {
2835                 weston_log("creating a keymap file for %lu bytes failed: %m\n",
2836                         (unsigned long) xkb_info->keymap_size);
2837                 goto err_keymap_str;
2838         }
2839
2840         xkb_info->keymap_area = mmap(NULL, xkb_info->keymap_size,
2841                                      PROT_READ | PROT_WRITE,
2842                                      MAP_SHARED, xkb_info->keymap_fd, 0);
2843         if (xkb_info->keymap_area == MAP_FAILED) {
2844                 weston_log("failed to mmap() %lu bytes\n",
2845                         (unsigned long) xkb_info->keymap_size);
2846                 goto err_dev_zero;
2847         }
2848         strcpy(xkb_info->keymap_area, keymap_str);
2849         free(keymap_str);
2850
2851         return xkb_info;
2852
2853 err_dev_zero:
2854         close(xkb_info->keymap_fd);
2855 err_keymap_str:
2856         free(keymap_str);
2857 err_keymap:
2858         xkb_keymap_unref(xkb_info->keymap);
2859         free(xkb_info);
2860         return NULL;
2861 }
2862
2863 static int
2864 weston_compositor_build_global_keymap(struct weston_compositor *ec)
2865 {
2866         struct xkb_keymap *keymap;
2867
2868         if (ec->xkb_info != NULL)
2869                 return 0;
2870
2871         keymap = xkb_keymap_new_from_names(ec->xkb_context,
2872                                            &ec->xkb_names,
2873                                            0);
2874         if (keymap == NULL) {
2875                 weston_log("failed to compile global XKB keymap\n");
2876                 weston_log("  tried rules %s, model %s, layout %s, variant %s, "
2877                         "options %s\n",
2878                         ec->xkb_names.rules, ec->xkb_names.model,
2879                         ec->xkb_names.layout, ec->xkb_names.variant,
2880                         ec->xkb_names.options);
2881                 return -1;
2882         }
2883
2884         ec->xkb_info = weston_xkb_info_create(keymap);
2885         xkb_keymap_unref(keymap);
2886         if (ec->xkb_info == NULL)
2887                 return -1;
2888
2889         return 0;
2890 }
2891
2892 WL_EXPORT void
2893 weston_seat_update_keymap(struct weston_seat *seat, struct xkb_keymap *keymap)
2894 {
2895         struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
2896
2897         if (!keyboard || !keymap)
2898                 return;
2899
2900         xkb_keymap_unref(keyboard->pending_keymap);
2901         keyboard->pending_keymap = xkb_keymap_ref(keymap);
2902
2903         if (keyboard->keys.size == 0)
2904                 update_keymap(seat);
2905 }
2906
2907 WL_EXPORT int
2908 weston_seat_init_keyboard(struct weston_seat *seat, struct xkb_keymap *keymap)
2909 {
2910         struct weston_keyboard *keyboard;
2911
2912         if (seat->keyboard_state) {
2913                 seat->keyboard_device_count += 1;
2914                 if (seat->keyboard_device_count == 1)
2915                         seat_send_updated_caps(seat);
2916                 return 0;
2917         }
2918
2919         keyboard = weston_keyboard_create();
2920         if (keyboard == NULL) {
2921                 weston_log("failed to allocate weston keyboard struct\n");
2922                 return -1;
2923         }
2924
2925         if (keymap != NULL) {
2926                 keyboard->xkb_info = weston_xkb_info_create(keymap);
2927                 if (keyboard->xkb_info == NULL)
2928                         goto err;
2929         } else {
2930                 if (weston_compositor_build_global_keymap(seat->compositor) < 0)
2931                         goto err;
2932                 keyboard->xkb_info = seat->compositor->xkb_info;
2933                 keyboard->xkb_info->ref_count++;
2934         }
2935
2936         keyboard->xkb_state.state = xkb_state_new(keyboard->xkb_info->keymap);
2937         if (keyboard->xkb_state.state == NULL) {
2938                 weston_log("failed to initialise XKB state\n");
2939                 goto err;
2940         }
2941
2942         keyboard->xkb_state.leds = 0;
2943
2944         seat->keyboard_state = keyboard;
2945         seat->keyboard_device_count = 1;
2946         keyboard->seat = seat;
2947
2948         seat_send_updated_caps(seat);
2949
2950         return 0;
2951
2952 err:
2953         if (keyboard->xkb_info)
2954                 weston_xkb_info_destroy(keyboard->xkb_info);
2955         free(keyboard);
2956
2957         return -1;
2958 }
2959
2960 static void
2961 weston_keyboard_reset_state(struct weston_keyboard *keyboard)
2962 {
2963         struct weston_seat *seat = keyboard->seat;
2964         struct xkb_state *state;
2965
2966         state = xkb_state_new(keyboard->xkb_info->keymap);
2967         if (!state) {
2968                 weston_log("failed to reset XKB state\n");
2969                 return;
2970         }
2971         xkb_state_unref(keyboard->xkb_state.state);
2972         keyboard->xkb_state.state = state;
2973
2974         keyboard->xkb_state.leds = 0;
2975
2976         seat->modifier_state = 0;
2977 }
2978
2979 WL_EXPORT void
2980 weston_seat_release_keyboard(struct weston_seat *seat)
2981 {
2982         seat->keyboard_device_count--;
2983         assert(seat->keyboard_device_count >= 0);
2984         if (seat->keyboard_device_count == 0) {
2985                 weston_keyboard_set_focus(seat->keyboard_state, NULL);
2986                 weston_keyboard_cancel_grab(seat->keyboard_state);
2987                 weston_keyboard_reset_state(seat->keyboard_state);
2988                 seat_send_updated_caps(seat);
2989         }
2990 }
2991
2992 WL_EXPORT void
2993 weston_seat_init_pointer(struct weston_seat *seat)
2994 {
2995         struct weston_pointer *pointer;
2996
2997         if (seat->pointer_state) {
2998                 seat->pointer_device_count += 1;
2999                 if (seat->pointer_device_count == 1)
3000                         seat_send_updated_caps(seat);
3001                 return;
3002         }
3003
3004         pointer = weston_pointer_create(seat);
3005         if (pointer == NULL)
3006                 return;
3007
3008         seat->pointer_state = pointer;
3009         seat->pointer_device_count = 1;
3010         pointer->seat = seat;
3011
3012         seat_send_updated_caps(seat);
3013 }
3014
3015 WL_EXPORT void
3016 weston_seat_release_pointer(struct weston_seat *seat)
3017 {
3018         struct weston_pointer *pointer = seat->pointer_state;
3019
3020         seat->pointer_device_count--;
3021         if (seat->pointer_device_count == 0) {
3022                 weston_pointer_clear_focus(pointer);
3023                 weston_pointer_cancel_grab(pointer);
3024
3025                 if (pointer->sprite)
3026                         pointer_unmap_sprite(pointer);
3027
3028                 weston_pointer_reset_state(pointer);
3029                 seat_send_updated_caps(seat);
3030
3031                 /* seat->pointer is intentionally not destroyed so that
3032                  * a newly attached pointer on this seat will retain
3033                  * the previous cursor co-ordinates.
3034                  */
3035         }
3036 }
3037
3038 WL_EXPORT void
3039 weston_seat_init_touch(struct weston_seat *seat)
3040 {
3041         struct weston_touch *touch;
3042
3043         if (seat->touch_state) {
3044                 seat->touch_device_count += 1;
3045                 if (seat->touch_device_count == 1)
3046                         seat_send_updated_caps(seat);
3047                 return;
3048         }
3049
3050         touch = weston_touch_create();
3051         if (touch == NULL)
3052                 return;
3053
3054         seat->touch_state = touch;
3055         seat->touch_device_count = 1;
3056         touch->seat = seat;
3057
3058         seat_send_updated_caps(seat);
3059 }
3060
3061 WL_EXPORT void
3062 weston_seat_release_touch(struct weston_seat *seat)
3063 {
3064         seat->touch_device_count--;
3065         if (seat->touch_device_count == 0) {
3066                 weston_touch_set_focus(seat->touch_state, NULL);
3067                 weston_touch_cancel_grab(seat->touch_state);
3068                 weston_touch_reset_state(seat->touch_state);
3069                 seat_send_updated_caps(seat);
3070         }
3071 }
3072
3073 WL_EXPORT void
3074 weston_seat_init(struct weston_seat *seat, struct weston_compositor *ec,
3075                  const char *seat_name)
3076 {
3077         memset(seat, 0, sizeof *seat);
3078
3079         seat->selection_data_source = NULL;
3080         wl_list_init(&seat->base_resource_list);
3081         wl_signal_init(&seat->selection_signal);
3082         wl_list_init(&seat->drag_resource_list);
3083         wl_signal_init(&seat->destroy_signal);
3084         wl_signal_init(&seat->updated_caps_signal);
3085
3086         seat->global = wl_global_create(ec->wl_display, &wl_seat_interface, 5,
3087                                         seat, bind_seat);
3088
3089         seat->compositor = ec;
3090         seat->modifier_state = 0;
3091         seat->seat_name = strdup(seat_name);
3092
3093         wl_list_insert(ec->seat_list.prev, &seat->link);
3094
3095         clipboard_create(seat);
3096
3097         wl_signal_emit(&ec->seat_created_signal, seat);
3098 }
3099
3100 WL_EXPORT void
3101 weston_seat_release(struct weston_seat *seat)
3102 {
3103         struct wl_resource *resource;
3104
3105         wl_resource_for_each(resource, &seat->base_resource_list) {
3106                 wl_resource_set_user_data(resource, NULL);
3107         }
3108
3109         wl_resource_for_each(resource, &seat->drag_resource_list) {
3110                 wl_resource_set_user_data(resource, NULL);
3111         }
3112
3113         wl_list_remove(&seat->base_resource_list);
3114         wl_list_remove(&seat->drag_resource_list);
3115
3116         wl_list_remove(&seat->link);
3117
3118         if (seat->saved_kbd_focus)
3119                 wl_list_remove(&seat->saved_kbd_focus_listener.link);
3120
3121         if (seat->pointer_state)
3122                 weston_pointer_destroy(seat->pointer_state);
3123         if (seat->keyboard_state)
3124                 weston_keyboard_destroy(seat->keyboard_state);
3125         if (seat->touch_state)
3126                 weston_touch_destroy(seat->touch_state);
3127
3128         free (seat->seat_name);
3129
3130         wl_global_destroy(seat->global);
3131
3132         wl_signal_emit(&seat->destroy_signal, seat);
3133 }
3134
3135 /** Get a seat's keyboard pointer
3136  *
3137  * \param seat The seat to query
3138  * \return The seat's keyboard pointer, or NULL if no keyboard is present
3139  *
3140  * The keyboard pointer for a seat isn't freed when all keyboards are removed,
3141  * so it should only be used when the seat's keyboard_device_count is greater
3142  * than zero.  This function does that test and only returns a pointer
3143  * when a keyboard is present.
3144  */
3145 WL_EXPORT struct weston_keyboard *
3146 weston_seat_get_keyboard(struct weston_seat *seat)
3147 {
3148         if (!seat)
3149                 return NULL;
3150
3151         if (seat->keyboard_device_count)
3152                 return seat->keyboard_state;
3153
3154         return NULL;
3155 }
3156
3157 /** Get a seat's pointer pointer
3158  *
3159  * \param seat The seat to query
3160  * \return The seat's pointer pointer, or NULL if no pointer device is present
3161  *
3162  * The pointer pointer for a seat isn't freed when all mice are removed,
3163  * so it should only be used when the seat's pointer_device_count is greater
3164  * than zero.  This function does that test and only returns a pointer
3165  * when a pointing device is present.
3166  */
3167 WL_EXPORT struct weston_pointer *
3168 weston_seat_get_pointer(struct weston_seat *seat)
3169 {
3170         if (!seat)
3171                 return NULL;
3172
3173         if (seat->pointer_device_count)
3174                 return seat->pointer_state;
3175
3176         return NULL;
3177 }
3178
3179 static const struct zwp_locked_pointer_v1_interface locked_pointer_interface;
3180 static const struct zwp_confined_pointer_v1_interface confined_pointer_interface;
3181
3182 static enum pointer_constraint_type
3183 pointer_constraint_get_type(struct weston_pointer_constraint *constraint)
3184 {
3185         if (wl_resource_instance_of(constraint->resource,
3186                                     &zwp_locked_pointer_v1_interface,
3187                                     &locked_pointer_interface)) {
3188                 return POINTER_CONSTRAINT_TYPE_LOCK;
3189         } else if (wl_resource_instance_of(constraint->resource,
3190                                            &zwp_confined_pointer_v1_interface,
3191                                            &confined_pointer_interface)) {
3192                 return POINTER_CONSTRAINT_TYPE_CONFINE;
3193         }
3194
3195         abort();
3196         return 0;
3197 }
3198
3199 static void
3200 pointer_constraint_notify_activated(struct weston_pointer_constraint *constraint)
3201 {
3202         struct wl_resource *resource = constraint->resource;
3203
3204         switch (pointer_constraint_get_type(constraint)) {
3205         case POINTER_CONSTRAINT_TYPE_LOCK:
3206                 zwp_locked_pointer_v1_send_locked(resource);
3207                 break;
3208         case POINTER_CONSTRAINT_TYPE_CONFINE:
3209                 zwp_confined_pointer_v1_send_confined(resource);
3210                 break;
3211         }
3212 }
3213
3214 static void
3215 pointer_constraint_notify_deactivated(struct weston_pointer_constraint *constraint)
3216 {
3217         struct wl_resource *resource = constraint->resource;
3218
3219         switch (pointer_constraint_get_type(constraint)) {
3220         case POINTER_CONSTRAINT_TYPE_LOCK:
3221                 zwp_locked_pointer_v1_send_unlocked(resource);
3222                 break;
3223         case POINTER_CONSTRAINT_TYPE_CONFINE:
3224                 zwp_confined_pointer_v1_send_unconfined(resource);
3225                 break;
3226         }
3227 }
3228
3229 static struct weston_pointer_constraint *
3230 get_pointer_constraint_for_pointer(struct weston_surface *surface,
3231                                    struct weston_pointer *pointer)
3232 {
3233         struct weston_pointer_constraint *constraint;
3234
3235         wl_list_for_each(constraint, &surface->pointer_constraints, link) {
3236                 if (constraint->pointer == pointer)
3237                         return constraint;
3238         }
3239
3240         return NULL;
3241 }
3242
3243 /** Get a seat's touch pointer
3244  *
3245  * \param seat The seat to query
3246  * \return The seat's touch pointer, or NULL if no touch device is present
3247  *
3248  * The touch pointer for a seat isn't freed when all touch devices are removed,
3249  * so it should only be used when the seat's touch_device_count is greater
3250  * than zero.  This function does that test and only returns a pointer
3251  * when a touch device is present.
3252  */
3253 WL_EXPORT struct weston_touch *
3254 weston_seat_get_touch(struct weston_seat *seat)
3255 {
3256         if (!seat)
3257                 return NULL;
3258
3259         if (seat->touch_device_count)
3260                 return seat->touch_state;
3261
3262         return NULL;
3263 }
3264
3265 /** Sets the keyboard focus to the given surface
3266  *
3267  * \param seat The seat to query
3268  */
3269 WL_EXPORT void
3270 weston_seat_set_keyboard_focus(struct weston_seat *seat,
3271                                struct weston_surface *surface)
3272 {
3273         struct weston_compositor *compositor = seat->compositor;
3274         struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat);
3275         struct weston_surface_activation_data activation_data;
3276
3277         if (keyboard && keyboard->focus != surface) {
3278                 weston_keyboard_set_focus(keyboard, surface);
3279                 wl_data_device_set_keyboard_focus(seat);
3280         }
3281
3282         inc_activate_serial(compositor);
3283
3284         activation_data = (struct weston_surface_activation_data) {
3285                 .surface = surface,
3286                 .seat = seat,
3287         };
3288         wl_signal_emit(&compositor->activate_signal, &activation_data);
3289 }
3290
3291 static void
3292 enable_pointer_constraint(struct weston_pointer_constraint *constraint,
3293                           struct weston_view *view)
3294 {
3295         assert(constraint->view == NULL);
3296         constraint->view = view;
3297         pointer_constraint_notify_activated(constraint);
3298         weston_pointer_start_grab(constraint->pointer, &constraint->grab);
3299         wl_list_remove(&constraint->surface_destroy_listener.link);
3300         wl_list_init(&constraint->surface_destroy_listener.link);
3301 }
3302
3303 static bool
3304 is_pointer_constraint_enabled(struct weston_pointer_constraint *constraint)
3305 {
3306         return constraint->view != NULL;
3307 }
3308
3309 static void
3310 weston_pointer_constraint_disable(struct weston_pointer_constraint *constraint)
3311 {
3312         constraint->view = NULL;
3313         pointer_constraint_notify_deactivated(constraint);
3314         weston_pointer_end_grab(constraint->grab.pointer);
3315 }
3316
3317 void
3318 weston_pointer_constraint_destroy(struct weston_pointer_constraint *constraint)
3319 {
3320         if (is_pointer_constraint_enabled(constraint))
3321                 weston_pointer_constraint_disable(constraint);
3322
3323         wl_list_remove(&constraint->pointer_destroy_listener.link);
3324         wl_list_remove(&constraint->surface_destroy_listener.link);
3325         wl_list_remove(&constraint->surface_commit_listener.link);
3326         wl_list_remove(&constraint->surface_activate_listener.link);
3327
3328         wl_resource_set_user_data(constraint->resource, NULL);
3329         pixman_region32_fini(&constraint->region);
3330         wl_list_remove(&constraint->link);
3331         free(constraint);
3332 }
3333
3334 static void
3335 disable_pointer_constraint(struct weston_pointer_constraint *constraint)
3336 {
3337         switch (constraint->lifetime) {
3338         case ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_ONESHOT:
3339                 weston_pointer_constraint_destroy(constraint);
3340                 break;
3341         case ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT:
3342                 weston_pointer_constraint_disable(constraint);
3343                 break;
3344         }
3345 }
3346
3347 static bool
3348 is_within_constraint_region(struct weston_pointer_constraint *constraint,
3349                             wl_fixed_t sx, wl_fixed_t sy)
3350 {
3351         struct weston_surface *surface = constraint->surface;
3352         pixman_region32_t constraint_region;
3353         bool result;
3354
3355         pixman_region32_init(&constraint_region);
3356         pixman_region32_intersect(&constraint_region,
3357                                   &surface->input,
3358                                   &constraint->region);
3359         result = pixman_region32_contains_point(&constraint_region,
3360                                                 wl_fixed_to_int(sx),
3361                                                 wl_fixed_to_int(sy),
3362                                                 NULL);
3363         pixman_region32_fini(&constraint_region);
3364
3365         return result;
3366 }
3367
3368 static void
3369 maybe_enable_pointer_constraint(struct weston_pointer_constraint *constraint)
3370 {
3371         struct weston_surface *surface = constraint->surface;
3372         struct weston_view *vit;
3373         struct weston_view *view = NULL;
3374         struct weston_pointer *pointer = constraint->pointer;
3375         struct weston_keyboard *keyboard;
3376         struct weston_seat *seat = pointer->seat;
3377         int32_t x, y;
3378
3379         /* Postpone if no view of the surface was most recently clicked. */
3380         wl_list_for_each(vit, &surface->views, surface_link) {
3381                 if (vit->click_to_activate_serial ==
3382                     surface->compositor->activate_serial) {
3383                         view = vit;
3384                 }
3385         }
3386         if (view == NULL)
3387                 return;
3388
3389         /* Postpone if surface doesn't have keyboard focus. */
3390         keyboard = weston_seat_get_keyboard(seat);
3391         if (!keyboard || keyboard->focus != surface)
3392                 return;
3393
3394         /* Postpone constraint if the pointer is not within the
3395          * constraint region.
3396          */
3397         weston_view_from_global(view,
3398                                 wl_fixed_to_int(pointer->x),
3399                                 wl_fixed_to_int(pointer->y),
3400                                 &x, &y);
3401         if (!is_within_constraint_region(constraint,
3402                                          wl_fixed_from_int(x),
3403                                          wl_fixed_from_int(y)))
3404                 return;
3405
3406         enable_pointer_constraint(constraint, view);
3407 }
3408
3409 static void
3410 locked_pointer_grab_pointer_focus(struct weston_pointer_grab *grab)
3411 {
3412 }
3413
3414 static void
3415 locked_pointer_grab_pointer_motion(struct weston_pointer_grab *grab,
3416                                    const struct timespec *time,
3417                                    struct weston_pointer_motion_event *event)
3418 {
3419         pointer_send_relative_motion(grab->pointer, time, event);
3420 }
3421
3422 static void
3423 locked_pointer_grab_pointer_button(struct weston_pointer_grab *grab,
3424                                    const struct timespec *time,
3425                                    uint32_t button,
3426                                    uint32_t state_w)
3427 {
3428         weston_pointer_send_button(grab->pointer, time, button, state_w);
3429 }
3430
3431 static void
3432 locked_pointer_grab_pointer_axis(struct weston_pointer_grab *grab,
3433                                  const struct timespec *time,
3434                                  struct weston_pointer_axis_event *event)
3435 {
3436         weston_pointer_send_axis(grab->pointer, time, event);
3437 }
3438
3439 static void
3440 locked_pointer_grab_pointer_axis_source(struct weston_pointer_grab *grab,
3441                                         uint32_t source)
3442 {
3443         weston_pointer_send_axis_source(grab->pointer, source);
3444 }
3445
3446 static void
3447 locked_pointer_grab_pointer_frame(struct weston_pointer_grab *grab)
3448 {
3449         weston_pointer_send_frame(grab->pointer);
3450 }
3451
3452 static void
3453 locked_pointer_grab_pointer_cancel(struct weston_pointer_grab *grab)
3454 {
3455         struct weston_pointer_constraint *constraint =
3456                 container_of(grab, struct weston_pointer_constraint, grab);
3457
3458         disable_pointer_constraint(constraint);
3459 }
3460
3461 static const struct weston_pointer_grab_interface
3462                                 locked_pointer_grab_interface = {
3463         locked_pointer_grab_pointer_focus,
3464         locked_pointer_grab_pointer_motion,
3465         locked_pointer_grab_pointer_button,
3466         locked_pointer_grab_pointer_axis,
3467         locked_pointer_grab_pointer_axis_source,
3468         locked_pointer_grab_pointer_frame,
3469         locked_pointer_grab_pointer_cancel,
3470 };
3471
3472 static void
3473 pointer_constraint_constrain_resource_destroyed(struct wl_resource *resource)
3474 {
3475         struct weston_pointer_constraint *constraint =
3476                 wl_resource_get_user_data(resource);
3477
3478         if (!constraint)
3479                 return;
3480
3481         weston_pointer_constraint_destroy(constraint);
3482 }
3483
3484 static void
3485 pointer_constraint_surface_activate(struct wl_listener *listener, void *data)
3486 {
3487         struct weston_surface_activation_data *activation = data;
3488         struct weston_pointer *pointer;
3489         struct weston_surface *focus = activation->surface;
3490         struct weston_pointer_constraint *constraint =
3491                 container_of(listener, struct weston_pointer_constraint,
3492                              surface_activate_listener);
3493         bool is_constraint_surface;
3494
3495         pointer = weston_seat_get_pointer(activation->seat);
3496         if (!pointer)
3497                 return;
3498
3499         is_constraint_surface =
3500                 get_pointer_constraint_for_pointer(focus, pointer) == constraint;
3501
3502         if (is_constraint_surface &&
3503             !is_pointer_constraint_enabled(constraint))
3504                 maybe_enable_pointer_constraint(constraint);
3505         else if (!is_constraint_surface &&
3506                  is_pointer_constraint_enabled(constraint))
3507                 disable_pointer_constraint(constraint);
3508 }
3509
3510 static void
3511 pointer_constraint_pointer_destroyed(struct wl_listener *listener, void *data)
3512 {
3513         struct weston_pointer_constraint *constraint =
3514                 container_of(listener, struct weston_pointer_constraint,
3515                              pointer_destroy_listener);
3516
3517         weston_pointer_constraint_destroy(constraint);
3518 }
3519
3520 static void
3521 pointer_constraint_surface_destroyed(struct wl_listener *listener, void *data)
3522 {
3523         struct weston_pointer_constraint *constraint =
3524                 container_of(listener, struct weston_pointer_constraint,
3525                              surface_destroy_listener);
3526
3527         weston_pointer_constraint_destroy(constraint);
3528 }
3529
3530 static void
3531 pointer_constraint_surface_committed(struct wl_listener *listener, void *data)
3532 {
3533         struct weston_pointer_constraint *constraint =
3534                 container_of(listener, struct weston_pointer_constraint,
3535                              surface_commit_listener);
3536
3537         if (constraint->region_is_pending) {
3538                 constraint->region_is_pending = false;
3539                 pixman_region32_copy(&constraint->region,
3540                                      &constraint->region_pending);
3541                 pixman_region32_fini(&constraint->region_pending);
3542                 pixman_region32_init(&constraint->region_pending);
3543         }
3544
3545         if (constraint->hint_is_pending) {
3546                 constraint->hint_is_pending = false;
3547
3548                 constraint->hint_is_pending = true;
3549                 constraint->hint_x = constraint->hint_x_pending;
3550                 constraint->hint_y = constraint->hint_y_pending;
3551         }
3552
3553         if (pointer_constraint_get_type(constraint) ==
3554             POINTER_CONSTRAINT_TYPE_CONFINE &&
3555             is_pointer_constraint_enabled(constraint))
3556                 maybe_warp_confined_pointer(constraint);
3557 }
3558
3559 static struct weston_pointer_constraint *
3560 weston_pointer_constraint_create(struct weston_surface *surface,
3561                                  struct weston_pointer *pointer,
3562                                  struct weston_region *region,
3563                                  enum zwp_pointer_constraints_v1_lifetime lifetime,
3564                                  struct wl_resource *cr,
3565                                  const struct weston_pointer_grab_interface *grab_interface)
3566 {
3567         struct weston_pointer_constraint *constraint;
3568
3569         constraint = zalloc(sizeof *constraint);
3570         if (!constraint)
3571                 return NULL;
3572
3573         constraint->lifetime = lifetime;
3574         pixman_region32_init(&constraint->region);
3575         pixman_region32_init(&constraint->region_pending);
3576         wl_list_insert(&surface->pointer_constraints, &constraint->link);
3577         constraint->surface = surface;
3578         constraint->pointer = pointer;
3579         constraint->resource = cr;
3580         constraint->grab.interface = grab_interface;
3581         if (region) {
3582                 pixman_region32_copy(&constraint->region,
3583                                      &region->region);
3584         } else {
3585                 pixman_region32_fini(&constraint->region);
3586                 region_init_infinite(&constraint->region);
3587         }
3588
3589         constraint->surface_activate_listener.notify =
3590                 pointer_constraint_surface_activate;
3591         constraint->surface_destroy_listener.notify =
3592                 pointer_constraint_surface_destroyed;
3593         constraint->surface_commit_listener.notify =
3594                 pointer_constraint_surface_committed;
3595         constraint->pointer_destroy_listener.notify =
3596                 pointer_constraint_pointer_destroyed;
3597
3598         wl_signal_add(&surface->compositor->activate_signal,
3599                       &constraint->surface_activate_listener);
3600         wl_signal_add(&pointer->destroy_signal,
3601                       &constraint->pointer_destroy_listener);
3602         wl_signal_add(&surface->destroy_signal,
3603                       &constraint->surface_destroy_listener);
3604         wl_signal_add(&surface->commit_signal,
3605                       &constraint->surface_commit_listener);
3606
3607         return constraint;
3608 }
3609
3610 static void
3611 init_pointer_constraint(struct wl_resource *pointer_constraints_resource,
3612                         uint32_t id,
3613                         struct weston_surface *surface,
3614                         struct weston_pointer *pointer,
3615                         struct weston_region *region,
3616                         enum zwp_pointer_constraints_v1_lifetime lifetime,
3617                         const struct wl_interface *interface,
3618                         const void *implementation,
3619                         const struct weston_pointer_grab_interface *grab_interface)
3620 {
3621         struct wl_client *client =
3622                 wl_resource_get_client(pointer_constraints_resource);
3623         struct wl_resource *cr;
3624         struct weston_pointer_constraint *constraint;
3625
3626         if (pointer && get_pointer_constraint_for_pointer(surface, pointer)) {
3627                 wl_resource_post_error(pointer_constraints_resource,
3628                                        ZWP_POINTER_CONSTRAINTS_V1_ERROR_ALREADY_CONSTRAINED,
3629                                        "the pointer has a lock/confine request on this surface");
3630                 return;
3631         }
3632
3633         cr = wl_resource_create(client, interface,
3634                                 wl_resource_get_version(pointer_constraints_resource),
3635                                 id);
3636         if (cr == NULL) {
3637                 wl_client_post_no_memory(client);
3638                 return;
3639         }
3640
3641         if (pointer) {
3642                 constraint = weston_pointer_constraint_create(surface, pointer,
3643                                                               region, lifetime,
3644                                                               cr, grab_interface);
3645                 if (constraint == NULL) {
3646                         wl_client_post_no_memory(client);
3647                         return;
3648                 }
3649         } else {
3650                 constraint = NULL;
3651         }
3652
3653         wl_resource_set_implementation(cr, implementation, constraint,
3654                                        pointer_constraint_constrain_resource_destroyed);
3655
3656         if (constraint)
3657                 maybe_enable_pointer_constraint(constraint);
3658 }
3659
3660 static void
3661 pointer_constraints_destroy(struct wl_client *client,
3662                             struct wl_resource *resource)
3663 {
3664         wl_resource_destroy(resource);
3665 }
3666
3667 static void
3668 locked_pointer_destroy(struct wl_client *client,
3669                        struct wl_resource *resource)
3670 {
3671         struct weston_pointer_constraint *constraint =
3672                 wl_resource_get_user_data(resource);
3673         wl_fixed_t x, y;
3674
3675         if (constraint && constraint->view && constraint->hint_is_pending &&
3676             is_within_constraint_region(constraint,
3677                                         constraint->hint_x,
3678                                         constraint->hint_y)) {
3679                 weston_view_to_global_fixed(constraint->view,
3680                                             constraint->hint_x,
3681                                             constraint->hint_y,
3682                                             &x, &y);
3683                 weston_pointer_move_to(constraint->pointer, x, y);
3684         }
3685         wl_resource_destroy(resource);
3686 }
3687
3688 static void
3689 locked_pointer_set_cursor_position_hint(struct wl_client *client,
3690                                         struct wl_resource *resource,
3691                                         wl_fixed_t surface_x,
3692                                         wl_fixed_t surface_y)
3693 {
3694         struct weston_pointer_constraint *constraint =
3695                 wl_resource_get_user_data(resource);
3696
3697         /* Ignore a set cursor hint that was sent after the lock was cancelled.
3698          */
3699         if (!constraint ||
3700             !constraint->resource ||
3701             constraint->resource != resource)
3702                 return;
3703
3704         constraint->hint_is_pending = true;
3705         constraint->hint_x_pending = surface_x;
3706         constraint->hint_y_pending = surface_y;
3707 }
3708
3709 static void
3710 locked_pointer_set_region(struct wl_client *client,
3711                           struct wl_resource *resource,
3712                           struct wl_resource *region_resource)
3713 {
3714         struct weston_pointer_constraint *constraint =
3715                 wl_resource_get_user_data(resource);
3716         struct weston_region *region = region_resource ?
3717                 wl_resource_get_user_data(region_resource) : NULL;
3718
3719         if (!constraint)
3720                 return;
3721
3722         if (region) {
3723                 pixman_region32_copy(&constraint->region_pending,
3724                                      &region->region);
3725         } else {
3726                 pixman_region32_fini(&constraint->region_pending);
3727                 region_init_infinite(&constraint->region_pending);
3728         }
3729         constraint->region_is_pending = true;
3730 }
3731
3732
3733 static const struct zwp_locked_pointer_v1_interface locked_pointer_interface = {
3734         locked_pointer_destroy,
3735         locked_pointer_set_cursor_position_hint,
3736         locked_pointer_set_region,
3737 };
3738
3739 static void
3740 pointer_constraints_lock_pointer(struct wl_client *client,
3741                                  struct wl_resource *resource,
3742                                  uint32_t id,
3743                                  struct wl_resource *surface_resource,
3744                                  struct wl_resource *pointer_resource,
3745                                  struct wl_resource *region_resource,
3746                                  uint32_t lifetime)
3747 {
3748         struct weston_surface *surface =
3749                 wl_resource_get_user_data(surface_resource);
3750         struct weston_pointer *pointer = wl_resource_get_user_data(pointer_resource);
3751         struct weston_region *region = region_resource ?
3752                 wl_resource_get_user_data(region_resource) : NULL;
3753
3754         init_pointer_constraint(resource, id, surface, pointer, region, lifetime,
3755                                 &zwp_locked_pointer_v1_interface,
3756                                 &locked_pointer_interface,
3757                                 &locked_pointer_grab_interface);
3758 }
3759
3760 static void
3761 confined_pointer_grab_pointer_focus(struct weston_pointer_grab *grab)
3762 {
3763 }
3764
3765 static double
3766 vec2d_cross_product(struct vec2d a, struct vec2d b)
3767 {
3768         return a.x * b.y - a.y * b.x;
3769 }
3770
3771 static struct vec2d
3772 vec2d_add(struct vec2d a, struct vec2d b)
3773 {
3774         return (struct vec2d) {
3775                 .x = a.x + b.x,
3776                 .y = a.y + b.y,
3777         };
3778 }
3779
3780 static struct vec2d
3781 vec2d_subtract(struct vec2d a, struct vec2d b)
3782 {
3783         return (struct vec2d) {
3784                 .x = a.x - b.x,
3785                 .y = a.y - b.y,
3786         };
3787 }
3788
3789 static struct vec2d
3790 vec2d_multiply_constant(double c, struct vec2d a)
3791 {
3792         return (struct vec2d) {
3793                 .x = c * a.x,
3794                 .y = c * a.y,
3795         };
3796 }
3797
3798 static bool
3799 lines_intersect(struct line *line1, struct line *line2,
3800                 struct vec2d *intersection)
3801 {
3802         struct vec2d p = line1->a;
3803         struct vec2d r = vec2d_subtract(line1->b, line1->a);
3804         struct vec2d q = line2->a;
3805         struct vec2d s = vec2d_subtract(line2->b, line2->a);
3806         double rxs;
3807         double sxr;
3808         double t;
3809         double u;
3810
3811         /*
3812          * The line (p, r) and (q, s) intersects where
3813          *
3814          *   p + t r = q + u s
3815          *
3816          * Calculate t:
3817          *
3818          *   (p + t r) × s = (q + u s) × s
3819          *   p × s + t (r × s) = q × s + u (s × s)
3820          *   p × s + t (r × s) = q × s
3821          *   t (r × s) = q × s - p × s
3822          *   t (r × s) = (q - p) × s
3823          *   t = ((q - p) × s) / (r × s)
3824          *
3825          * Using the same method, for u we get:
3826          *
3827          *   u = ((p - q) × r) / (s × r)
3828          */
3829
3830         rxs = vec2d_cross_product(r, s);
3831         sxr = vec2d_cross_product(s, r);
3832
3833         /* If r × s = 0 then the lines are either parallel or collinear. */
3834         if (fabs(rxs) < DBL_MIN)
3835                 return false;
3836
3837         t = vec2d_cross_product(vec2d_subtract(q, p), s) / rxs;
3838         u = vec2d_cross_product(vec2d_subtract(p, q), r) / sxr;
3839
3840         /* The lines only intersect if 0 ≤ t ≤ 1 and 0 ≤ u ≤ 1. */
3841         if (t < 0.0 || t > 1.0 || u < 0.0 || u > 1.0)
3842                 return false;
3843
3844         *intersection = vec2d_add(p, vec2d_multiply_constant(t, r));
3845         return true;
3846 }
3847
3848 static struct border *
3849 add_border(struct wl_array *array,
3850            double x1, double y1,
3851            double x2, double y2,
3852            enum motion_direction blocking_dir)
3853 {
3854         struct border *border = wl_array_add(array, sizeof *border);
3855
3856         *border = (struct border) {
3857                 .line = (struct line) {
3858                         .a = (struct vec2d) {
3859                                 .x = x1,
3860                                 .y = y1,
3861                         },
3862                         .b = (struct vec2d) {
3863                                 .x = x2,
3864                                 .y = y2,
3865                         },
3866                 },
3867                 .blocking_dir = blocking_dir,
3868         };
3869
3870         return border;
3871 }
3872
3873 static int
3874 compare_lines_x(const void *a, const void *b)
3875 {
3876         const struct border *border_a = a;
3877         const struct border *border_b = b;
3878
3879
3880         if (border_a->line.a.x == border_b->line.a.x)
3881                 return border_a->line.b.x < border_b->line.b.x;
3882         else
3883                 return border_a->line.a.x > border_b->line.a.x;
3884 }
3885
3886 static void
3887 add_non_overlapping_edges(pixman_box32_t *boxes,
3888                           int band_above_start,
3889                           int band_below_start,
3890                           int band_below_end,
3891                           struct wl_array *borders)
3892 {
3893         int i;
3894         struct wl_array band_merge;
3895         struct border *border;
3896         struct border *prev_border;
3897         struct border *new_border;
3898
3899         wl_array_init(&band_merge);
3900
3901         /* Add bottom band of previous row, and top band of current row, and
3902          * sort them so lower left x coordinate comes first. If there are two
3903          * borders with the same left x coordinate, the wider one comes first.
3904          */
3905         for (i = band_above_start; i < band_below_start; i++) {
3906                 pixman_box32_t *box = &boxes[i];
3907                 add_border(&band_merge, box->x1, box->y2, box->x2, box->y2,
3908                            MOTION_DIRECTION_POSITIVE_Y);
3909         }
3910         for (i = band_below_start; i < band_below_end; i++) {
3911                 pixman_box32_t *box= &boxes[i];
3912                 add_border(&band_merge, box->x1, box->y1, box->x2, box->y1,
3913                            MOTION_DIRECTION_NEGATIVE_Y);
3914         }
3915         qsort(band_merge.data,
3916               band_merge.size / sizeof *border,
3917               sizeof *border,
3918               compare_lines_x);
3919
3920         /* Combine the two combined bands so that any overlapping border is
3921          * eliminated. */
3922         prev_border = NULL;
3923         wl_array_for_each(border, &band_merge) {
3924                 assert(border->line.a.y == border->line.b.y);
3925                 assert(!prev_border ||
3926                        prev_border->line.a.y == border->line.a.y);
3927                 assert(!prev_border ||
3928                        (prev_border->line.a.x != border->line.a.x ||
3929                         prev_border->line.b.x != border->line.b.x));
3930                 assert(!prev_border ||
3931                        prev_border->line.a.x <= border->line.a.x);
3932
3933                 if (prev_border &&
3934                     prev_border->line.a.x == border->line.a.x) {
3935                         /*
3936                          * ------------ +
3937                          * -------      =
3938                          * [     ]-----
3939                          */
3940                         prev_border->line.a.x = border->line.b.x;
3941                 } else if (prev_border &&
3942                            prev_border->line.b.x == border->line.b.x) {
3943                         /*
3944                          * ------------ +
3945                          *       ------ =
3946                          * ------[    ]
3947                          */
3948                         prev_border->line.b.x = border->line.a.x;
3949                 } else if (prev_border &&
3950                            prev_border->line.b.x == border->line.a.x) {
3951                         /*
3952                          * --------        +
3953                          *         ------  =
3954                          * --------------
3955                          */
3956                         prev_border->line.b.x = border->line.b.x;
3957                 } else if (prev_border &&
3958                            prev_border->line.b.x >= border->line.a.x) {
3959                         /*
3960                          * --------------- +
3961                          *      ------     =
3962                          * -----[    ]----
3963                          */
3964                         new_border = add_border(borders,
3965                                                 border->line.b.x,
3966                                                 border->line.b.y,
3967                                                 prev_border->line.b.x,
3968                                                 prev_border->line.b.y,
3969                                                 prev_border->blocking_dir);
3970                         prev_border->line.b.x = border->line.a.x;
3971                         prev_border = new_border;
3972                 } else {
3973                         assert(!prev_border ||
3974                                prev_border->line.b.x < border->line.a.x);
3975                         /*
3976                          * First border or non-overlapping.
3977                          *
3978                          * -----           +
3979                          *        -----    =
3980                          * -----  -----
3981                          */
3982                         new_border = wl_array_add(borders, sizeof *border);
3983                         *new_border = *border;
3984                         prev_border = new_border;
3985                 }
3986         }
3987
3988         wl_array_release(&band_merge);
3989 }
3990
3991 static void
3992 add_band_bottom_edges(pixman_box32_t *boxes,
3993                       int band_start,
3994                       int band_end,
3995                       struct wl_array *borders)
3996 {
3997         int i;
3998
3999         for (i = band_start; i < band_end; i++) {
4000                 add_border(borders,
4001                            boxes[i].x1, boxes[i].y2,
4002                            boxes[i].x2, boxes[i].y2,
4003                            MOTION_DIRECTION_POSITIVE_Y);
4004         }
4005 }
4006
4007 static void
4008 region_to_outline(pixman_region32_t *region, struct wl_array *borders)
4009 {
4010         pixman_box32_t *boxes;
4011         int num_boxes;
4012         int i;
4013         int top_most, bottom_most;
4014         int current_roof;
4015         int prev_top;
4016         int band_start, prev_band_start;
4017
4018         /*
4019          * Remove any overlapping lines from the set of rectangles. Note that
4020          * pixman regions are grouped as rows of rectangles, where rectangles
4021          * in one row never touch or overlap and are all of the same height.
4022          *
4023          *             -------- ---                   -------- ---
4024          *             |      | | |                   |      | | |
4025          *   ----------====---- ---         -----------  ----- ---
4026          *   |            |            =>   |            |
4027          *   ----==========---------        -----        ----------
4028          *       |                 |            |                 |
4029          *       -------------------            -------------------
4030          *
4031          */
4032
4033         boxes = pixman_region32_rectangles(region, &num_boxes);
4034         prev_top = 0;
4035         top_most = boxes[0].y1;
4036         current_roof = top_most;
4037         bottom_most = boxes[num_boxes - 1].y2;
4038         band_start = 0;
4039         prev_band_start = 0;
4040         for (i = 0; i < num_boxes; i++) {
4041                 /* Detect if there is a vertical empty space, and add the lower
4042                  * level of the previous band if so was the case. */
4043                 if (i > 0 &&
4044                     boxes[i].y1 != prev_top &&
4045                     boxes[i].y1 != boxes[i - 1].y2) {
4046                         current_roof = boxes[i].y1;
4047                         add_band_bottom_edges(boxes,
4048                                               band_start,
4049                                               i,
4050                                               borders);
4051                 }
4052
4053                 /* Special case adding the last band, since it won't be handled
4054                  * by the band change detection below. */
4055                 if (boxes[i].y1 != current_roof && i == num_boxes - 1) {
4056                         if (boxes[i].y1 != prev_top) {
4057                                 /* The last band is a single box, so we don't
4058                                  * have a prev_band_start to tell us when the
4059                                  * previous band started. */
4060                                 add_non_overlapping_edges(boxes,
4061                                                           band_start,
4062                                                           i,
4063                                                           i + 1,
4064                                                           borders);
4065                         } else {
4066                                 add_non_overlapping_edges(boxes,
4067                                                           prev_band_start,
4068                                                           band_start,
4069                                                           i + 1,
4070                                                           borders);
4071                         }
4072                 }
4073
4074                 /* Detect when passing a band and combine the top border of the
4075                  * just passed band with the bottom band of the previous band.
4076                  */
4077                 if (boxes[i].y1 != top_most && boxes[i].y1 != prev_top) {
4078                         /* Combine the two passed bands. */
4079                         if (prev_top != current_roof) {
4080                                 add_non_overlapping_edges(boxes,
4081                                                           prev_band_start,
4082                                                           band_start,
4083                                                           i,
4084                                                           borders);
4085                         }
4086
4087                         prev_band_start = band_start;
4088                         band_start = i;
4089                 }
4090
4091                 /* Add the top border if the box is part of the current roof. */
4092                 if (boxes[i].y1 == current_roof) {
4093                         add_border(borders,
4094                                    boxes[i].x1, boxes[i].y1,
4095                                    boxes[i].x2, boxes[i].y1,
4096                                    MOTION_DIRECTION_NEGATIVE_Y);
4097                 }
4098
4099                 /* Add the bottom border of the last band. */
4100                 if (boxes[i].y2 == bottom_most) {
4101                         add_border(borders,
4102                                    boxes[i].x1, boxes[i].y2,
4103                                    boxes[i].x2, boxes[i].y2,
4104                                    MOTION_DIRECTION_POSITIVE_Y);
4105                 }
4106
4107                 /* Always add the left border. */
4108                 add_border(borders,
4109                            boxes[i].x1, boxes[i].y1,
4110                            boxes[i].x1, boxes[i].y2,
4111                            MOTION_DIRECTION_NEGATIVE_X);
4112
4113                 /* Always add the right border. */
4114                 add_border(borders,
4115                            boxes[i].x2, boxes[i].y1,
4116                            boxes[i].x2, boxes[i].y2,
4117                            MOTION_DIRECTION_POSITIVE_X);
4118
4119                 prev_top = boxes[i].y1;
4120         }
4121 }
4122
4123 static bool
4124 is_border_horizontal (struct border *border)
4125 {
4126         return border->line.a.y == border->line.b.y;
4127 }
4128
4129 static bool
4130 is_border_blocking_directions(struct border *border,
4131                               uint32_t directions)
4132 {
4133         /* Don't block parallel motions. */
4134         if (is_border_horizontal(border)) {
4135                 if ((directions & (MOTION_DIRECTION_POSITIVE_Y |
4136                                    MOTION_DIRECTION_NEGATIVE_Y)) == 0)
4137                         return false;
4138         } else {
4139                 if ((directions & (MOTION_DIRECTION_POSITIVE_X |
4140                                    MOTION_DIRECTION_NEGATIVE_X)) == 0)
4141                         return false;
4142         }
4143
4144         return (~border->blocking_dir & directions) != directions;
4145 }
4146
4147 static struct border *
4148 get_closest_border(struct wl_array *borders,
4149                    struct line *motion,
4150                    uint32_t directions)
4151 {
4152         struct border *border;
4153         struct vec2d intersection;
4154         struct vec2d delta;
4155         double distance_2;
4156         struct border *closest_border = NULL;
4157         double closest_distance_2 = DBL_MAX;
4158
4159         wl_array_for_each(border, borders) {
4160                 if (!is_border_blocking_directions(border, directions))
4161                         continue;
4162
4163                 if (!lines_intersect(&border->line, motion, &intersection))
4164                         continue;
4165
4166                 delta = vec2d_subtract(intersection, motion->a);
4167                 distance_2 = delta.x*delta.x + delta.y*delta.y;
4168                 if (distance_2 < closest_distance_2) {
4169                         closest_border = border;
4170                         closest_distance_2 = distance_2;
4171                 }
4172         }
4173
4174         return closest_border;
4175 }
4176
4177 static void
4178 clamp_to_border(struct border *border,
4179                 struct line *motion,
4180                 uint32_t *motion_dir)
4181 {
4182         /*
4183          * When clamping either rightward or downward motions, the motion needs
4184          * to be clamped so that the destination coordinate does not end up on
4185          * the border (see weston_pointer_clamp_event_to_region). Do this by
4186          * clamping such motions to the border minus the smallest possible
4187          * wl_fixed_t value.
4188          */
4189         if (is_border_horizontal(border)) {
4190                 if (*motion_dir & MOTION_DIRECTION_POSITIVE_Y)
4191                         motion->b.y = border->line.a.y - wl_fixed_to_double(1);
4192                 else
4193                         motion->b.y = border->line.a.y;
4194                 *motion_dir &= ~(MOTION_DIRECTION_POSITIVE_Y |
4195                                  MOTION_DIRECTION_NEGATIVE_Y);
4196         } else {
4197                 if (*motion_dir & MOTION_DIRECTION_POSITIVE_X)
4198                         motion->b.x = border->line.a.x - wl_fixed_to_double(1);
4199                 else
4200                         motion->b.x = border->line.a.x;
4201                 *motion_dir &= ~(MOTION_DIRECTION_POSITIVE_X |
4202                                  MOTION_DIRECTION_NEGATIVE_X);
4203         }
4204 }
4205
4206 static uint32_t
4207 get_motion_directions(struct line *motion)
4208 {
4209         uint32_t directions = 0;
4210
4211         if (motion->a.x < motion->b.x)
4212                 directions |= MOTION_DIRECTION_POSITIVE_X;
4213         else if (motion->a.x > motion->b.x)
4214                 directions |= MOTION_DIRECTION_NEGATIVE_X;
4215         if (motion->a.y < motion->b.y)
4216                 directions |= MOTION_DIRECTION_POSITIVE_Y;
4217         else if (motion->a.y > motion->b.y)
4218                 directions |= MOTION_DIRECTION_NEGATIVE_Y;
4219
4220         return directions;
4221 }
4222
4223 static void
4224 weston_pointer_clamp_event_to_region(struct weston_pointer *pointer,
4225                                      struct weston_pointer_motion_event *event,
4226                                      pixman_region32_t *region,
4227                                      wl_fixed_t *clamped_x,
4228                                      wl_fixed_t *clamped_y)
4229 {
4230         wl_fixed_t x, y;
4231         wl_fixed_t sx, sy;
4232         wl_fixed_t old_sx = pointer->sx;
4233         wl_fixed_t old_sy = pointer->sy;
4234         struct wl_array borders;
4235         struct line motion;
4236         struct border *closest_border;
4237         float new_x_f, new_y_f;
4238         uint32_t directions;
4239
4240         weston_pointer_motion_to_abs(pointer, event, &x, &y);
4241         weston_view_from_global_fixed(pointer->focus, x, y, &sx, &sy);
4242
4243         wl_array_init(&borders);
4244
4245         /*
4246          * Generate borders given the confine region we are to use. The borders
4247          * are defined to be the outer region of the allowed area. This means
4248          * top/left borders are "within" the allowed area, while bottom/right
4249          * borders are outside. This needs to be considered when clamping
4250          * confined motion vectors.
4251          */
4252         region_to_outline(region, &borders);
4253
4254         motion = (struct line) {
4255                 .a = (struct vec2d) {
4256                         .x = wl_fixed_to_double(old_sx),
4257                         .y = wl_fixed_to_double(old_sy),
4258                 },
4259                 .b = (struct vec2d) {
4260                         .x = wl_fixed_to_double(sx),
4261                         .y = wl_fixed_to_double(sy),
4262                 },
4263         };
4264         directions = get_motion_directions(&motion);
4265
4266         while (directions) {
4267                 closest_border = get_closest_border(&borders,
4268                                                     &motion,
4269                                                     directions);
4270                 if (closest_border)
4271                         clamp_to_border(closest_border, &motion, &directions);
4272                 else
4273                         break;
4274         }
4275
4276         weston_view_to_global_float(pointer->focus,
4277                                     (float) motion.b.x, (float) motion.b.y,
4278                                     &new_x_f, &new_y_f);
4279         *clamped_x = wl_fixed_from_double(new_x_f);
4280         *clamped_y = wl_fixed_from_double(new_y_f);
4281
4282         wl_array_release(&borders);
4283 }
4284
4285 static double
4286 point_to_border_distance_2(struct border *border, double x, double y)
4287 {
4288         double orig_x, orig_y;
4289         double dx, dy;
4290
4291         if (is_border_horizontal(border)) {
4292                 if (x < border->line.a.x)
4293                         orig_x = border->line.a.x;
4294                 else if (x > border->line.b.x)
4295                         orig_x = border->line.b.x;
4296                 else
4297                         orig_x = x;
4298                 orig_y = border->line.a.y;
4299         } else {
4300                 if (y < border->line.a.y)
4301                         orig_y = border->line.a.y;
4302                 else if (y > border->line.b.y)
4303                         orig_y = border->line.b.y;
4304                 else
4305                         orig_y = y;
4306                 orig_x = border->line.a.x;
4307         }
4308
4309
4310         dx = fabs(orig_x - x);
4311         dy = fabs(orig_y - y);
4312         return dx*dx + dy*dy;
4313 }
4314
4315 static void
4316 warp_to_behind_border(struct border *border, wl_fixed_t *sx, wl_fixed_t *sy)
4317 {
4318         switch (border->blocking_dir) {
4319         case MOTION_DIRECTION_POSITIVE_X:
4320         case MOTION_DIRECTION_NEGATIVE_X:
4321                 if (border->blocking_dir == MOTION_DIRECTION_POSITIVE_X)
4322                         *sx = wl_fixed_from_double(border->line.a.x) - 1;
4323                 else
4324                         *sx = wl_fixed_from_double(border->line.a.x) + 1;
4325                 if (*sy < wl_fixed_from_double(border->line.a.y))
4326                         *sy = wl_fixed_from_double(border->line.a.y) + 1;
4327                 else if (*sy > wl_fixed_from_double(border->line.b.y))
4328                         *sy = wl_fixed_from_double(border->line.b.y) - 1;
4329                 break;
4330         case MOTION_DIRECTION_POSITIVE_Y:
4331         case MOTION_DIRECTION_NEGATIVE_Y:
4332                 if (border->blocking_dir == MOTION_DIRECTION_POSITIVE_Y)
4333                         *sy = wl_fixed_from_double(border->line.a.y) - 1;
4334                 else
4335                         *sy = wl_fixed_from_double(border->line.a.y) + 1;
4336                 if (*sx < wl_fixed_from_double(border->line.a.x))
4337                         *sx = wl_fixed_from_double(border->line.a.x) + 1;
4338                 else if (*sx > wl_fixed_from_double(border->line.b.x))
4339                         *sx = wl_fixed_from_double(border->line.b.x) - 1;
4340                 break;
4341         }
4342 }
4343
4344 static void
4345 maybe_warp_confined_pointer(struct weston_pointer_constraint *constraint)
4346 {
4347         wl_fixed_t x;
4348         wl_fixed_t y;
4349         wl_fixed_t sx;
4350         wl_fixed_t sy;
4351
4352         weston_view_from_global_fixed(constraint->view,
4353                                       constraint->pointer->x,
4354                                       constraint->pointer->y,
4355                                       &sx,
4356                                       &sy);
4357
4358         if (!is_within_constraint_region(constraint, sx, sy)) {
4359                 double xf = wl_fixed_to_double(sx);
4360                 double yf = wl_fixed_to_double(sy);
4361                 pixman_region32_t confine_region;
4362                 struct wl_array borders;
4363                 struct border *border;
4364                 double closest_distance_2 = DBL_MAX;
4365                 struct border *closest_border = NULL;
4366
4367                 wl_array_init(&borders);
4368
4369                 pixman_region32_init(&confine_region);
4370                 pixman_region32_intersect(&confine_region,
4371                                           &constraint->view->surface->input,
4372                                           &constraint->region);
4373                 region_to_outline(&confine_region, &borders);
4374                 pixman_region32_fini(&confine_region);
4375
4376                 wl_array_for_each(border, &borders) {
4377                         double distance_2;
4378
4379                         distance_2 = point_to_border_distance_2(border, xf, yf);
4380                         if (distance_2 < closest_distance_2) {
4381                                 closest_border = border;
4382                                 closest_distance_2 = distance_2;
4383                         }
4384                 }
4385                 assert(closest_border);
4386
4387                 warp_to_behind_border(closest_border, &sx, &sy);
4388
4389                 wl_array_release(&borders);
4390
4391                 weston_view_to_global_fixed(constraint->view, sx, sy, &x, &y);
4392                 weston_pointer_move_to(constraint->pointer, x, y);
4393         }
4394 }
4395
4396 static void
4397 confined_pointer_grab_pointer_motion(struct weston_pointer_grab *grab,
4398                                      const struct timespec *time,
4399                                      struct weston_pointer_motion_event *event)
4400 {
4401         struct weston_pointer_constraint *constraint =
4402                 container_of(grab, struct weston_pointer_constraint, grab);
4403         struct weston_pointer *pointer = grab->pointer;
4404         struct weston_surface *surface;
4405         wl_fixed_t x, y;
4406         wl_fixed_t old_sx = pointer->sx;
4407         wl_fixed_t old_sy = pointer->sy;
4408         pixman_region32_t confine_region;
4409
4410         assert(pointer->focus);
4411         assert(pointer->focus->surface == constraint->surface);
4412
4413         surface = pointer->focus->surface;
4414
4415         pixman_region32_init(&confine_region);
4416         pixman_region32_intersect(&confine_region,
4417                                   &surface->input,
4418                                   &constraint->region);
4419         weston_pointer_clamp_event_to_region(pointer, event,
4420                                              &confine_region, &x, &y);
4421         weston_pointer_move_to(pointer, x, y);
4422         pixman_region32_fini(&confine_region);
4423
4424         weston_view_from_global_fixed(pointer->focus, x, y,
4425                                       &pointer->sx, &pointer->sy);
4426
4427         if (old_sx != pointer->sx || old_sy != pointer->sy) {
4428                 pointer_send_motion(pointer, time,
4429                                     pointer->sx, pointer->sy);
4430         }
4431
4432         pointer_send_relative_motion(pointer, time, event);
4433 }
4434
4435 static void
4436 confined_pointer_grab_pointer_button(struct weston_pointer_grab *grab,
4437                                      const struct timespec *time,
4438                                      uint32_t button,
4439                                      uint32_t state_w)
4440 {
4441         weston_pointer_send_button(grab->pointer, time, button, state_w);
4442 }
4443
4444 static void
4445 confined_pointer_grab_pointer_axis(struct weston_pointer_grab *grab,
4446                                    const struct timespec *time,
4447                                    struct weston_pointer_axis_event *event)
4448 {
4449         weston_pointer_send_axis(grab->pointer, time, event);
4450 }
4451
4452 static void
4453 confined_pointer_grab_pointer_axis_source(struct weston_pointer_grab *grab,
4454                                           uint32_t source)
4455 {
4456         weston_pointer_send_axis_source(grab->pointer, source);
4457 }
4458
4459 static void
4460 confined_pointer_grab_pointer_frame(struct weston_pointer_grab *grab)
4461 {
4462         weston_pointer_send_frame(grab->pointer);
4463 }
4464
4465 static void
4466 confined_pointer_grab_pointer_cancel(struct weston_pointer_grab *grab)
4467 {
4468         struct weston_pointer_constraint *constraint =
4469                 container_of(grab, struct weston_pointer_constraint, grab);
4470
4471         disable_pointer_constraint(constraint);
4472
4473         /* If this is a persistent constraint, re-add the surface destroy signal
4474          * listener only if we are currently not destroying the surface. */
4475         switch (constraint->lifetime) {
4476         case ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT:
4477                 if (constraint->surface->resource)
4478                         wl_signal_add(&constraint->surface->destroy_signal,
4479                                       &constraint->surface_destroy_listener);
4480                 break;
4481         case ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_ONESHOT:
4482                 break;
4483         }
4484 }
4485
4486 static const struct weston_pointer_grab_interface
4487                                 confined_pointer_grab_interface = {
4488         confined_pointer_grab_pointer_focus,
4489         confined_pointer_grab_pointer_motion,
4490         confined_pointer_grab_pointer_button,
4491         confined_pointer_grab_pointer_axis,
4492         confined_pointer_grab_pointer_axis_source,
4493         confined_pointer_grab_pointer_frame,
4494         confined_pointer_grab_pointer_cancel,
4495 };
4496
4497 static void
4498 confined_pointer_destroy(struct wl_client *client,
4499                          struct wl_resource *resource)
4500 {
4501         wl_resource_destroy(resource);
4502 }
4503
4504 static void
4505 confined_pointer_set_region(struct wl_client *client,
4506                             struct wl_resource *resource,
4507                             struct wl_resource *region_resource)
4508 {
4509         struct weston_pointer_constraint *constraint =
4510                 wl_resource_get_user_data(resource);
4511         struct weston_region *region = region_resource ?
4512                 wl_resource_get_user_data(region_resource) : NULL;
4513
4514         if (!constraint)
4515                 return;
4516
4517         if (region) {
4518                 pixman_region32_copy(&constraint->region_pending,
4519                                      &region->region);
4520         } else {
4521                 pixman_region32_fini(&constraint->region_pending);
4522                 region_init_infinite(&constraint->region_pending);
4523         }
4524         constraint->region_is_pending = true;
4525 }
4526
4527 static const struct zwp_confined_pointer_v1_interface confined_pointer_interface = {
4528         confined_pointer_destroy,
4529         confined_pointer_set_region,
4530 };
4531
4532 static void
4533 pointer_constraints_confine_pointer(struct wl_client *client,
4534                                     struct wl_resource *resource,
4535                                     uint32_t id,
4536                                     struct wl_resource *surface_resource,
4537                                     struct wl_resource *pointer_resource,
4538                                     struct wl_resource *region_resource,
4539                                     uint32_t lifetime)
4540 {
4541         struct weston_surface *surface =
4542                 wl_resource_get_user_data(surface_resource);
4543         struct weston_pointer *pointer = wl_resource_get_user_data(pointer_resource);
4544         struct weston_region *region = region_resource ?
4545                 wl_resource_get_user_data(region_resource) : NULL;
4546
4547         init_pointer_constraint(resource, id, surface, pointer, region, lifetime,
4548                                 &zwp_confined_pointer_v1_interface,
4549                                 &confined_pointer_interface,
4550                                 &confined_pointer_grab_interface);
4551 }
4552
4553 static const struct zwp_pointer_constraints_v1_interface pointer_constraints_interface = {
4554         pointer_constraints_destroy,
4555         pointer_constraints_lock_pointer,
4556         pointer_constraints_confine_pointer,
4557 };
4558
4559 static void
4560 bind_pointer_constraints(struct wl_client *client, void *data,
4561                          uint32_t version, uint32_t id)
4562 {
4563         struct wl_resource *resource;
4564
4565         resource = wl_resource_create(client,
4566                                       &zwp_pointer_constraints_v1_interface,
4567                                       1, id);
4568
4569         wl_resource_set_implementation(resource, &pointer_constraints_interface,
4570                                        NULL, NULL);
4571 }
4572
4573 static void
4574 input_timestamps_manager_destroy(struct wl_client *client,
4575                                  struct wl_resource *resource)
4576 {
4577         wl_resource_destroy(resource);
4578 }
4579
4580 static void
4581 input_timestamps_manager_get_keyboard_timestamps(struct wl_client *client,
4582                                                  struct wl_resource *resource,
4583                                                  uint32_t id,
4584                                                  struct wl_resource *keyboard_resource)
4585 {
4586         wl_client_post_no_memory(client);
4587 }
4588
4589 static void
4590 input_timestamps_manager_get_pointer_timestamps(struct wl_client *client,
4591                                                 struct wl_resource *resource,
4592                                                 uint32_t id,
4593                                                 struct wl_resource *pointer_resource)
4594 {
4595         wl_client_post_no_memory(client);
4596 }
4597
4598 static void
4599 input_timestamps_manager_get_touch_timestamps(struct wl_client *client,
4600                                               struct wl_resource *resource,
4601                                               uint32_t id,
4602                                               struct wl_resource *touch_resource)
4603 {
4604         wl_client_post_no_memory(client);
4605 }
4606
4607 static const struct zwp_input_timestamps_manager_v1_interface
4608                                 input_timestamps_manager_interface = {
4609         input_timestamps_manager_destroy,
4610         input_timestamps_manager_get_keyboard_timestamps,
4611         input_timestamps_manager_get_pointer_timestamps,
4612         input_timestamps_manager_get_touch_timestamps,
4613 };
4614
4615 static void
4616 bind_input_timestamps_manager(struct wl_client *client, void *data,
4617                               uint32_t version, uint32_t id)
4618 {
4619         struct wl_resource *resource =
4620                 wl_resource_create(client,
4621                                    &zwp_input_timestamps_manager_v1_interface,
4622                                    1, id);
4623
4624         if (resource == NULL) {
4625                 wl_client_post_no_memory(client);
4626                 return;
4627         }
4628
4629         wl_resource_set_implementation(resource,
4630                                        &input_timestamps_manager_interface,
4631                                        NULL, NULL);
4632 }
4633
4634 int
4635 weston_input_init(struct weston_compositor *compositor)
4636 {
4637         if (!wl_global_create(compositor->wl_display,
4638                               &zwp_relative_pointer_manager_v1_interface, 1,
4639                               compositor, bind_relative_pointer_manager))
4640                 return -1;
4641
4642         if (!wl_global_create(compositor->wl_display,
4643                               &zwp_pointer_constraints_v1_interface, 1,
4644                               NULL, bind_pointer_constraints))
4645                 return -1;
4646
4647         if (!wl_global_create(compositor->wl_display,
4648                               &zwp_input_timestamps_manager_v1_interface, 1,
4649                               NULL, bind_input_timestamps_manager))
4650                 return -1;
4651
4652         return 0;
4653 }