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