shell: Replace set_margin with set_window_geometry
[platform/upstream/weston.git] / clients / window.c
1 /*
2  * Copyright © 2008 Kristian Høgsberg
3  * Copyright © 2012-2013 Collabora, Ltd.
4  *
5  * Permission to use, copy, modify, distribute, and sell this software and its
6  * documentation for any purpose is hereby granted without fee, provided that
7  * the above copyright notice appear in all copies and that both that copyright
8  * notice and this permission notice appear in supporting documentation, and
9  * that the name of the copyright holders not be used in advertising or
10  * publicity pertaining to distribution of the software without specific,
11  * written prior permission.  The copyright holders make no representations
12  * about the suitability of this software for any purpose.  It is provided "as
13  * is" without express or implied warranty.
14  *
15  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
16  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
17  * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
18  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
19  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
20  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
21  * OF THIS SOFTWARE.
22  */
23
24 #include "config.h"
25
26 #include <stdint.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <stdarg.h>
30 #include <string.h>
31 #include <fcntl.h>
32 #include <unistd.h>
33 #include <errno.h>
34 #include <math.h>
35 #include <assert.h>
36 #include <time.h>
37 #include <cairo.h>
38 #include <sys/mman.h>
39 #include <sys/epoll.h>
40 #include <sys/timerfd.h>
41
42 #ifdef HAVE_CAIRO_EGL
43 #include <wayland-egl.h>
44
45 #ifdef USE_CAIRO_GLESV2
46 #include <GLES2/gl2.h>
47 #include <GLES2/gl2ext.h>
48 #else
49 #include <GL/gl.h>
50 #endif
51 #include <EGL/egl.h>
52 #include <EGL/eglext.h>
53
54 #include <cairo-gl.h>
55 #else /* HAVE_CAIRO_EGL */
56 typedef void *EGLDisplay;
57 typedef void *EGLConfig;
58 typedef void *EGLContext;
59 #define EGL_NO_DISPLAY ((EGLDisplay)0)
60 #endif /* no HAVE_CAIRO_EGL */
61
62 #include <xkbcommon/xkbcommon.h>
63 #include <wayland-cursor.h>
64
65 #include <linux/input.h>
66 #include <wayland-client.h>
67 #include "../shared/cairo-util.h"
68 #include "xdg-shell-client-protocol.h"
69 #include "text-cursor-position-client-protocol.h"
70 #include "workspaces-client-protocol.h"
71 #include "../shared/os-compatibility.h"
72
73 #include "window.h"
74
75 struct shm_pool;
76
77 struct global {
78         uint32_t name;
79         char *interface;
80         uint32_t version;
81         struct wl_list link;
82 };
83
84 struct display {
85         struct wl_display *display;
86         struct wl_registry *registry;
87         struct wl_compositor *compositor;
88         struct wl_subcompositor *subcompositor;
89         struct wl_shm *shm;
90         struct wl_data_device_manager *data_device_manager;
91         struct text_cursor_position *text_cursor_position;
92         struct workspace_manager *workspace_manager;
93         struct xdg_shell *xdg_shell;
94         EGLDisplay dpy;
95         EGLConfig argb_config;
96         EGLContext argb_ctx;
97         cairo_device_t *argb_device;
98         uint32_t serial;
99
100         int display_fd;
101         uint32_t display_fd_events;
102         struct task display_task;
103
104         int epoll_fd;
105         struct wl_list deferred_list;
106
107         int running;
108
109         struct wl_list global_list;
110         struct wl_list window_list;
111         struct wl_list input_list;
112         struct wl_list output_list;
113
114         struct theme *theme;
115
116         struct wl_cursor_theme *cursor_theme;
117         struct wl_cursor **cursors;
118
119         display_output_handler_t output_configure_handler;
120         display_global_handler_t global_handler;
121         display_global_handler_t global_handler_remove;
122
123         void *user_data;
124
125         struct xkb_context *xkb_context;
126
127         uint32_t workspace;
128         uint32_t workspace_count;
129
130         /* A hack to get text extents for tooltips */
131         cairo_surface_t *dummy_surface;
132         void *dummy_surface_data;
133
134         int has_rgb565;
135         int seat_version;
136 };
137
138 struct window_output {
139         struct output *output;
140         struct wl_list link;
141 };
142
143 struct toysurface {
144         /*
145          * Prepare the surface for drawing. Makes sure there is a surface
146          * of the right size available for rendering, and returns it.
147          * dx,dy are the x,y of wl_surface.attach.
148          * width,height are the new buffer size.
149          * If flags has SURFACE_HINT_RESIZE set, the user is
150          * doing continuous resizing.
151          * Returns the Cairo surface to draw to.
152          */
153         cairo_surface_t *(*prepare)(struct toysurface *base, int dx, int dy,
154                                     int32_t width, int32_t height, uint32_t flags,
155                                     enum wl_output_transform buffer_transform, int32_t buffer_scale);
156
157         /*
158          * Post the surface to the server, returning the server allocation
159          * rectangle. The Cairo surface from prepare() must be destroyed
160          * after calling this.
161          */
162         void (*swap)(struct toysurface *base,
163                      enum wl_output_transform buffer_transform, int32_t buffer_scale,
164                      struct rectangle *server_allocation);
165
166         /*
167          * Make the toysurface current with the given EGL context.
168          * Returns 0 on success, and negative of failure.
169          */
170         int (*acquire)(struct toysurface *base, EGLContext ctx);
171
172         /*
173          * Release the toysurface from the EGL context, returning control
174          * to Cairo.
175          */
176         void (*release)(struct toysurface *base);
177
178         /*
179          * Destroy the toysurface, including the Cairo surface, any
180          * backing storage, and the Wayland protocol objects.
181          */
182         void (*destroy)(struct toysurface *base);
183 };
184
185 struct surface {
186         struct window *window;
187
188         struct wl_surface *surface;
189         struct wl_subsurface *subsurface;
190         int synchronized;
191         int synchronized_default;
192         struct toysurface *toysurface;
193         struct widget *widget;
194         int redraw_needed;
195         struct wl_callback *frame_cb;
196         uint32_t last_time;
197
198         struct rectangle allocation;
199         struct rectangle server_allocation;
200
201         struct wl_region *input_region;
202         struct wl_region *opaque_region;
203
204         enum window_buffer_type buffer_type;
205         enum wl_output_transform buffer_transform;
206         int32_t buffer_scale;
207
208         cairo_surface_t *cairo_surface;
209
210         struct wl_list link;
211 };
212
213 struct window {
214         struct display *display;
215         struct wl_list window_output_list;
216         char *title;
217         struct rectangle saved_allocation;
218         struct rectangle min_allocation;
219         struct rectangle pending_allocation;
220         int x, y;
221         int redraw_needed;
222         int redraw_task_scheduled;
223         struct task redraw_task;
224         int resize_needed;
225         int custom;
226         int focused;
227
228         int resizing;
229
230         int fullscreen;
231         int maximized;
232
233         enum preferred_format preferred_format;
234
235         window_key_handler_t key_handler;
236         window_keyboard_focus_handler_t keyboard_focus_handler;
237         window_data_handler_t data_handler;
238         window_drop_handler_t drop_handler;
239         window_close_handler_t close_handler;
240         window_fullscreen_handler_t fullscreen_handler;
241         window_output_handler_t output_handler;
242         window_state_changed_handler_t state_changed_handler;
243
244         struct surface *main_surface;
245         struct xdg_surface *xdg_surface;
246         struct xdg_popup *xdg_popup;
247
248         struct window *parent;
249
250         struct window_frame *frame;
251
252         /* struct surface::link, contains also main_surface */
253         struct wl_list subsurface_list;
254
255         void *user_data;
256         struct wl_list link;
257 };
258
259 struct widget {
260         struct window *window;
261         struct surface *surface;
262         struct tooltip *tooltip;
263         struct wl_list child_list;
264         struct wl_list link;
265         struct rectangle allocation;
266         widget_resize_handler_t resize_handler;
267         widget_redraw_handler_t redraw_handler;
268         widget_enter_handler_t enter_handler;
269         widget_leave_handler_t leave_handler;
270         widget_motion_handler_t motion_handler;
271         widget_button_handler_t button_handler;
272         widget_touch_down_handler_t touch_down_handler;
273         widget_touch_up_handler_t touch_up_handler;
274         widget_touch_motion_handler_t touch_motion_handler;
275         widget_touch_frame_handler_t touch_frame_handler;
276         widget_touch_cancel_handler_t touch_cancel_handler;
277         widget_axis_handler_t axis_handler;
278         void *user_data;
279         int opaque;
280         int tooltip_count;
281         int default_cursor;
282         /* If this is set to false then no cairo surface will be
283          * created before redrawing the surface. This is useful if the
284          * redraw handler is going to do completely custom rendering
285          * such as using EGL directly */
286         int use_cairo;
287 };
288
289 struct touch_point {
290         int32_t id;
291         float x, y;
292         struct widget *widget;
293         struct wl_list link;
294 };
295
296 struct input {
297         struct display *display;
298         struct wl_seat *seat;
299         struct wl_pointer *pointer;
300         struct wl_keyboard *keyboard;
301         struct wl_touch *touch;
302         struct wl_list touch_point_list;
303         struct window *pointer_focus;
304         struct window *keyboard_focus;
305         struct window *touch_focus;
306         int current_cursor;
307         uint32_t cursor_anim_start;
308         struct wl_callback *cursor_frame_cb;
309         struct wl_surface *pointer_surface;
310         uint32_t modifiers;
311         uint32_t pointer_enter_serial;
312         uint32_t cursor_serial;
313         float sx, sy;
314         struct wl_list link;
315
316         struct widget *focus_widget;
317         struct widget *grab;
318         uint32_t grab_button;
319
320         struct wl_data_device *data_device;
321         struct data_offer *drag_offer;
322         struct data_offer *selection_offer;
323         uint32_t touch_grab;
324         int32_t touch_grab_id;
325         float drag_x, drag_y;
326         struct window *drag_focus;
327         uint32_t drag_enter_serial;
328
329         struct {
330                 struct xkb_keymap *keymap;
331                 struct xkb_state *state;
332                 xkb_mod_mask_t control_mask;
333                 xkb_mod_mask_t alt_mask;
334                 xkb_mod_mask_t shift_mask;
335         } xkb;
336
337         struct task repeat_task;
338         int repeat_timer_fd;
339         uint32_t repeat_sym;
340         uint32_t repeat_key;
341         uint32_t repeat_time;
342 };
343
344 struct output {
345         struct display *display;
346         struct wl_output *output;
347         uint32_t server_output_id;
348         struct rectangle allocation;
349         struct wl_list link;
350         int transform;
351         int scale;
352         char *make;
353         char *model;
354
355         display_output_handler_t destroy_handler;
356         void *user_data;
357 };
358
359 struct window_frame {
360         struct widget *widget;
361         struct widget *child;
362         struct frame *frame;
363 };
364
365 struct menu {
366         void *user_data;
367         struct window *window;
368         struct widget *widget;
369         struct input *input;
370         struct frame *frame;
371         const char **entries;
372         uint32_t time;
373         int current;
374         int count;
375         int release_count;
376         menu_func_t func;
377 };
378
379 struct tooltip {
380         struct widget *parent;
381         struct widget *widget;
382         char *entry;
383         struct task tooltip_task;
384         int tooltip_fd;
385         float x, y;
386 };
387
388 struct shm_pool {
389         struct wl_shm_pool *pool;
390         size_t size;
391         size_t used;
392         void *data;
393 };
394
395 enum {
396         CURSOR_DEFAULT = 100,
397         CURSOR_UNSET
398 };
399
400 static const cairo_user_data_key_t shm_surface_data_key;
401
402 /* #define DEBUG */
403
404 #ifdef DEBUG
405
406 static void
407 debug_print(void *proxy, int line, const char *func, const char *fmt, ...)
408 __attribute__ ((format (printf, 4, 5)));
409
410 static void
411 debug_print(void *proxy, int line, const char *func, const char *fmt, ...)
412 {
413         va_list ap;
414         struct timeval tv;
415
416         gettimeofday(&tv, NULL);
417         fprintf(stderr, "%8ld.%03ld ",
418                 (long)tv.tv_sec & 0xffff, (long)tv.tv_usec / 1000);
419
420         if (proxy)
421                 fprintf(stderr, "%s@%d ",
422                         wl_proxy_get_class(proxy), wl_proxy_get_id(proxy));
423
424         /*fprintf(stderr, __FILE__ ":%d:%s ", line, func);*/
425         fprintf(stderr, "%s ", func);
426
427         va_start(ap, fmt);
428         vfprintf(stderr, fmt, ap);
429         va_end(ap);
430 }
431
432 #define DBG(fmt, ...) \
433         debug_print(NULL, __LINE__, __func__, fmt, ##__VA_ARGS__)
434
435 #define DBG_OBJ(obj, fmt, ...) \
436         debug_print(obj, __LINE__, __func__, fmt, ##__VA_ARGS__)
437
438 #else
439
440 #define DBG(...) do {} while (0)
441 #define DBG_OBJ(...) do {} while (0)
442
443 #endif
444
445 static void
446 surface_to_buffer_size (enum wl_output_transform buffer_transform, int32_t buffer_scale, int32_t *width, int32_t *height)
447 {
448         int32_t tmp;
449
450         switch (buffer_transform) {
451         case WL_OUTPUT_TRANSFORM_90:
452         case WL_OUTPUT_TRANSFORM_270:
453         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
454         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
455                 tmp = *width;
456                 *width = *height;
457                 *height = tmp;
458                 break;
459         default:
460                 break;
461         }
462
463         *width *= buffer_scale;
464         *height *= buffer_scale;
465 }
466
467 static void
468 buffer_to_surface_size (enum wl_output_transform buffer_transform, int32_t buffer_scale, int32_t *width, int32_t *height)
469 {
470         int32_t tmp;
471
472         switch (buffer_transform) {
473         case WL_OUTPUT_TRANSFORM_90:
474         case WL_OUTPUT_TRANSFORM_270:
475         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
476         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
477                 tmp = *width;
478                 *width = *height;
479                 *height = tmp;
480                 break;
481         default:
482                 break;
483         }
484
485         *width /= buffer_scale;
486         *height /= buffer_scale;
487 }
488
489 #ifdef HAVE_CAIRO_EGL
490
491 struct egl_window_surface {
492         struct toysurface base;
493         cairo_surface_t *cairo_surface;
494         struct display *display;
495         struct wl_surface *surface;
496         struct wl_egl_window *egl_window;
497         EGLSurface egl_surface;
498 };
499
500 static struct egl_window_surface *
501 to_egl_window_surface(struct toysurface *base)
502 {
503         return container_of(base, struct egl_window_surface, base);
504 }
505
506 static cairo_surface_t *
507 egl_window_surface_prepare(struct toysurface *base, int dx, int dy,
508                            int32_t width, int32_t height, uint32_t flags,
509                            enum wl_output_transform buffer_transform, int32_t buffer_scale)
510 {
511         struct egl_window_surface *surface = to_egl_window_surface(base);
512
513         surface_to_buffer_size (buffer_transform, buffer_scale, &width, &height);
514
515         wl_egl_window_resize(surface->egl_window, width, height, dx, dy);
516         cairo_gl_surface_set_size(surface->cairo_surface, width, height);
517
518         return cairo_surface_reference(surface->cairo_surface);
519 }
520
521 static void
522 egl_window_surface_swap(struct toysurface *base,
523                         enum wl_output_transform buffer_transform, int32_t buffer_scale,
524                         struct rectangle *server_allocation)
525 {
526         struct egl_window_surface *surface = to_egl_window_surface(base);
527
528         cairo_gl_surface_swapbuffers(surface->cairo_surface);
529         wl_egl_window_get_attached_size(surface->egl_window,
530                                         &server_allocation->width,
531                                         &server_allocation->height);
532
533         buffer_to_surface_size (buffer_transform, buffer_scale,
534                                 &server_allocation->width,
535                                 &server_allocation->height);
536 }
537
538 static int
539 egl_window_surface_acquire(struct toysurface *base, EGLContext ctx)
540 {
541         struct egl_window_surface *surface = to_egl_window_surface(base);
542         cairo_device_t *device;
543
544         device = cairo_surface_get_device(surface->cairo_surface);
545         if (!device)
546                 return -1;
547
548         if (!ctx) {
549                 if (device == surface->display->argb_device)
550                         ctx = surface->display->argb_ctx;
551                 else
552                         assert(0);
553         }
554
555         cairo_device_flush(device);
556         cairo_device_acquire(device);
557         if (!eglMakeCurrent(surface->display->dpy, surface->egl_surface,
558                             surface->egl_surface, ctx))
559                 fprintf(stderr, "failed to make surface current\n");
560
561         return 0;
562 }
563
564 static void
565 egl_window_surface_release(struct toysurface *base)
566 {
567         struct egl_window_surface *surface = to_egl_window_surface(base);
568         cairo_device_t *device;
569
570         device = cairo_surface_get_device(surface->cairo_surface);
571         if (!device)
572                 return;
573
574         if (!eglMakeCurrent(surface->display->dpy, NULL, NULL,
575                             surface->display->argb_ctx))
576                 fprintf(stderr, "failed to make context current\n");
577
578         cairo_device_release(device);
579 }
580
581 static void
582 egl_window_surface_destroy(struct toysurface *base)
583 {
584         struct egl_window_surface *surface = to_egl_window_surface(base);
585         struct display *d = surface->display;
586
587         cairo_surface_destroy(surface->cairo_surface);
588         eglDestroySurface(d->dpy, surface->egl_surface);
589         wl_egl_window_destroy(surface->egl_window);
590         surface->surface = NULL;
591
592         free(surface);
593 }
594
595 static struct toysurface *
596 egl_window_surface_create(struct display *display,
597                           struct wl_surface *wl_surface,
598                           uint32_t flags,
599                           struct rectangle *rectangle)
600 {
601         struct egl_window_surface *surface;
602
603         if (display->dpy == EGL_NO_DISPLAY)
604                 return NULL;
605
606         surface = calloc(1, sizeof *surface);
607         if (!surface)
608                 return NULL;
609
610         surface->base.prepare = egl_window_surface_prepare;
611         surface->base.swap = egl_window_surface_swap;
612         surface->base.acquire = egl_window_surface_acquire;
613         surface->base.release = egl_window_surface_release;
614         surface->base.destroy = egl_window_surface_destroy;
615
616         surface->display = display;
617         surface->surface = wl_surface;
618
619         surface->egl_window = wl_egl_window_create(surface->surface,
620                                                    rectangle->width,
621                                                    rectangle->height);
622
623         surface->egl_surface = eglCreateWindowSurface(display->dpy,
624                                                       display->argb_config,
625                                                       surface->egl_window,
626                                                       NULL);
627
628         surface->cairo_surface =
629                 cairo_gl_surface_create_for_egl(display->argb_device,
630                                                 surface->egl_surface,
631                                                 rectangle->width,
632                                                 rectangle->height);
633
634         return &surface->base;
635 }
636
637 #else
638
639 static struct toysurface *
640 egl_window_surface_create(struct display *display,
641                           struct wl_surface *wl_surface,
642                           uint32_t flags,
643                           struct rectangle *rectangle)
644 {
645         return NULL;
646 }
647
648 #endif
649
650 struct shm_surface_data {
651         struct wl_buffer *buffer;
652         struct shm_pool *pool;
653 };
654
655 struct wl_buffer *
656 display_get_buffer_for_surface(struct display *display,
657                                cairo_surface_t *surface)
658 {
659         struct shm_surface_data *data;
660
661         data = cairo_surface_get_user_data(surface, &shm_surface_data_key);
662
663         return data->buffer;
664 }
665
666 static void
667 shm_pool_destroy(struct shm_pool *pool);
668
669 static void
670 shm_surface_data_destroy(void *p)
671 {
672         struct shm_surface_data *data = p;
673
674         wl_buffer_destroy(data->buffer);
675         if (data->pool)
676                 shm_pool_destroy(data->pool);
677
678         free(data);
679 }
680
681 static struct wl_shm_pool *
682 make_shm_pool(struct display *display, int size, void **data)
683 {
684         struct wl_shm_pool *pool;
685         int fd;
686
687         fd = os_create_anonymous_file(size);
688         if (fd < 0) {
689                 fprintf(stderr, "creating a buffer file for %d B failed: %m\n",
690                         size);
691                 return NULL;
692         }
693
694         *data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
695         if (*data == MAP_FAILED) {
696                 fprintf(stderr, "mmap failed: %m\n");
697                 close(fd);
698                 return NULL;
699         }
700
701         pool = wl_shm_create_pool(display->shm, fd, size);
702
703         close(fd);
704
705         return pool;
706 }
707
708 static struct shm_pool *
709 shm_pool_create(struct display *display, size_t size)
710 {
711         struct shm_pool *pool = malloc(sizeof *pool);
712
713         if (!pool)
714                 return NULL;
715
716         pool->pool = make_shm_pool(display, size, &pool->data);
717         if (!pool->pool) {
718                 free(pool);
719                 return NULL;
720         }
721
722         pool->size = size;
723         pool->used = 0;
724
725         return pool;
726 }
727
728 static void *
729 shm_pool_allocate(struct shm_pool *pool, size_t size, int *offset)
730 {
731         if (pool->used + size > pool->size)
732                 return NULL;
733
734         *offset = pool->used;
735         pool->used += size;
736
737         return (char *) pool->data + *offset;
738 }
739
740 /* destroy the pool. this does not unmap the memory though */
741 static void
742 shm_pool_destroy(struct shm_pool *pool)
743 {
744         munmap(pool->data, pool->size);
745         wl_shm_pool_destroy(pool->pool);
746         free(pool);
747 }
748
749 /* Start allocating from the beginning of the pool again */
750 static void
751 shm_pool_reset(struct shm_pool *pool)
752 {
753         pool->used = 0;
754 }
755
756 static int
757 data_length_for_shm_surface(struct rectangle *rect)
758 {
759         int stride;
760
761         stride = cairo_format_stride_for_width (CAIRO_FORMAT_ARGB32,
762                                                 rect->width);
763         return stride * rect->height;
764 }
765
766 static cairo_surface_t *
767 display_create_shm_surface_from_pool(struct display *display,
768                                      struct rectangle *rectangle,
769                                      uint32_t flags, struct shm_pool *pool)
770 {
771         struct shm_surface_data *data;
772         uint32_t format;
773         cairo_surface_t *surface;
774         cairo_format_t cairo_format;
775         int stride, length, offset;
776         void *map;
777
778         data = malloc(sizeof *data);
779         if (data == NULL)
780                 return NULL;
781
782         if (flags & SURFACE_HINT_RGB565 && display->has_rgb565)
783                 cairo_format = CAIRO_FORMAT_RGB16_565;
784         else
785                 cairo_format = CAIRO_FORMAT_ARGB32;
786
787         stride = cairo_format_stride_for_width (cairo_format, rectangle->width);
788         length = stride * rectangle->height;
789         data->pool = NULL;
790         map = shm_pool_allocate(pool, length, &offset);
791
792         if (!map) {
793                 free(data);
794                 return NULL;
795         }
796
797         surface = cairo_image_surface_create_for_data (map,
798                                                        cairo_format,
799                                                        rectangle->width,
800                                                        rectangle->height,
801                                                        stride);
802
803         cairo_surface_set_user_data(surface, &shm_surface_data_key,
804                                     data, shm_surface_data_destroy);
805
806         if (flags & SURFACE_HINT_RGB565 && display->has_rgb565)
807                 format = WL_SHM_FORMAT_RGB565;
808         else {
809                 if (flags & SURFACE_OPAQUE)
810                         format = WL_SHM_FORMAT_XRGB8888;
811                 else
812                         format = WL_SHM_FORMAT_ARGB8888;
813         }
814
815         data->buffer = wl_shm_pool_create_buffer(pool->pool, offset,
816                                                  rectangle->width,
817                                                  rectangle->height,
818                                                  stride, format);
819
820         return surface;
821 }
822
823 static cairo_surface_t *
824 display_create_shm_surface(struct display *display,
825                            struct rectangle *rectangle, uint32_t flags,
826                            struct shm_pool *alternate_pool,
827                            struct shm_surface_data **data_ret)
828 {
829         struct shm_surface_data *data;
830         struct shm_pool *pool;
831         cairo_surface_t *surface;
832
833         if (alternate_pool) {
834                 shm_pool_reset(alternate_pool);
835                 surface = display_create_shm_surface_from_pool(display,
836                                                                rectangle,
837                                                                flags,
838                                                                alternate_pool);
839                 if (surface) {
840                         data = cairo_surface_get_user_data(surface,
841                                                            &shm_surface_data_key);
842                         goto out;
843                 }
844         }
845
846         pool = shm_pool_create(display,
847                                data_length_for_shm_surface(rectangle));
848         if (!pool)
849                 return NULL;
850
851         surface =
852                 display_create_shm_surface_from_pool(display, rectangle,
853                                                      flags, pool);
854
855         if (!surface) {
856                 shm_pool_destroy(pool);
857                 return NULL;
858         }
859
860         /* make sure we destroy the pool when the surface is destroyed */
861         data = cairo_surface_get_user_data(surface, &shm_surface_data_key);
862         data->pool = pool;
863
864 out:
865         if (data_ret)
866                 *data_ret = data;
867
868         return surface;
869 }
870
871 static int
872 check_size(struct rectangle *rect)
873 {
874         if (rect->width && rect->height)
875                 return 0;
876
877         fprintf(stderr, "tried to create surface of "
878                 "width: %d, height: %d\n", rect->width, rect->height);
879         return -1;
880 }
881
882 cairo_surface_t *
883 display_create_surface(struct display *display,
884                        struct wl_surface *surface,
885                        struct rectangle *rectangle,
886                        uint32_t flags)
887 {
888         if (check_size(rectangle) < 0)
889                 return NULL;
890
891         assert(flags & SURFACE_SHM);
892         return display_create_shm_surface(display, rectangle, flags,
893                                           NULL, NULL);
894 }
895
896 struct shm_surface_leaf {
897         cairo_surface_t *cairo_surface;
898         /* 'data' is automatically destroyed, when 'cairo_surface' is */
899         struct shm_surface_data *data;
900
901         struct shm_pool *resize_pool;
902         int busy;
903 };
904
905 static void
906 shm_surface_leaf_release(struct shm_surface_leaf *leaf)
907 {
908         if (leaf->cairo_surface)
909                 cairo_surface_destroy(leaf->cairo_surface);
910         /* leaf->data already destroyed via cairo private */
911
912         if (leaf->resize_pool)
913                 shm_pool_destroy(leaf->resize_pool);
914
915         memset(leaf, 0, sizeof *leaf);
916 }
917
918 #define MAX_LEAVES 3
919
920 struct shm_surface {
921         struct toysurface base;
922         struct display *display;
923         struct wl_surface *surface;
924         uint32_t flags;
925         int dx, dy;
926
927         struct shm_surface_leaf leaf[MAX_LEAVES];
928         struct shm_surface_leaf *current;
929 };
930
931 static struct shm_surface *
932 to_shm_surface(struct toysurface *base)
933 {
934         return container_of(base, struct shm_surface, base);
935 }
936
937 static void
938 shm_surface_buffer_state_debug(struct shm_surface *surface, const char *msg)
939 {
940 #ifdef DEBUG
941         struct shm_surface_leaf *leaf;
942         char bufs[MAX_LEAVES + 1];
943         int i;
944
945         for (i = 0; i < MAX_LEAVES; i++) {
946                 leaf = &surface->leaf[i];
947
948                 if (leaf->busy)
949                         bufs[i] = 'b';
950                 else if (leaf->cairo_surface)
951                         bufs[i] = 'a';
952                 else
953                         bufs[i] = ' ';
954         }
955
956         bufs[MAX_LEAVES] = '\0';
957         DBG_OBJ(surface->surface, "%s, leaves [%s]\n", msg, bufs);
958 #endif
959 }
960
961 static void
962 shm_surface_buffer_release(void *data, struct wl_buffer *buffer)
963 {
964         struct shm_surface *surface = data;
965         struct shm_surface_leaf *leaf;
966         int i;
967         int free_found;
968
969         shm_surface_buffer_state_debug(surface, "buffer_release before");
970
971         for (i = 0; i < MAX_LEAVES; i++) {
972                 leaf = &surface->leaf[i];
973                 if (leaf->data && leaf->data->buffer == buffer) {
974                         leaf->busy = 0;
975                         break;
976                 }
977         }
978         assert(i < MAX_LEAVES && "unknown buffer released");
979
980         /* Leave one free leaf with storage, release others */
981         free_found = 0;
982         for (i = 0; i < MAX_LEAVES; i++) {
983                 leaf = &surface->leaf[i];
984
985                 if (!leaf->cairo_surface || leaf->busy)
986                         continue;
987
988                 if (!free_found)
989                         free_found = 1;
990                 else
991                         shm_surface_leaf_release(leaf);
992         }
993
994         shm_surface_buffer_state_debug(surface, "buffer_release  after");
995 }
996
997 static const struct wl_buffer_listener shm_surface_buffer_listener = {
998         shm_surface_buffer_release
999 };
1000
1001 static cairo_surface_t *
1002 shm_surface_prepare(struct toysurface *base, int dx, int dy,
1003                     int32_t width, int32_t height, uint32_t flags,
1004                     enum wl_output_transform buffer_transform, int32_t buffer_scale)
1005 {
1006         int resize_hint = !!(flags & SURFACE_HINT_RESIZE);
1007         struct shm_surface *surface = to_shm_surface(base);
1008         struct rectangle rect = { 0};
1009         struct shm_surface_leaf *leaf = NULL;
1010         int i;
1011
1012         surface->dx = dx;
1013         surface->dy = dy;
1014
1015         /* pick a free buffer, preferrably one that already has storage */
1016         for (i = 0; i < MAX_LEAVES; i++) {
1017                 if (surface->leaf[i].busy)
1018                         continue;
1019
1020                 if (!leaf || surface->leaf[i].cairo_surface)
1021                         leaf = &surface->leaf[i];
1022         }
1023         DBG_OBJ(surface->surface, "pick leaf %d\n",
1024                 (int)(leaf - &surface->leaf[0]));
1025
1026         if (!leaf) {
1027                 fprintf(stderr, "%s: all buffers are held by the server.\n",
1028                         __func__);
1029                 exit(1);
1030                 return NULL;
1031         }
1032
1033         if (!resize_hint && leaf->resize_pool) {
1034                 cairo_surface_destroy(leaf->cairo_surface);
1035                 leaf->cairo_surface = NULL;
1036                 shm_pool_destroy(leaf->resize_pool);
1037                 leaf->resize_pool = NULL;
1038         }
1039
1040         surface_to_buffer_size (buffer_transform, buffer_scale, &width, &height);
1041
1042         if (leaf->cairo_surface &&
1043             cairo_image_surface_get_width(leaf->cairo_surface) == width &&
1044             cairo_image_surface_get_height(leaf->cairo_surface) == height)
1045                 goto out;
1046
1047         if (leaf->cairo_surface)
1048                 cairo_surface_destroy(leaf->cairo_surface);
1049
1050 #ifdef USE_RESIZE_POOL
1051         if (resize_hint && !leaf->resize_pool) {
1052                 /* Create a big pool to allocate from, while continuously
1053                  * resizing. Mmapping a new pool in the server
1054                  * is relatively expensive, so reusing a pool performs
1055                  * better, but may temporarily reserve unneeded memory.
1056                  */
1057                 /* We should probably base this number on the output size. */
1058                 leaf->resize_pool = shm_pool_create(surface->display,
1059                                                     6 * 1024 * 1024);
1060         }
1061 #endif
1062
1063         rect.width = width;
1064         rect.height = height;
1065
1066         leaf->cairo_surface =
1067                 display_create_shm_surface(surface->display, &rect,
1068                                            surface->flags,
1069                                            leaf->resize_pool,
1070                                            &leaf->data);
1071         if (!leaf->cairo_surface)
1072                 return NULL;
1073
1074         wl_buffer_add_listener(leaf->data->buffer,
1075                                &shm_surface_buffer_listener, surface);
1076
1077 out:
1078         surface->current = leaf;
1079
1080         return cairo_surface_reference(leaf->cairo_surface);
1081 }
1082
1083 static void
1084 shm_surface_swap(struct toysurface *base,
1085                  enum wl_output_transform buffer_transform, int32_t buffer_scale,
1086                  struct rectangle *server_allocation)
1087 {
1088         struct shm_surface *surface = to_shm_surface(base);
1089         struct shm_surface_leaf *leaf = surface->current;
1090
1091         server_allocation->width =
1092                 cairo_image_surface_get_width(leaf->cairo_surface);
1093         server_allocation->height =
1094                 cairo_image_surface_get_height(leaf->cairo_surface);
1095
1096         buffer_to_surface_size (buffer_transform, buffer_scale,
1097                                 &server_allocation->width,
1098                                 &server_allocation->height);
1099
1100         wl_surface_attach(surface->surface, leaf->data->buffer,
1101                           surface->dx, surface->dy);
1102         wl_surface_damage(surface->surface, 0, 0,
1103                           server_allocation->width, server_allocation->height);
1104         wl_surface_commit(surface->surface);
1105
1106         DBG_OBJ(surface->surface, "leaf %d busy\n",
1107                 (int)(leaf - &surface->leaf[0]));
1108
1109         leaf->busy = 1;
1110         surface->current = NULL;
1111 }
1112
1113 static int
1114 shm_surface_acquire(struct toysurface *base, EGLContext ctx)
1115 {
1116         return -1;
1117 }
1118
1119 static void
1120 shm_surface_release(struct toysurface *base)
1121 {
1122 }
1123
1124 static void
1125 shm_surface_destroy(struct toysurface *base)
1126 {
1127         struct shm_surface *surface = to_shm_surface(base);
1128         int i;
1129
1130         for (i = 0; i < MAX_LEAVES; i++)
1131                 shm_surface_leaf_release(&surface->leaf[i]);
1132
1133         free(surface);
1134 }
1135
1136 static struct toysurface *
1137 shm_surface_create(struct display *display, struct wl_surface *wl_surface,
1138                    uint32_t flags, struct rectangle *rectangle)
1139 {
1140         struct shm_surface *surface;
1141         DBG_OBJ(wl_surface, "\n");
1142
1143         surface = xmalloc(sizeof *surface);
1144         memset(surface, 0, sizeof *surface);
1145
1146         if (!surface)
1147                 return NULL;
1148
1149         surface->base.prepare = shm_surface_prepare;
1150         surface->base.swap = shm_surface_swap;
1151         surface->base.acquire = shm_surface_acquire;
1152         surface->base.release = shm_surface_release;
1153         surface->base.destroy = shm_surface_destroy;
1154
1155         surface->display = display;
1156         surface->surface = wl_surface;
1157         surface->flags = flags;
1158
1159         return &surface->base;
1160 }
1161
1162 /*
1163  * The following correspondences between file names and cursors was copied
1164  * from: https://bugs.kde.org/attachment.cgi?id=67313
1165  */
1166
1167 static const char *bottom_left_corners[] = {
1168         "bottom_left_corner",
1169         "sw-resize",
1170         "size_bdiag"
1171 };
1172
1173 static const char *bottom_right_corners[] = {
1174         "bottom_right_corner",
1175         "se-resize",
1176         "size_fdiag"
1177 };
1178
1179 static const char *bottom_sides[] = {
1180         "bottom_side",
1181         "s-resize",
1182         "size_ver"
1183 };
1184
1185 static const char *grabbings[] = {
1186         "grabbing",
1187         "closedhand",
1188         "208530c400c041818281048008011002"
1189 };
1190
1191 static const char *left_ptrs[] = {
1192         "left_ptr",
1193         "default",
1194         "top_left_arrow",
1195         "left-arrow"
1196 };
1197
1198 static const char *left_sides[] = {
1199         "left_side",
1200         "w-resize",
1201         "size_hor"
1202 };
1203
1204 static const char *right_sides[] = {
1205         "right_side",
1206         "e-resize",
1207         "size_hor"
1208 };
1209
1210 static const char *top_left_corners[] = {
1211         "top_left_corner",
1212         "nw-resize",
1213         "size_fdiag"
1214 };
1215
1216 static const char *top_right_corners[] = {
1217         "top_right_corner",
1218         "ne-resize",
1219         "size_bdiag"
1220 };
1221
1222 static const char *top_sides[] = {
1223         "top_side",
1224         "n-resize",
1225         "size_ver"
1226 };
1227
1228 static const char *xterms[] = {
1229         "xterm",
1230         "ibeam",
1231         "text"
1232 };
1233
1234 static const char *hand1s[] = {
1235         "hand1",
1236         "pointer",
1237         "pointing_hand",
1238         "e29285e634086352946a0e7090d73106"
1239 };
1240
1241 static const char *watches[] = {
1242         "watch",
1243         "wait",
1244         "0426c94ea35c87780ff01dc239897213"
1245 };
1246
1247 struct cursor_alternatives {
1248         const char **names;
1249         size_t count;
1250 };
1251
1252 static const struct cursor_alternatives cursors[] = {
1253         {bottom_left_corners, ARRAY_LENGTH(bottom_left_corners)},
1254         {bottom_right_corners, ARRAY_LENGTH(bottom_right_corners)},
1255         {bottom_sides, ARRAY_LENGTH(bottom_sides)},
1256         {grabbings, ARRAY_LENGTH(grabbings)},
1257         {left_ptrs, ARRAY_LENGTH(left_ptrs)},
1258         {left_sides, ARRAY_LENGTH(left_sides)},
1259         {right_sides, ARRAY_LENGTH(right_sides)},
1260         {top_left_corners, ARRAY_LENGTH(top_left_corners)},
1261         {top_right_corners, ARRAY_LENGTH(top_right_corners)},
1262         {top_sides, ARRAY_LENGTH(top_sides)},
1263         {xterms, ARRAY_LENGTH(xterms)},
1264         {hand1s, ARRAY_LENGTH(hand1s)},
1265         {watches, ARRAY_LENGTH(watches)},
1266 };
1267
1268 static void
1269 create_cursors(struct display *display)
1270 {
1271         struct weston_config *config;
1272         struct weston_config_section *s;
1273         int size;
1274         char *theme = NULL;
1275         unsigned int i, j;
1276         struct wl_cursor *cursor;
1277
1278         config = weston_config_parse("weston.ini");
1279         s = weston_config_get_section(config, "shell", NULL, NULL);
1280         weston_config_section_get_string(s, "cursor-theme", &theme, NULL);
1281         weston_config_section_get_int(s, "cursor-size", &size, 32);
1282         weston_config_destroy(config);
1283
1284         display->cursor_theme = wl_cursor_theme_load(theme, size, display->shm);
1285         if (!display->cursor_theme) {
1286                 fprintf(stderr, "could not load theme '%s'\n", theme);
1287                 return;
1288         }
1289         free(theme);
1290         display->cursors =
1291                 xmalloc(ARRAY_LENGTH(cursors) * sizeof display->cursors[0]);
1292
1293         for (i = 0; i < ARRAY_LENGTH(cursors); i++) {
1294                 cursor = NULL;
1295                 for (j = 0; !cursor && j < cursors[i].count; ++j)
1296                         cursor = wl_cursor_theme_get_cursor(
1297                             display->cursor_theme, cursors[i].names[j]);
1298
1299                 if (!cursor)
1300                         fprintf(stderr, "could not load cursor '%s'\n",
1301                                 cursors[i].names[0]);
1302
1303                 display->cursors[i] = cursor;
1304         }
1305 }
1306
1307 static void
1308 destroy_cursors(struct display *display)
1309 {
1310         wl_cursor_theme_destroy(display->cursor_theme);
1311         free(display->cursors);
1312 }
1313
1314 struct wl_cursor_image *
1315 display_get_pointer_image(struct display *display, int pointer)
1316 {
1317         struct wl_cursor *cursor = display->cursors[pointer];
1318
1319         return cursor ? cursor->images[0] : NULL;
1320 }
1321
1322 static void
1323 surface_flush(struct surface *surface)
1324 {
1325         if (!surface->cairo_surface)
1326                 return;
1327
1328         if (surface->opaque_region) {
1329                 wl_surface_set_opaque_region(surface->surface,
1330                                              surface->opaque_region);
1331                 wl_region_destroy(surface->opaque_region);
1332                 surface->opaque_region = NULL;
1333         }
1334
1335         if (surface->input_region) {
1336                 wl_surface_set_input_region(surface->surface,
1337                                             surface->input_region);
1338                 wl_region_destroy(surface->input_region);
1339                 surface->input_region = NULL;
1340         }
1341
1342         surface->toysurface->swap(surface->toysurface,
1343                                   surface->buffer_transform, surface->buffer_scale,
1344                                   &surface->server_allocation);
1345
1346         cairo_surface_destroy(surface->cairo_surface);
1347         surface->cairo_surface = NULL;
1348 }
1349
1350 int
1351 window_has_focus(struct window *window)
1352 {
1353         return window->focused;
1354 }
1355
1356 static void
1357 window_close(struct window *window)
1358 {
1359         if (window->close_handler)
1360                 window->close_handler(window->user_data);
1361         else
1362                 display_exit(window->display);
1363 }
1364
1365 struct display *
1366 window_get_display(struct window *window)
1367 {
1368         return window->display;
1369 }
1370
1371 static void
1372 surface_create_surface(struct surface *surface, uint32_t flags)
1373 {
1374         struct display *display = surface->window->display;
1375         struct rectangle allocation = surface->allocation;
1376
1377         if (!surface->toysurface && display->dpy &&
1378             surface->buffer_type == WINDOW_BUFFER_TYPE_EGL_WINDOW) {
1379                 surface->toysurface =
1380                         egl_window_surface_create(display,
1381                                                   surface->surface,
1382                                                   flags,
1383                                                   &allocation);
1384         }
1385
1386         if (!surface->toysurface)
1387                 surface->toysurface = shm_surface_create(display,
1388                                                          surface->surface,
1389                                                          flags, &allocation);
1390
1391         surface->cairo_surface = surface->toysurface->prepare(
1392                 surface->toysurface, 0, 0,
1393                 allocation.width, allocation.height, flags,
1394                 surface->buffer_transform, surface->buffer_scale);
1395 }
1396
1397 static void
1398 window_create_main_surface(struct window *window)
1399 {
1400         struct surface *surface = window->main_surface;
1401         uint32_t flags = 0;
1402
1403         if (window->resizing)
1404                 flags |= SURFACE_HINT_RESIZE;
1405
1406         if (window->preferred_format == WINDOW_PREFERRED_FORMAT_RGB565)
1407                 flags |= SURFACE_HINT_RGB565;
1408
1409         surface_create_surface(surface, flags);
1410 }
1411
1412 int
1413 window_get_buffer_transform(struct window *window)
1414 {
1415         return window->main_surface->buffer_transform;
1416 }
1417
1418 void
1419 window_set_buffer_transform(struct window *window,
1420                             enum wl_output_transform transform)
1421 {
1422         window->main_surface->buffer_transform = transform;
1423         wl_surface_set_buffer_transform(window->main_surface->surface,
1424                                         transform);
1425 }
1426
1427 void
1428 window_set_buffer_scale(struct window *window,
1429                         int32_t scale)
1430 {
1431         window->main_surface->buffer_scale = scale;
1432         wl_surface_set_buffer_scale(window->main_surface->surface,
1433                                     scale);
1434 }
1435
1436 uint32_t
1437 window_get_buffer_scale(struct window *window)
1438 {
1439         return window->main_surface->buffer_scale;
1440 }
1441
1442 uint32_t
1443 window_get_output_scale(struct window *window)
1444 {
1445         struct window_output *window_output;
1446         struct window_output *window_output_tmp;
1447         int scale = 1;
1448
1449         wl_list_for_each_safe(window_output, window_output_tmp,
1450                               &window->window_output_list, link) {
1451                 if (window_output->output->scale > scale)
1452                         scale = window_output->output->scale;
1453         }
1454
1455         return scale;
1456 }
1457
1458 static void window_frame_destroy(struct window_frame *frame);
1459
1460 static void
1461 surface_destroy(struct surface *surface)
1462 {
1463         if (surface->frame_cb)
1464                 wl_callback_destroy(surface->frame_cb);
1465
1466         if (surface->input_region)
1467                 wl_region_destroy(surface->input_region);
1468
1469         if (surface->opaque_region)
1470                 wl_region_destroy(surface->opaque_region);
1471
1472         if (surface->subsurface)
1473                 wl_subsurface_destroy(surface->subsurface);
1474
1475         wl_surface_destroy(surface->surface);
1476
1477         if (surface->toysurface)
1478                 surface->toysurface->destroy(surface->toysurface);
1479
1480         wl_list_remove(&surface->link);
1481         free(surface);
1482 }
1483
1484 void
1485 window_destroy(struct window *window)
1486 {
1487         struct display *display = window->display;
1488         struct input *input;
1489         struct window_output *window_output;
1490         struct window_output *window_output_tmp;
1491
1492         wl_list_remove(&window->redraw_task.link);
1493
1494         wl_list_for_each(input, &display->input_list, link) {     
1495                 if (input->touch_focus == window)
1496                         input->touch_focus = NULL;
1497                 if (input->pointer_focus == window)
1498                         input->pointer_focus = NULL;
1499                 if (input->keyboard_focus == window)
1500                         input->keyboard_focus = NULL;
1501                 if (input->focus_widget &&
1502                     input->focus_widget->window == window)
1503                         input->focus_widget = NULL;
1504         }
1505
1506         wl_list_for_each_safe(window_output, window_output_tmp,
1507                               &window->window_output_list, link) {
1508                 free (window_output);
1509         }
1510
1511         if (window->frame)
1512                 window_frame_destroy(window->frame);
1513
1514         if (window->xdg_surface)
1515                 xdg_surface_destroy(window->xdg_surface);
1516         if (window->xdg_popup)
1517                 xdg_popup_destroy(window->xdg_popup);
1518
1519         surface_destroy(window->main_surface);
1520
1521         wl_list_remove(&window->link);
1522
1523         free(window->title);
1524         free(window);
1525 }
1526
1527 static struct widget *
1528 widget_find_widget(struct widget *widget, int32_t x, int32_t y)
1529 {
1530         struct widget *child, *target;
1531
1532         wl_list_for_each(child, &widget->child_list, link) {
1533                 target = widget_find_widget(child, x, y);
1534                 if (target)
1535                         return target;
1536         }
1537
1538         if (widget->allocation.x <= x &&
1539             x < widget->allocation.x + widget->allocation.width &&
1540             widget->allocation.y <= y &&
1541             y < widget->allocation.y + widget->allocation.height) {
1542                 return widget;
1543         }
1544
1545         return NULL;
1546 }
1547
1548 static struct widget *
1549 window_find_widget(struct window *window, int32_t x, int32_t y)
1550 {
1551         struct surface *surface;
1552         struct widget *widget;
1553
1554         wl_list_for_each(surface, &window->subsurface_list, link) {
1555                 widget = widget_find_widget(surface->widget, x, y);
1556                 if (widget)
1557                         return widget;
1558         }
1559
1560         return NULL;
1561 }
1562
1563 static struct widget *
1564 widget_create(struct window *window, struct surface *surface, void *data)
1565 {
1566         struct widget *widget;
1567
1568         widget = xzalloc(sizeof *widget);
1569         widget->window = window;
1570         widget->surface = surface;
1571         widget->user_data = data;
1572         widget->allocation = surface->allocation;
1573         wl_list_init(&widget->child_list);
1574         widget->opaque = 0;
1575         widget->tooltip = NULL;
1576         widget->tooltip_count = 0;
1577         widget->default_cursor = CURSOR_LEFT_PTR;
1578         widget->use_cairo = 1;
1579
1580         return widget;
1581 }
1582
1583 struct widget *
1584 window_add_widget(struct window *window, void *data)
1585 {
1586         struct widget *widget;
1587
1588         widget = widget_create(window, window->main_surface, data);
1589         wl_list_init(&widget->link);
1590         window->main_surface->widget = widget;
1591
1592         return widget;
1593 }
1594
1595 struct widget *
1596 widget_add_widget(struct widget *parent, void *data)
1597 {
1598         struct widget *widget;
1599
1600         widget = widget_create(parent->window, parent->surface, data);
1601         wl_list_insert(parent->child_list.prev, &widget->link);
1602
1603         return widget;
1604 }
1605
1606 void
1607 widget_destroy(struct widget *widget)
1608 {
1609         struct display *display = widget->window->display;
1610         struct surface *surface = widget->surface;
1611         struct input *input;
1612
1613         /* Destroy the sub-surface along with the root widget */
1614         if (surface->widget == widget && surface->subsurface)
1615                 surface_destroy(widget->surface);
1616
1617         if (widget->tooltip)
1618                 widget_destroy_tooltip(widget);
1619
1620         wl_list_for_each(input, &display->input_list, link) {
1621                 if (input->focus_widget == widget)
1622                         input->focus_widget = NULL;
1623         }
1624
1625         wl_list_remove(&widget->link);
1626         free(widget);
1627 }
1628
1629 void
1630 widget_set_default_cursor(struct widget *widget, int cursor)
1631 {
1632         widget->default_cursor = cursor;
1633 }
1634
1635 void
1636 widget_get_allocation(struct widget *widget, struct rectangle *allocation)
1637 {
1638         *allocation = widget->allocation;
1639 }
1640
1641 void
1642 widget_set_size(struct widget *widget, int32_t width, int32_t height)
1643 {
1644         widget->allocation.width = width;
1645         widget->allocation.height = height;
1646 }
1647
1648 void
1649 widget_set_allocation(struct widget *widget,
1650                       int32_t x, int32_t y, int32_t width, int32_t height)
1651 {
1652         widget->allocation.x = x;
1653         widget->allocation.y = y;
1654         widget_set_size(widget, width, height);
1655 }
1656
1657 void
1658 widget_set_transparent(struct widget *widget, int transparent)
1659 {
1660         widget->opaque = !transparent;
1661 }
1662
1663 void *
1664 widget_get_user_data(struct widget *widget)
1665 {
1666         return widget->user_data;
1667 }
1668
1669 static cairo_surface_t *
1670 widget_get_cairo_surface(struct widget *widget)
1671 {
1672         struct surface *surface = widget->surface;
1673         struct window *window = widget->window;
1674
1675         assert(widget->use_cairo);
1676
1677         if (!surface->cairo_surface) {
1678                 if (surface == window->main_surface)
1679                         window_create_main_surface(window);
1680                 else
1681                         surface_create_surface(surface, 0);
1682         }
1683
1684         return surface->cairo_surface;
1685 }
1686
1687 static void
1688 widget_cairo_update_transform(struct widget *widget, cairo_t *cr)
1689 {
1690         struct surface *surface = widget->surface;
1691         double angle;
1692         cairo_matrix_t m;
1693         enum wl_output_transform transform;
1694         int surface_width, surface_height;
1695         int translate_x, translate_y;
1696         int32_t scale;
1697
1698         surface_width = surface->allocation.width;
1699         surface_height = surface->allocation.height;
1700
1701         transform = surface->buffer_transform;
1702         scale = surface->buffer_scale;
1703
1704         switch (transform) {
1705         case WL_OUTPUT_TRANSFORM_FLIPPED:
1706         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
1707         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
1708         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
1709                 cairo_matrix_init(&m, -1, 0, 0, 1, 0, 0);
1710                 break;
1711         default:
1712                 cairo_matrix_init_identity(&m);
1713                 break;
1714         }
1715
1716         switch (transform) {
1717         case WL_OUTPUT_TRANSFORM_NORMAL:
1718         default:
1719                 angle = 0;
1720                 translate_x = 0;
1721                 translate_y = 0;
1722                 break;
1723         case WL_OUTPUT_TRANSFORM_FLIPPED:
1724                 angle = 0;
1725                 translate_x = surface_width;
1726                 translate_y = 0;
1727                 break;
1728         case WL_OUTPUT_TRANSFORM_90:
1729                 angle = M_PI_2;
1730                 translate_x = surface_height;
1731                 translate_y = 0;
1732                 break;
1733         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
1734                 angle = M_PI_2;
1735                 translate_x = surface_height;
1736                 translate_y = surface_width;
1737                 break;
1738         case WL_OUTPUT_TRANSFORM_180:
1739                 angle = M_PI;
1740                 translate_x = surface_width;
1741                 translate_y = surface_height;
1742                 break;
1743         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
1744                 angle = M_PI;
1745                 translate_x = 0;
1746                 translate_y = surface_height;
1747                 break;
1748         case WL_OUTPUT_TRANSFORM_270:
1749                 angle = M_PI + M_PI_2;
1750                 translate_x = 0;
1751                 translate_y = surface_width;
1752                 break;
1753         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
1754                 angle = M_PI + M_PI_2;
1755                 translate_x = 0;
1756                 translate_y = 0;
1757                 break;
1758         }
1759
1760         cairo_scale(cr, scale, scale);
1761         cairo_translate(cr, translate_x, translate_y);
1762         cairo_rotate(cr, angle);
1763         cairo_transform(cr, &m);
1764 }
1765
1766 cairo_t *
1767 widget_cairo_create(struct widget *widget)
1768 {
1769         struct surface *surface = widget->surface;
1770         cairo_surface_t *cairo_surface;
1771         cairo_t *cr;
1772
1773         cairo_surface = widget_get_cairo_surface(widget);
1774         cr = cairo_create(cairo_surface);
1775
1776         widget_cairo_update_transform(widget, cr);
1777
1778         cairo_translate(cr, -surface->allocation.x, -surface->allocation.y);
1779
1780         return cr;
1781 }
1782
1783 struct wl_surface *
1784 widget_get_wl_surface(struct widget *widget)
1785 {
1786         return widget->surface->surface;
1787 }
1788
1789 struct wl_subsurface *
1790 widget_get_wl_subsurface(struct widget *widget)
1791 {
1792         return widget->surface->subsurface;
1793 }
1794
1795 uint32_t
1796 widget_get_last_time(struct widget *widget)
1797 {
1798         return widget->surface->last_time;
1799 }
1800
1801 void
1802 widget_input_region_add(struct widget *widget, const struct rectangle *rect)
1803 {
1804         struct wl_compositor *comp = widget->window->display->compositor;
1805         struct surface *surface = widget->surface;
1806
1807         if (!surface->input_region)
1808                 surface->input_region = wl_compositor_create_region(comp);
1809
1810         if (rect) {
1811                 wl_region_add(surface->input_region,
1812                               rect->x, rect->y, rect->width, rect->height);
1813         }
1814 }
1815
1816 void
1817 widget_set_resize_handler(struct widget *widget,
1818                           widget_resize_handler_t handler)
1819 {
1820         widget->resize_handler = handler;
1821 }
1822
1823 void
1824 widget_set_redraw_handler(struct widget *widget,
1825                           widget_redraw_handler_t handler)
1826 {
1827         widget->redraw_handler = handler;
1828 }
1829
1830 void
1831 widget_set_enter_handler(struct widget *widget, widget_enter_handler_t handler)
1832 {
1833         widget->enter_handler = handler;
1834 }
1835
1836 void
1837 widget_set_leave_handler(struct widget *widget, widget_leave_handler_t handler)
1838 {
1839         widget->leave_handler = handler;
1840 }
1841
1842 void
1843 widget_set_motion_handler(struct widget *widget,
1844                           widget_motion_handler_t handler)
1845 {
1846         widget->motion_handler = handler;
1847 }
1848
1849 void
1850 widget_set_button_handler(struct widget *widget,
1851                           widget_button_handler_t handler)
1852 {
1853         widget->button_handler = handler;
1854 }
1855
1856 void
1857 widget_set_touch_up_handler(struct widget *widget,
1858                             widget_touch_up_handler_t handler)
1859 {
1860         widget->touch_up_handler = handler;
1861 }
1862
1863 void
1864 widget_set_touch_down_handler(struct widget *widget,
1865                               widget_touch_down_handler_t handler)
1866 {
1867         widget->touch_down_handler = handler;
1868 }
1869
1870 void
1871 widget_set_touch_motion_handler(struct widget *widget,
1872                                 widget_touch_motion_handler_t handler)
1873 {
1874         widget->touch_motion_handler = handler;
1875 }
1876
1877 void
1878 widget_set_touch_frame_handler(struct widget *widget,
1879                                widget_touch_frame_handler_t handler)
1880 {
1881         widget->touch_frame_handler = handler;
1882 }
1883
1884 void
1885 widget_set_touch_cancel_handler(struct widget *widget,
1886                                 widget_touch_cancel_handler_t handler)
1887 {
1888         widget->touch_cancel_handler = handler;
1889 }
1890
1891 void
1892 widget_set_axis_handler(struct widget *widget,
1893                         widget_axis_handler_t handler)
1894 {
1895         widget->axis_handler = handler;
1896 }
1897
1898 static void
1899 window_schedule_redraw_task(struct window *window);
1900
1901 void
1902 widget_schedule_redraw(struct widget *widget)
1903 {
1904         DBG_OBJ(widget->surface->surface, "widget %p\n", widget);
1905         widget->surface->redraw_needed = 1;
1906         window_schedule_redraw_task(widget->window);
1907 }
1908
1909 void
1910 widget_set_use_cairo(struct widget *widget,
1911                      int use_cairo)
1912 {
1913         widget->use_cairo = use_cairo;
1914 }
1915
1916 cairo_surface_t *
1917 window_get_surface(struct window *window)
1918 {
1919         cairo_surface_t *cairo_surface;
1920
1921         cairo_surface = widget_get_cairo_surface(window->main_surface->widget);
1922
1923         return cairo_surface_reference(cairo_surface);
1924 }
1925
1926 struct wl_surface *
1927 window_get_wl_surface(struct window *window)
1928 {
1929         return window->main_surface->surface;
1930 }
1931
1932 static void
1933 tooltip_redraw_handler(struct widget *widget, void *data)
1934 {
1935         cairo_t *cr;
1936         const int32_t r = 3;
1937         struct tooltip *tooltip = data;
1938         int32_t width, height;
1939
1940         cr = widget_cairo_create(widget);
1941         cairo_translate(cr, widget->allocation.x, widget->allocation.y);
1942         cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
1943         cairo_set_source_rgba(cr, 0.0, 0.0, 0.0, 0.0);
1944         cairo_paint(cr);
1945
1946         width = widget->allocation.width;
1947         height = widget->allocation.height;
1948         rounded_rect(cr, 0, 0, width, height, r);
1949
1950         cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
1951         cairo_set_source_rgba(cr, 0.0, 0.0, 0.4, 0.8);
1952         cairo_fill(cr);
1953
1954         cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
1955         cairo_move_to(cr, 10, 16);
1956         cairo_show_text(cr, tooltip->entry);
1957         cairo_destroy(cr);
1958 }
1959
1960 static cairo_text_extents_t
1961 get_text_extents(struct display *display, struct tooltip *tooltip)
1962 {
1963         cairo_t *cr;
1964         cairo_text_extents_t extents;
1965
1966         /* Use the dummy_surface because tooltip's surface was not
1967          * created yet, and parent does not have a valid surface
1968          * outside repaint, either.
1969          */
1970         cr = cairo_create(display->dummy_surface);
1971         cairo_text_extents(cr, tooltip->entry, &extents);
1972         cairo_destroy(cr);
1973
1974         return extents;
1975 }
1976
1977 static int
1978 window_create_tooltip(struct tooltip *tooltip)
1979 {
1980         struct widget *parent = tooltip->parent;
1981         struct display *display = parent->window->display;
1982         const int offset_y = 27;
1983         const int margin = 3;
1984         cairo_text_extents_t extents;
1985
1986         if (tooltip->widget)
1987                 return 0;
1988
1989         tooltip->widget = window_add_subsurface(parent->window, tooltip, SUBSURFACE_DESYNCHRONIZED);
1990
1991         extents = get_text_extents(display, tooltip);
1992         widget_set_redraw_handler(tooltip->widget, tooltip_redraw_handler);
1993         widget_set_allocation(tooltip->widget,
1994                               tooltip->x, tooltip->y + offset_y,
1995                               extents.width + 20, 20 + margin * 2);
1996
1997         return 0;
1998 }
1999
2000 void
2001 widget_destroy_tooltip(struct widget *parent)
2002 {
2003         struct tooltip *tooltip = parent->tooltip;
2004
2005         parent->tooltip_count = 0;
2006         if (!tooltip)
2007                 return;
2008
2009         if (tooltip->widget) {
2010                 widget_destroy(tooltip->widget);
2011                 tooltip->widget = NULL;
2012         }
2013
2014         close(tooltip->tooltip_fd);
2015         free(tooltip->entry);
2016         free(tooltip);
2017         parent->tooltip = NULL;
2018 }
2019
2020 static void
2021 tooltip_func(struct task *task, uint32_t events)
2022 {
2023         struct tooltip *tooltip =
2024                 container_of(task, struct tooltip, tooltip_task);
2025         uint64_t exp;
2026
2027         if (read(tooltip->tooltip_fd, &exp, sizeof (uint64_t)) != sizeof (uint64_t))
2028                 abort();
2029         window_create_tooltip(tooltip);
2030 }
2031
2032 #define TOOLTIP_TIMEOUT 500
2033 static int
2034 tooltip_timer_reset(struct tooltip *tooltip)
2035 {
2036         struct itimerspec its;
2037
2038         its.it_interval.tv_sec = 0;
2039         its.it_interval.tv_nsec = 0;
2040         its.it_value.tv_sec = TOOLTIP_TIMEOUT / 1000;
2041         its.it_value.tv_nsec = (TOOLTIP_TIMEOUT % 1000) * 1000 * 1000;
2042         if (timerfd_settime(tooltip->tooltip_fd, 0, &its, NULL) < 0) {
2043                 fprintf(stderr, "could not set timerfd\n: %m");
2044                 return -1;
2045         }
2046
2047         return 0;
2048 }
2049
2050 int
2051 widget_set_tooltip(struct widget *parent, char *entry, float x, float y)
2052 {
2053         struct tooltip *tooltip = parent->tooltip;
2054
2055         parent->tooltip_count++;
2056         if (tooltip) {
2057                 tooltip->x = x;
2058                 tooltip->y = y;
2059                 tooltip_timer_reset(tooltip);
2060                 return 0;
2061         }
2062
2063         /* the handler might be triggered too fast via input device motion, so
2064          * we need this check here to make sure tooltip is fully initialized */
2065         if (parent->tooltip_count > 1)
2066                 return 0;
2067
2068         tooltip = malloc(sizeof *tooltip);
2069         if (!tooltip)
2070                 return -1;
2071
2072         parent->tooltip = tooltip;
2073         tooltip->parent = parent;
2074         tooltip->widget = NULL;
2075         tooltip->x = x;
2076         tooltip->y = y;
2077         tooltip->entry = strdup(entry);
2078         tooltip->tooltip_fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
2079         if (tooltip->tooltip_fd < 0) {
2080                 fprintf(stderr, "could not create timerfd\n: %m");
2081                 return -1;
2082         }
2083
2084         tooltip->tooltip_task.run = tooltip_func;
2085         display_watch_fd(parent->window->display, tooltip->tooltip_fd,
2086                          EPOLLIN, &tooltip->tooltip_task);
2087         tooltip_timer_reset(tooltip);
2088
2089         return 0;
2090 }
2091
2092 static void
2093 workspace_manager_state(void *data,
2094                         struct workspace_manager *workspace_manager,
2095                         uint32_t current,
2096                         uint32_t count)
2097 {
2098         struct display *display = data;
2099
2100         display->workspace = current;
2101         display->workspace_count = count;
2102 }
2103
2104 static const struct workspace_manager_listener workspace_manager_listener = {
2105         workspace_manager_state
2106 };
2107
2108 static void
2109 frame_resize_handler(struct widget *widget,
2110                      int32_t width, int32_t height, void *data)
2111 {
2112         struct window_frame *frame = data;
2113         struct widget *child = frame->child;
2114         struct rectangle interior;
2115         struct rectangle input;
2116         struct rectangle opaque;
2117
2118         if (widget->window->fullscreen) {
2119                 interior.x = 0;
2120                 interior.y = 0;
2121                 interior.width = width;
2122                 interior.height = height;
2123         } else {
2124                 frame_resize(frame->frame, width, height);
2125                 frame_interior(frame->frame, &interior.x, &interior.y,
2126                                &interior.width, &interior.height);
2127         }
2128
2129         widget_set_allocation(child, interior.x, interior.y,
2130                               interior.width, interior.height);
2131
2132         if (child->resize_handler) {
2133                 child->resize_handler(child, interior.width, interior.height,
2134                                       child->user_data);
2135
2136                 if (widget->window->fullscreen) {
2137                         width = child->allocation.width;
2138                         height = child->allocation.height;
2139                 } else {
2140                         frame_resize_inside(frame->frame,
2141                                             child->allocation.width,
2142                                             child->allocation.height);
2143                         width = frame_width(frame->frame);
2144                         height = frame_height(frame->frame);
2145                 }
2146         }
2147
2148         widget_set_allocation(widget, 0, 0, width, height);
2149
2150         widget->surface->input_region =
2151                 wl_compositor_create_region(widget->window->display->compositor);
2152         if (!widget->window->fullscreen) {
2153                 frame_input_rect(frame->frame, &input.x, &input.y,
2154                                  &input.width, &input.height);
2155                 wl_region_add(widget->surface->input_region,
2156                               input.x, input.y, input.width, input.height);
2157         } else {
2158                 wl_region_add(widget->surface->input_region, 0, 0, width, height);
2159         }
2160
2161         widget_set_allocation(widget, 0, 0, width, height);
2162
2163         if (child->opaque) {
2164                 if (!widget->window->fullscreen) {
2165                         frame_opaque_rect(frame->frame, &opaque.x, &opaque.y,
2166                                           &opaque.width, &opaque.height);
2167
2168                         wl_region_add(widget->surface->opaque_region,
2169                                       opaque.x, opaque.y,
2170                                       opaque.width, opaque.height);
2171                 } else {
2172                         wl_region_add(widget->surface->opaque_region,
2173                                       0, 0, width, height);
2174                 }
2175         }
2176
2177
2178         widget_schedule_redraw(widget);
2179 }
2180
2181 static void
2182 frame_redraw_handler(struct widget *widget, void *data)
2183 {
2184         cairo_t *cr;
2185         struct window_frame *frame = data;
2186         struct window *window = widget->window;
2187
2188         if (window->fullscreen)
2189                 return;
2190
2191         cr = widget_cairo_create(widget);
2192
2193         frame_repaint(frame->frame, cr);
2194
2195         cairo_destroy(cr);
2196 }
2197
2198 static int
2199 frame_get_pointer_image_for_location(struct window_frame *frame,
2200                                      enum theme_location location)
2201 {
2202         struct window *window = frame->widget->window;
2203
2204         if (window->custom)
2205                 return CURSOR_LEFT_PTR;
2206
2207         switch (location) {
2208         case THEME_LOCATION_RESIZING_TOP:
2209                 return CURSOR_TOP;
2210         case THEME_LOCATION_RESIZING_BOTTOM:
2211                 return CURSOR_BOTTOM;
2212         case THEME_LOCATION_RESIZING_LEFT:
2213                 return CURSOR_LEFT;
2214         case THEME_LOCATION_RESIZING_RIGHT:
2215                 return CURSOR_RIGHT;
2216         case THEME_LOCATION_RESIZING_TOP_LEFT:
2217                 return CURSOR_TOP_LEFT;
2218         case THEME_LOCATION_RESIZING_TOP_RIGHT:
2219                 return CURSOR_TOP_RIGHT;
2220         case THEME_LOCATION_RESIZING_BOTTOM_LEFT:
2221                 return CURSOR_BOTTOM_LEFT;
2222         case THEME_LOCATION_RESIZING_BOTTOM_RIGHT:
2223                 return CURSOR_BOTTOM_RIGHT;
2224         case THEME_LOCATION_EXTERIOR:
2225         case THEME_LOCATION_TITLEBAR:
2226         default:
2227                 return CURSOR_LEFT_PTR;
2228         }
2229 }
2230
2231 void
2232 window_show_frame_menu(struct window *window,
2233                        struct input *input, uint32_t time)
2234 {
2235         int32_t x, y;
2236
2237         if (window->xdg_surface) {
2238                 input_get_position(input, &x, &y);
2239                 xdg_surface_show_window_menu(window->xdg_surface,
2240                                              input_get_seat(input),
2241                                              window->display->serial,
2242                                              x - 10, y - 10);
2243         }
2244 }
2245
2246 static int
2247 frame_enter_handler(struct widget *widget,
2248                     struct input *input, float x, float y, void *data)
2249 {
2250         struct window_frame *frame = data;
2251         enum theme_location location;
2252
2253         location = frame_pointer_enter(frame->frame, input, x, y);
2254         if (frame_status(frame->frame) & FRAME_STATUS_REPAINT)
2255                 widget_schedule_redraw(frame->widget);
2256
2257         return frame_get_pointer_image_for_location(data, location);
2258 }
2259
2260 static int
2261 frame_motion_handler(struct widget *widget,
2262                      struct input *input, uint32_t time,
2263                      float x, float y, void *data)
2264 {
2265         struct window_frame *frame = data;
2266         enum theme_location location;
2267
2268         location = frame_pointer_motion(frame->frame, input, x, y);
2269         if (frame_status(frame->frame) & FRAME_STATUS_REPAINT)
2270                 widget_schedule_redraw(frame->widget);
2271
2272         return frame_get_pointer_image_for_location(data, location);
2273 }
2274
2275 static void
2276 frame_leave_handler(struct widget *widget,
2277                     struct input *input, void *data)
2278 {
2279         struct window_frame *frame = data;
2280
2281         frame_pointer_leave(frame->frame, input);
2282         if (frame_status(frame->frame) & FRAME_STATUS_REPAINT)
2283                 widget_schedule_redraw(frame->widget);
2284 }
2285
2286 static void
2287 frame_handle_status(struct window_frame *frame, struct input *input,
2288                     uint32_t time, enum theme_location location)
2289 {
2290         struct window *window = frame->widget->window;
2291         uint32_t status;
2292
2293         status = frame_status(frame->frame);
2294         if (status & FRAME_STATUS_REPAINT)
2295                 widget_schedule_redraw(frame->widget);
2296
2297         if (status & FRAME_STATUS_MINIMIZE) {
2298                 window_set_minimized(window);
2299                 frame_status_clear(frame->frame, FRAME_STATUS_MINIMIZE);
2300         }
2301
2302         if (status & FRAME_STATUS_MENU) {
2303                 window_show_frame_menu(window, input, time);
2304                 frame_status_clear(frame->frame, FRAME_STATUS_MENU);
2305         }
2306
2307         if (status & FRAME_STATUS_MAXIMIZE) {
2308                 window_set_maximized(window, !window->maximized);
2309                 frame_status_clear(frame->frame, FRAME_STATUS_MAXIMIZE);
2310         }
2311
2312         if (status & FRAME_STATUS_CLOSE) {
2313                 window_close(window);
2314                 return;
2315         }
2316
2317         if ((status & FRAME_STATUS_MOVE) && window->xdg_surface) {
2318                 input_ungrab(input);
2319                 xdg_surface_move(window->xdg_surface,
2320                                  input_get_seat(input),
2321                                  window->display->serial);
2322
2323                 frame_status_clear(frame->frame, FRAME_STATUS_MOVE);
2324         }
2325
2326         if ((status & FRAME_STATUS_RESIZE) && window->xdg_surface) {
2327                 input_ungrab(input);
2328
2329                 xdg_surface_resize(window->xdg_surface,
2330                                    input_get_seat(input),
2331                                    window->display->serial,
2332                                    location);
2333
2334                 frame_status_clear(frame->frame, FRAME_STATUS_RESIZE);
2335         }
2336 }
2337
2338 static void
2339 frame_button_handler(struct widget *widget,
2340                      struct input *input, uint32_t time,
2341                      uint32_t button, enum wl_pointer_button_state state,
2342                      void *data)
2343
2344 {
2345         struct window_frame *frame = data;
2346         enum theme_location location;
2347
2348         location = frame_pointer_button(frame->frame, input, button, state);
2349         frame_handle_status(frame, input, time, location);
2350 }
2351
2352 static void
2353 frame_touch_down_handler(struct widget *widget, struct input *input,
2354                          uint32_t serial, uint32_t time, int32_t id,
2355                          float x, float y, void *data)
2356 {
2357         struct window_frame *frame = data;
2358
2359         frame_touch_down(frame->frame, input, id, x, y);
2360         frame_handle_status(frame, input, time, THEME_LOCATION_CLIENT_AREA);
2361 }
2362
2363 static void
2364 frame_touch_up_handler(struct widget *widget,
2365                          struct input *input, uint32_t serial, uint32_t time,
2366                          int32_t id, void *data)
2367 {
2368         struct window_frame *frame = data;
2369
2370         frame_touch_up(frame->frame, input, id);
2371         frame_handle_status(frame, input, time, THEME_LOCATION_CLIENT_AREA);
2372 }
2373
2374 struct widget *
2375 window_frame_create(struct window *window, void *data)
2376 {
2377         struct window_frame *frame;
2378         uint32_t buttons;
2379
2380         if (window->custom) {
2381                 buttons = FRAME_BUTTON_NONE;
2382         } else {
2383                 buttons = FRAME_BUTTON_ALL;
2384         }
2385
2386         frame = xzalloc(sizeof *frame);
2387         frame->frame = frame_create(window->display->theme, 0, 0,
2388                                     buttons, window->title);
2389
2390         frame->widget = window_add_widget(window, frame);
2391         frame->child = widget_add_widget(frame->widget, data);
2392
2393         widget_set_redraw_handler(frame->widget, frame_redraw_handler);
2394         widget_set_resize_handler(frame->widget, frame_resize_handler);
2395         widget_set_enter_handler(frame->widget, frame_enter_handler);
2396         widget_set_leave_handler(frame->widget, frame_leave_handler);
2397         widget_set_motion_handler(frame->widget, frame_motion_handler);
2398         widget_set_button_handler(frame->widget, frame_button_handler);
2399         widget_set_touch_down_handler(frame->widget, frame_touch_down_handler);
2400         widget_set_touch_up_handler(frame->widget, frame_touch_up_handler);
2401
2402         window->frame = frame;
2403
2404         return frame->child;
2405 }
2406
2407 void
2408 window_frame_set_child_size(struct widget *widget, int child_width,
2409                             int child_height)
2410 {
2411         struct display *display = widget->window->display;
2412         struct theme *t = display->theme;
2413         int decoration_width, decoration_height;
2414         int width, height;
2415         int margin = widget->window->maximized ? 0 : t->margin;
2416
2417         if (!widget->window->fullscreen) {
2418                 decoration_width = (t->width + margin) * 2;
2419                 decoration_height = t->width +
2420                         t->titlebar_height + margin * 2;
2421
2422                 width = child_width + decoration_width;
2423                 height = child_height + decoration_height;
2424         } else {
2425                 width = child_width;
2426                 height = child_height;
2427         }
2428
2429         window_schedule_resize(widget->window, width, height);
2430 }
2431
2432 static void
2433 window_frame_destroy(struct window_frame *frame)
2434 {
2435         frame_destroy(frame->frame);
2436
2437         /* frame->child must be destroyed by the application */
2438         widget_destroy(frame->widget);
2439         free(frame);
2440 }
2441
2442 static void
2443 input_set_focus_widget(struct input *input, struct widget *focus,
2444                        float x, float y)
2445 {
2446         struct widget *old, *widget;
2447         int cursor;
2448
2449         if (focus == input->focus_widget)
2450                 return;
2451
2452         old = input->focus_widget;
2453         if (old) {
2454                 widget = old;
2455                 if (input->grab)
2456                         widget = input->grab;
2457                 if (widget->leave_handler)
2458                         widget->leave_handler(old, input, widget->user_data);
2459                 input->focus_widget = NULL;
2460         }
2461
2462         if (focus) {
2463                 widget = focus;
2464                 if (input->grab)
2465                         widget = input->grab;
2466                 input->focus_widget = focus;
2467                 if (widget->enter_handler)
2468                         cursor = widget->enter_handler(focus, input, x, y,
2469                                                        widget->user_data);
2470                 else
2471                         cursor = widget->default_cursor;
2472
2473                 input_set_pointer_image(input, cursor);
2474         }
2475 }
2476
2477 void
2478 touch_grab(struct input  *input, int32_t touch_id)
2479 {
2480         input->touch_grab = 1;
2481         input->touch_grab_id = touch_id;
2482 }
2483
2484 void
2485 touch_ungrab(struct input *input)
2486 {
2487         struct touch_point *tp, *tmp;
2488
2489         input->touch_grab = 0;
2490
2491         wl_list_for_each_safe(tp, tmp,
2492                         &input->touch_point_list, link) {
2493                 if (tp->id != input->touch_grab_id)
2494                         continue;
2495                 wl_list_remove(&tp->link);
2496                 free(tp);
2497
2498                 return;
2499         }
2500 }
2501
2502 void
2503 input_grab(struct input *input, struct widget *widget, uint32_t button)
2504 {
2505         input->grab = widget;
2506         input->grab_button = button;
2507
2508         input_set_focus_widget(input, widget, input->sx, input->sy);
2509 }
2510
2511 void
2512 input_ungrab(struct input *input)
2513 {
2514         struct widget *widget;
2515
2516         input->grab = NULL;
2517         if (input->pointer_focus) {
2518                 widget = window_find_widget(input->pointer_focus,
2519                                             input->sx, input->sy);
2520                 input_set_focus_widget(input, widget, input->sx, input->sy);
2521         }
2522 }
2523
2524 static void
2525 input_remove_pointer_focus(struct input *input)
2526 {
2527         struct window *window = input->pointer_focus;
2528
2529         if (!window)
2530                 return;
2531
2532         input_set_focus_widget(input, NULL, 0, 0);
2533
2534         input->pointer_focus = NULL;
2535         input->current_cursor = CURSOR_UNSET;
2536 }
2537
2538 static void
2539 pointer_handle_enter(void *data, struct wl_pointer *pointer,
2540                      uint32_t serial, struct wl_surface *surface,
2541                      wl_fixed_t sx_w, wl_fixed_t sy_w)
2542 {
2543         struct input *input = data;
2544         struct window *window;
2545         struct widget *widget;
2546         float sx = wl_fixed_to_double(sx_w);
2547         float sy = wl_fixed_to_double(sy_w);
2548
2549         if (!surface) {
2550                 /* enter event for a window we've just destroyed */
2551                 return;
2552         }
2553
2554         window = wl_surface_get_user_data(surface);
2555         if (surface != window->main_surface->surface) {
2556                 DBG("Ignoring input event from subsurface %p\n", surface);
2557                 return;
2558         }
2559
2560         input->display->serial = serial;
2561         input->pointer_enter_serial = serial;
2562         input->pointer_focus = window;
2563
2564         input->sx = sx;
2565         input->sy = sy;
2566
2567         widget = window_find_widget(window, sx, sy);
2568         input_set_focus_widget(input, widget, sx, sy);
2569 }
2570
2571 static void
2572 pointer_handle_leave(void *data, struct wl_pointer *pointer,
2573                      uint32_t serial, struct wl_surface *surface)
2574 {
2575         struct input *input = data;
2576
2577         input->display->serial = serial;
2578         input_remove_pointer_focus(input);
2579 }
2580
2581 static void
2582 pointer_handle_motion(void *data, struct wl_pointer *pointer,
2583                       uint32_t time, wl_fixed_t sx_w, wl_fixed_t sy_w)
2584 {
2585         struct input *input = data;
2586         struct window *window = input->pointer_focus;
2587         struct widget *widget;
2588         int cursor;
2589         float sx = wl_fixed_to_double(sx_w);
2590         float sy = wl_fixed_to_double(sy_w);
2591
2592         if (!window)
2593                 return;
2594
2595         input->sx = sx;
2596         input->sy = sy;
2597
2598         /* when making the window smaller - e.g. after a unmaximise we might
2599          * still have a pending motion event that the compositor has picked
2600          * based on the old surface dimensions
2601          */
2602         if (sx > window->main_surface->allocation.width ||
2603             sy > window->main_surface->allocation.height)
2604                 return;
2605
2606         if (!(input->grab && input->grab_button)) {
2607                 widget = window_find_widget(window, sx, sy);
2608                 input_set_focus_widget(input, widget, sx, sy);
2609         }
2610
2611         if (input->grab)
2612                 widget = input->grab;
2613         else
2614                 widget = input->focus_widget;
2615         if (widget) {
2616                 if (widget->motion_handler)
2617                         cursor = widget->motion_handler(input->focus_widget,
2618                                                         input, time, sx, sy,
2619                                                         widget->user_data);
2620                 else
2621                         cursor = widget->default_cursor;
2622         } else
2623                 cursor = CURSOR_LEFT_PTR;
2624
2625         input_set_pointer_image(input, cursor);
2626 }
2627
2628 static void
2629 pointer_handle_button(void *data, struct wl_pointer *pointer, uint32_t serial,
2630                       uint32_t time, uint32_t button, uint32_t state_w)
2631 {
2632         struct input *input = data;
2633         struct widget *widget;
2634         enum wl_pointer_button_state state = state_w;
2635
2636         input->display->serial = serial;
2637         if (input->focus_widget && input->grab == NULL &&
2638             state == WL_POINTER_BUTTON_STATE_PRESSED)
2639                 input_grab(input, input->focus_widget, button);
2640
2641         widget = input->grab;
2642         if (widget && widget->button_handler)
2643                 (*widget->button_handler)(widget,
2644                                           input, time,
2645                                           button, state,
2646                                           input->grab->user_data);
2647
2648         if (input->grab && input->grab_button == button &&
2649             state == WL_POINTER_BUTTON_STATE_RELEASED)
2650                 input_ungrab(input);
2651 }
2652
2653 static void
2654 pointer_handle_axis(void *data, struct wl_pointer *pointer,
2655                     uint32_t time, uint32_t axis, wl_fixed_t value)
2656 {
2657         struct input *input = data;
2658         struct widget *widget;
2659
2660         widget = input->focus_widget;
2661         if (input->grab)
2662                 widget = input->grab;
2663         if (widget && widget->axis_handler)
2664                 (*widget->axis_handler)(widget,
2665                                         input, time,
2666                                         axis, value,
2667                                         widget->user_data);
2668 }
2669
2670 static const struct wl_pointer_listener pointer_listener = {
2671         pointer_handle_enter,
2672         pointer_handle_leave,
2673         pointer_handle_motion,
2674         pointer_handle_button,
2675         pointer_handle_axis,
2676 };
2677
2678 static void
2679 input_remove_keyboard_focus(struct input *input)
2680 {
2681         struct window *window = input->keyboard_focus;
2682         struct itimerspec its;
2683
2684         its.it_interval.tv_sec = 0;
2685         its.it_interval.tv_nsec = 0;
2686         its.it_value.tv_sec = 0;
2687         its.it_value.tv_nsec = 0;
2688         timerfd_settime(input->repeat_timer_fd, 0, &its, NULL);
2689
2690         if (!window)
2691                 return;
2692
2693         if (window->keyboard_focus_handler)
2694                 (*window->keyboard_focus_handler)(window, NULL,
2695                                                   window->user_data);
2696
2697         input->keyboard_focus = NULL;
2698 }
2699
2700 static void
2701 keyboard_repeat_func(struct task *task, uint32_t events)
2702 {
2703         struct input *input =
2704                 container_of(task, struct input, repeat_task);
2705         struct window *window = input->keyboard_focus;
2706         uint64_t exp;
2707
2708         if (read(input->repeat_timer_fd, &exp, sizeof exp) != sizeof exp)
2709                 /* If we change the timer between the fd becoming
2710                  * readable and getting here, there'll be nothing to
2711                  * read and we get EAGAIN. */
2712                 return;
2713
2714         if (window && window->key_handler) {
2715                 (*window->key_handler)(window, input, input->repeat_time,
2716                                        input->repeat_key, input->repeat_sym,
2717                                        WL_KEYBOARD_KEY_STATE_PRESSED,
2718                                        window->user_data);
2719         }
2720 }
2721
2722 static void
2723 keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard,
2724                        uint32_t format, int fd, uint32_t size)
2725 {
2726         struct input *input = data;
2727         struct xkb_keymap *keymap;
2728         struct xkb_state *state;
2729         char *map_str;
2730
2731         if (!data) {
2732                 close(fd);
2733                 return;
2734         }
2735
2736         if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) {
2737                 close(fd);
2738                 return;
2739         }
2740
2741         map_str = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
2742         if (map_str == MAP_FAILED) {
2743                 close(fd);
2744                 return;
2745         }
2746
2747         keymap = xkb_map_new_from_string(input->display->xkb_context,
2748                                          map_str,
2749                                          XKB_KEYMAP_FORMAT_TEXT_V1,
2750                                          0);
2751         munmap(map_str, size);
2752         close(fd);
2753
2754         if (!keymap) {
2755                 fprintf(stderr, "failed to compile keymap\n");
2756                 return;
2757         }
2758
2759         state = xkb_state_new(keymap);
2760         if (!state) {
2761                 fprintf(stderr, "failed to create XKB state\n");
2762                 xkb_map_unref(keymap);
2763                 return;
2764         }
2765
2766         xkb_keymap_unref(input->xkb.keymap);
2767         xkb_state_unref(input->xkb.state);
2768         input->xkb.keymap = keymap;
2769         input->xkb.state = state;
2770
2771         input->xkb.control_mask =
2772                 1 << xkb_map_mod_get_index(input->xkb.keymap, "Control");
2773         input->xkb.alt_mask =
2774                 1 << xkb_map_mod_get_index(input->xkb.keymap, "Mod1");
2775         input->xkb.shift_mask =
2776                 1 << xkb_map_mod_get_index(input->xkb.keymap, "Shift");
2777 }
2778
2779 static void
2780 keyboard_handle_enter(void *data, struct wl_keyboard *keyboard,
2781                       uint32_t serial, struct wl_surface *surface,
2782                       struct wl_array *keys)
2783 {
2784         struct input *input = data;
2785         struct window *window;
2786
2787         input->display->serial = serial;
2788         input->keyboard_focus = wl_surface_get_user_data(surface);
2789
2790         window = input->keyboard_focus;
2791         if (window->keyboard_focus_handler)
2792                 (*window->keyboard_focus_handler)(window,
2793                                                   input, window->user_data);
2794 }
2795
2796 static void
2797 keyboard_handle_leave(void *data, struct wl_keyboard *keyboard,
2798                       uint32_t serial, struct wl_surface *surface)
2799 {
2800         struct input *input = data;
2801
2802         input->display->serial = serial;
2803         input_remove_keyboard_focus(input);
2804 }
2805
2806 static void
2807 keyboard_handle_key(void *data, struct wl_keyboard *keyboard,
2808                     uint32_t serial, uint32_t time, uint32_t key,
2809                     uint32_t state_w)
2810 {
2811         struct input *input = data;
2812         struct window *window = input->keyboard_focus;
2813         uint32_t code, num_syms;
2814         enum wl_keyboard_key_state state = state_w;
2815         const xkb_keysym_t *syms;
2816         xkb_keysym_t sym;
2817         struct itimerspec its;
2818
2819         input->display->serial = serial;
2820         code = key + 8;
2821         if (!window || !input->xkb.state)
2822                 return;
2823
2824         /* We only use input grabs for pointer events for now, so just
2825          * ignore key presses if a grab is active.  We expand the key
2826          * event delivery mechanism to route events to widgets to
2827          * properly handle key grabs.  In the meantime, this prevents
2828          * key event devlivery while a grab is active. */
2829         if (input->grab && input->grab_button == 0)
2830                 return;
2831
2832         num_syms = xkb_key_get_syms(input->xkb.state, code, &syms);
2833
2834         sym = XKB_KEY_NoSymbol;
2835         if (num_syms == 1)
2836                 sym = syms[0];
2837
2838
2839         if (sym == XKB_KEY_F5 && input->modifiers == MOD_ALT_MASK) {
2840                 if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
2841                         window_set_maximized(window, !window->maximized);
2842         } else if (sym == XKB_KEY_F11 &&
2843                    window->fullscreen_handler &&
2844                    state == WL_KEYBOARD_KEY_STATE_PRESSED) {
2845                 window->fullscreen_handler(window, window->user_data);
2846         } else if (sym == XKB_KEY_F4 &&
2847                    input->modifiers == MOD_ALT_MASK &&
2848                    state == WL_KEYBOARD_KEY_STATE_PRESSED) {
2849                 window_close(window);
2850         } else if (window->key_handler) {
2851                 (*window->key_handler)(window, input, time, key,
2852                                        sym, state, window->user_data);
2853         }
2854
2855         if (state == WL_KEYBOARD_KEY_STATE_RELEASED &&
2856             key == input->repeat_key) {
2857                 its.it_interval.tv_sec = 0;
2858                 its.it_interval.tv_nsec = 0;
2859                 its.it_value.tv_sec = 0;
2860                 its.it_value.tv_nsec = 0;
2861                 timerfd_settime(input->repeat_timer_fd, 0, &its, NULL);
2862         } else if (state == WL_KEYBOARD_KEY_STATE_PRESSED &&
2863                    xkb_keymap_key_repeats(input->xkb.keymap, code)) {
2864                 input->repeat_sym = sym;
2865                 input->repeat_key = key;
2866                 input->repeat_time = time;
2867                 its.it_interval.tv_sec = 0;
2868                 its.it_interval.tv_nsec = 25 * 1000 * 1000;
2869                 its.it_value.tv_sec = 0;
2870                 its.it_value.tv_nsec = 400 * 1000 * 1000;
2871                 timerfd_settime(input->repeat_timer_fd, 0, &its, NULL);
2872         }
2873 }
2874
2875 static void
2876 keyboard_handle_modifiers(void *data, struct wl_keyboard *keyboard,
2877                           uint32_t serial, uint32_t mods_depressed,
2878                           uint32_t mods_latched, uint32_t mods_locked,
2879                           uint32_t group)
2880 {
2881         struct input *input = data;
2882         xkb_mod_mask_t mask;
2883
2884         /* If we're not using a keymap, then we don't handle PC-style modifiers */
2885         if (!input->xkb.keymap)
2886                 return;
2887
2888         xkb_state_update_mask(input->xkb.state, mods_depressed, mods_latched,
2889                               mods_locked, 0, 0, group);
2890         mask = xkb_state_serialize_mods(input->xkb.state,
2891                                         XKB_STATE_DEPRESSED |
2892                                         XKB_STATE_LATCHED);
2893         input->modifiers = 0;
2894         if (mask & input->xkb.control_mask)
2895                 input->modifiers |= MOD_CONTROL_MASK;
2896         if (mask & input->xkb.alt_mask)
2897                 input->modifiers |= MOD_ALT_MASK;
2898         if (mask & input->xkb.shift_mask)
2899                 input->modifiers |= MOD_SHIFT_MASK;
2900 }
2901
2902 static const struct wl_keyboard_listener keyboard_listener = {
2903         keyboard_handle_keymap,
2904         keyboard_handle_enter,
2905         keyboard_handle_leave,
2906         keyboard_handle_key,
2907         keyboard_handle_modifiers,
2908 };
2909
2910 static void
2911 touch_handle_down(void *data, struct wl_touch *wl_touch,
2912                   uint32_t serial, uint32_t time, struct wl_surface *surface,
2913                   int32_t id, wl_fixed_t x_w, wl_fixed_t y_w)
2914 {
2915         struct input *input = data;
2916         struct widget *widget;
2917         float sx = wl_fixed_to_double(x_w);
2918         float sy = wl_fixed_to_double(y_w);
2919
2920         input->display->serial = serial;
2921         input->touch_focus = wl_surface_get_user_data(surface);
2922         if (!input->touch_focus) {
2923                 DBG("Failed to find to touch focus for surface %p\n", surface);
2924                 return;
2925         }
2926
2927         if (surface != input->touch_focus->main_surface->surface) {
2928                 DBG("Ignoring input event from subsurface %p\n", surface);
2929                 input->touch_focus = NULL;
2930                 return;
2931         }
2932
2933         if (input->grab)
2934                 widget = input->grab;
2935         else
2936                 widget = window_find_widget(input->touch_focus,
2937                                             wl_fixed_to_double(x_w),
2938                                             wl_fixed_to_double(y_w));
2939         if (widget) {
2940                 struct touch_point *tp = xmalloc(sizeof *tp);
2941                 if (tp) {
2942                         tp->id = id;
2943                         tp->widget = widget;
2944                         tp->x = sx;
2945                         tp->y = sy;
2946                         wl_list_insert(&input->touch_point_list, &tp->link);
2947
2948                         if (widget->touch_down_handler)
2949                                 (*widget->touch_down_handler)(widget, input, 
2950                                                               serial, time, id,
2951                                                               sx, sy,
2952                                                               widget->user_data);
2953                 }
2954         }
2955 }
2956
2957 static void
2958 touch_handle_up(void *data, struct wl_touch *wl_touch,
2959                 uint32_t serial, uint32_t time, int32_t id)
2960 {
2961         struct input *input = data;
2962         struct touch_point *tp, *tmp;
2963
2964         if (!input->touch_focus) {
2965                 DBG("No touch focus found for touch up event!\n");
2966                 return;
2967         }
2968
2969         wl_list_for_each_safe(tp, tmp, &input->touch_point_list, link) {
2970                 if (tp->id != id)
2971                         continue;
2972
2973                 if (tp->widget->touch_up_handler)
2974                         (*tp->widget->touch_up_handler)(tp->widget, input, serial,
2975                                                         time, id,
2976                                                         tp->widget->user_data);
2977
2978                 wl_list_remove(&tp->link);
2979                 free(tp);
2980
2981                 return;
2982         }
2983 }
2984
2985 static void
2986 touch_handle_motion(void *data, struct wl_touch *wl_touch,
2987                     uint32_t time, int32_t id, wl_fixed_t x_w, wl_fixed_t y_w)
2988 {
2989         struct input *input = data;
2990         struct touch_point *tp;
2991         float sx = wl_fixed_to_double(x_w);
2992         float sy = wl_fixed_to_double(y_w);
2993
2994         DBG("touch_handle_motion: %i %i\n", id, wl_list_length(&input->touch_point_list));
2995
2996         if (!input->touch_focus) {
2997                 DBG("No touch focus found for touch motion event!\n");
2998                 return;
2999         }
3000
3001         wl_list_for_each(tp, &input->touch_point_list, link) {
3002                 if (tp->id != id)
3003                         continue;
3004
3005                 tp->x = sx;
3006                 tp->y = sy;
3007                 if (tp->widget->touch_motion_handler)
3008                         (*tp->widget->touch_motion_handler)(tp->widget, input, time,
3009                                                             id, sx, sy,
3010                                                             tp->widget->user_data);
3011                 return;
3012         }
3013 }
3014
3015 static void
3016 touch_handle_frame(void *data, struct wl_touch *wl_touch)
3017 {
3018         struct input *input = data;
3019         struct touch_point *tp, *tmp;
3020
3021         DBG("touch_handle_frame\n");
3022
3023         if (!input->touch_focus) {
3024                 DBG("No touch focus found for touch frame event!\n");
3025                 return;
3026         }
3027
3028         wl_list_for_each_safe(tp, tmp, &input->touch_point_list, link) {
3029                 if (tp->widget->touch_frame_handler)
3030                         (*tp->widget->touch_frame_handler)(tp->widget, input, 
3031                                                            tp->widget->user_data);
3032         }
3033 }
3034
3035 static void
3036 touch_handle_cancel(void *data, struct wl_touch *wl_touch)
3037 {
3038         struct input *input = data;
3039         struct touch_point *tp, *tmp;
3040
3041         DBG("touch_handle_cancel\n");
3042
3043         if (!input->touch_focus) {
3044                 DBG("No touch focus found for touch cancel event!\n");
3045                 return;
3046         }
3047
3048         wl_list_for_each_safe(tp, tmp, &input->touch_point_list, link) {
3049                 if (tp->widget->touch_cancel_handler)
3050                         (*tp->widget->touch_cancel_handler)(tp->widget, input,
3051                                                             tp->widget->user_data);
3052
3053                 wl_list_remove(&tp->link);
3054                 free(tp);
3055         }
3056 }
3057
3058 static const struct wl_touch_listener touch_listener = {
3059         touch_handle_down,
3060         touch_handle_up,
3061         touch_handle_motion,
3062         touch_handle_frame,
3063         touch_handle_cancel,
3064 };
3065
3066 static void
3067 seat_handle_capabilities(void *data, struct wl_seat *seat,
3068                          enum wl_seat_capability caps)
3069 {
3070         struct input *input = data;
3071
3072         if ((caps & WL_SEAT_CAPABILITY_POINTER) && !input->pointer) {
3073                 input->pointer = wl_seat_get_pointer(seat);
3074                 wl_pointer_set_user_data(input->pointer, input);
3075                 wl_pointer_add_listener(input->pointer, &pointer_listener,
3076                                         input);
3077         } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && input->pointer) {
3078                 wl_pointer_destroy(input->pointer);
3079                 input->pointer = NULL;
3080         }
3081
3082         if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !input->keyboard) {
3083                 input->keyboard = wl_seat_get_keyboard(seat);
3084                 wl_keyboard_set_user_data(input->keyboard, input);
3085                 wl_keyboard_add_listener(input->keyboard, &keyboard_listener,
3086                                          input);
3087         } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && input->keyboard) {
3088                 wl_keyboard_destroy(input->keyboard);
3089                 input->keyboard = NULL;
3090         }
3091
3092         if ((caps & WL_SEAT_CAPABILITY_TOUCH) && !input->touch) {
3093                 input->touch = wl_seat_get_touch(seat);
3094                 wl_touch_set_user_data(input->touch, input);
3095                 wl_touch_add_listener(input->touch, &touch_listener, input);
3096         } else if (!(caps & WL_SEAT_CAPABILITY_TOUCH) && input->touch) {
3097                 wl_touch_destroy(input->touch);
3098                 input->touch = NULL;
3099         }
3100 }
3101
3102 static void
3103 seat_handle_name(void *data, struct wl_seat *seat,
3104                  const char *name)
3105 {
3106
3107 }
3108
3109 static const struct wl_seat_listener seat_listener = {
3110         seat_handle_capabilities,
3111         seat_handle_name
3112 };
3113
3114 void
3115 input_get_position(struct input *input, int32_t *x, int32_t *y)
3116 {
3117         *x = input->sx;
3118         *y = input->sy;
3119 }
3120
3121 int
3122 input_get_touch(struct input *input, int32_t id, float *x, float *y)
3123 {
3124         struct touch_point *tp;
3125
3126         wl_list_for_each(tp, &input->touch_point_list, link) {
3127                 if (tp->id != id)
3128                         continue;
3129
3130                 *x = tp->x;
3131                 *y = tp->y;
3132                 return 0;
3133         }
3134
3135         return -1;
3136 }
3137
3138 struct display *
3139 input_get_display(struct input *input)
3140 {
3141         return input->display;
3142 }
3143
3144 struct wl_seat *
3145 input_get_seat(struct input *input)
3146 {
3147         return input->seat;
3148 }
3149
3150 uint32_t
3151 input_get_modifiers(struct input *input)
3152 {
3153         return input->modifiers;
3154 }
3155
3156 struct widget *
3157 input_get_focus_widget(struct input *input)
3158 {
3159         return input->focus_widget;
3160 }
3161
3162 struct data_offer {
3163         struct wl_data_offer *offer;
3164         struct input *input;
3165         struct wl_array types;
3166         int refcount;
3167
3168         struct task io_task;
3169         int fd;
3170         data_func_t func;
3171         int32_t x, y;
3172         void *user_data;
3173 };
3174
3175 static void
3176 data_offer_offer(void *data, struct wl_data_offer *wl_data_offer, const char *type)
3177 {
3178         struct data_offer *offer = data;
3179         char **p;
3180
3181         p = wl_array_add(&offer->types, sizeof *p);
3182         *p = strdup(type);
3183 }
3184
3185 static const struct wl_data_offer_listener data_offer_listener = {
3186         data_offer_offer,
3187 };
3188
3189 static void
3190 data_offer_destroy(struct data_offer *offer)
3191 {
3192         char **p;
3193
3194         offer->refcount--;
3195         if (offer->refcount == 0) {
3196                 wl_data_offer_destroy(offer->offer);
3197                 for (p = offer->types.data; *p; p++)
3198                         free(*p);
3199                 wl_array_release(&offer->types);
3200                 free(offer);
3201         }
3202 }
3203
3204 static void
3205 data_device_data_offer(void *data,
3206                        struct wl_data_device *data_device,
3207                        struct wl_data_offer *_offer)
3208 {
3209         struct data_offer *offer;
3210
3211         offer = xmalloc(sizeof *offer);
3212
3213         wl_array_init(&offer->types);
3214         offer->refcount = 1;
3215         offer->input = data;
3216         offer->offer = _offer;
3217         wl_data_offer_add_listener(offer->offer,
3218                                    &data_offer_listener, offer);
3219 }
3220
3221 static void
3222 data_device_enter(void *data, struct wl_data_device *data_device,
3223                   uint32_t serial, struct wl_surface *surface,
3224                   wl_fixed_t x_w, wl_fixed_t y_w,
3225                   struct wl_data_offer *offer)
3226 {
3227         struct input *input = data;
3228         struct window *window;
3229         void *types_data;
3230         float x = wl_fixed_to_double(x_w);
3231         float y = wl_fixed_to_double(y_w);
3232         char **p;
3233
3234         window = wl_surface_get_user_data(surface);
3235         input->drag_enter_serial = serial;
3236         input->drag_focus = window,
3237         input->drag_x = x;
3238         input->drag_y = y;
3239
3240         if (!input->touch_grab)
3241                 input->pointer_enter_serial = serial;
3242
3243         if (offer) {
3244                 input->drag_offer = wl_data_offer_get_user_data(offer);
3245
3246                 p = wl_array_add(&input->drag_offer->types, sizeof *p);
3247                 *p = NULL;
3248
3249                 types_data = input->drag_offer->types.data;
3250         } else {
3251                 input->drag_offer = NULL;
3252                 types_data = NULL;
3253         }
3254
3255         if (window->data_handler)
3256                 window->data_handler(window, input, x, y, types_data,
3257                                      window->user_data);
3258 }
3259
3260 static void
3261 data_device_leave(void *data, struct wl_data_device *data_device)
3262 {
3263         struct input *input = data;
3264
3265         if (input->drag_offer) {
3266                 data_offer_destroy(input->drag_offer);
3267                 input->drag_offer = NULL;
3268         }
3269 }
3270
3271 static void
3272 data_device_motion(void *data, struct wl_data_device *data_device,
3273                    uint32_t time, wl_fixed_t x_w, wl_fixed_t y_w)
3274 {
3275         struct input *input = data;
3276         struct window *window = input->drag_focus;
3277         float x = wl_fixed_to_double(x_w);
3278         float y = wl_fixed_to_double(y_w);
3279         void *types_data;
3280
3281         input->drag_x = x;
3282         input->drag_y = y;
3283
3284         if (input->drag_offer)
3285                 types_data = input->drag_offer->types.data;
3286         else
3287                 types_data = NULL;
3288
3289         if (window->data_handler)
3290                 window->data_handler(window, input, x, y, types_data,
3291                                      window->user_data);
3292 }
3293
3294 static void
3295 data_device_drop(void *data, struct wl_data_device *data_device)
3296 {
3297         struct input *input = data;
3298         struct window *window = input->drag_focus;
3299         float x, y;
3300
3301         x = input->drag_x;
3302         y = input->drag_y;
3303
3304         if (window->drop_handler)
3305                 window->drop_handler(window, input,
3306                                      x, y, window->user_data);
3307
3308         if (input->touch_grab)
3309                 touch_ungrab(input);
3310 }
3311
3312 static void
3313 data_device_selection(void *data,
3314                       struct wl_data_device *wl_data_device,
3315                       struct wl_data_offer *offer)
3316 {
3317         struct input *input = data;
3318         char **p;
3319
3320         if (input->selection_offer)
3321                 data_offer_destroy(input->selection_offer);
3322
3323         if (offer) {
3324                 input->selection_offer = wl_data_offer_get_user_data(offer);
3325                 p = wl_array_add(&input->selection_offer->types, sizeof *p);
3326                 *p = NULL;
3327         } else {
3328                 input->selection_offer = NULL;
3329         }
3330 }
3331
3332 static const struct wl_data_device_listener data_device_listener = {
3333         data_device_data_offer,
3334         data_device_enter,
3335         data_device_leave,
3336         data_device_motion,
3337         data_device_drop,
3338         data_device_selection
3339 };
3340
3341 static void
3342 input_set_pointer_image_index(struct input *input, int index)
3343 {
3344         struct wl_buffer *buffer;
3345         struct wl_cursor *cursor;
3346         struct wl_cursor_image *image;
3347
3348         if (!input->pointer)
3349                 return;
3350
3351         cursor = input->display->cursors[input->current_cursor];
3352         if (!cursor)
3353                 return;
3354
3355         if (index >= (int) cursor->image_count) {
3356                 fprintf(stderr, "cursor index out of range\n");
3357                 return;
3358         }
3359
3360         image = cursor->images[index];
3361         buffer = wl_cursor_image_get_buffer(image);
3362         if (!buffer)
3363                 return;
3364
3365         wl_surface_attach(input->pointer_surface, buffer, 0, 0);
3366         wl_surface_damage(input->pointer_surface, 0, 0,
3367                           image->width, image->height);
3368         wl_surface_commit(input->pointer_surface);
3369         wl_pointer_set_cursor(input->pointer, input->pointer_enter_serial,
3370                               input->pointer_surface,
3371                               image->hotspot_x, image->hotspot_y);
3372 }
3373
3374 static const struct wl_callback_listener pointer_surface_listener;
3375
3376 static void
3377 pointer_surface_frame_callback(void *data, struct wl_callback *callback,
3378                                uint32_t time)
3379 {
3380         struct input *input = data;
3381         struct wl_cursor *cursor;
3382         int i;
3383
3384         if (callback) {
3385                 assert(callback == input->cursor_frame_cb);
3386                 wl_callback_destroy(callback);
3387                 input->cursor_frame_cb = NULL;
3388         }
3389
3390         if (!input->pointer)
3391                 return;
3392
3393         if (input->current_cursor == CURSOR_BLANK) {
3394                 wl_pointer_set_cursor(input->pointer,
3395                                       input->pointer_enter_serial,
3396                                       NULL, 0, 0);
3397                 return;
3398         }
3399
3400         if (input->current_cursor == CURSOR_UNSET)
3401                 return;
3402         cursor = input->display->cursors[input->current_cursor];
3403         if (!cursor)
3404                 return;
3405
3406         /* FIXME We don't have the current time on the first call so we set
3407          * the animation start to the time of the first frame callback. */
3408         if (time == 0)
3409                 input->cursor_anim_start = 0;
3410         else if (input->cursor_anim_start == 0)
3411                 input->cursor_anim_start = time;
3412
3413         if (time == 0 || input->cursor_anim_start == 0)
3414                 i = 0;
3415         else
3416                 i = wl_cursor_frame(cursor, time - input->cursor_anim_start);
3417
3418         if (cursor->image_count > 1) {
3419                 input->cursor_frame_cb =
3420                         wl_surface_frame(input->pointer_surface);
3421                 wl_callback_add_listener(input->cursor_frame_cb,
3422                                          &pointer_surface_listener, input);
3423         }
3424
3425         input_set_pointer_image_index(input, i);
3426 }
3427
3428 static const struct wl_callback_listener pointer_surface_listener = {
3429         pointer_surface_frame_callback
3430 };
3431
3432 void
3433 input_set_pointer_image(struct input *input, int pointer)
3434 {
3435         int force = 0;
3436
3437         if (!input->pointer)
3438                 return;
3439
3440         if (input->pointer_enter_serial > input->cursor_serial)
3441                 force = 1;
3442
3443         if (!force && pointer == input->current_cursor)
3444                 return;
3445
3446         input->current_cursor = pointer;
3447         input->cursor_serial = input->pointer_enter_serial;
3448         if (!input->cursor_frame_cb)
3449                 pointer_surface_frame_callback(input, NULL, 0);
3450         else if (force) {
3451                 /* The current frame callback may be stuck if, for instance,
3452                  * the set cursor request was processed by the server after
3453                  * this client lost the focus. In this case the cursor surface
3454                  * might not be mapped and the frame callback wouldn't ever
3455                  * complete. Send a set_cursor and attach to try to map the
3456                  * cursor surface again so that the callback will finish */
3457                 input_set_pointer_image_index(input, 0);
3458         }
3459 }
3460
3461 struct wl_data_device *
3462 input_get_data_device(struct input *input)
3463 {
3464         return input->data_device;
3465 }
3466
3467 void
3468 input_set_selection(struct input *input,
3469                     struct wl_data_source *source, uint32_t time)
3470 {
3471         if (input->data_device)
3472                 wl_data_device_set_selection(input->data_device, source, time);
3473 }
3474
3475 void
3476 input_accept(struct input *input, const char *type)
3477 {
3478         wl_data_offer_accept(input->drag_offer->offer,
3479                              input->drag_enter_serial, type);
3480 }
3481
3482 static void
3483 offer_io_func(struct task *task, uint32_t events)
3484 {
3485         struct data_offer *offer =
3486                 container_of(task, struct data_offer, io_task);
3487         unsigned int len;
3488         char buffer[4096];
3489
3490         len = read(offer->fd, buffer, sizeof buffer);
3491         offer->func(buffer, len,
3492                     offer->x, offer->y, offer->user_data);
3493
3494         if (len == 0) {
3495                 close(offer->fd);
3496                 data_offer_destroy(offer);
3497         }
3498 }
3499
3500 static void
3501 data_offer_receive_data(struct data_offer *offer, const char *mime_type,
3502                         data_func_t func, void *user_data)
3503 {
3504         int p[2];
3505
3506         if (pipe2(p, O_CLOEXEC) == -1)
3507                 return;
3508
3509         wl_data_offer_receive(offer->offer, mime_type, p[1]);
3510         close(p[1]);
3511
3512         offer->io_task.run = offer_io_func;
3513         offer->fd = p[0];
3514         offer->func = func;
3515         offer->refcount++;
3516         offer->user_data = user_data;
3517
3518         display_watch_fd(offer->input->display,
3519                          offer->fd, EPOLLIN, &offer->io_task);
3520 }
3521
3522 void
3523 input_receive_drag_data(struct input *input, const char *mime_type,
3524                         data_func_t func, void *data)
3525 {
3526         data_offer_receive_data(input->drag_offer, mime_type, func, data);
3527         input->drag_offer->x = input->drag_x;
3528         input->drag_offer->y = input->drag_y;
3529 }
3530
3531 int
3532 input_receive_drag_data_to_fd(struct input *input,
3533                               const char *mime_type, int fd)
3534 {
3535         if (input->drag_offer)
3536                 wl_data_offer_receive(input->drag_offer->offer, mime_type, fd);
3537
3538         return 0;
3539 }
3540
3541 int
3542 input_receive_selection_data(struct input *input, const char *mime_type,
3543                              data_func_t func, void *data)
3544 {
3545         char **p;
3546
3547         if (input->selection_offer == NULL)
3548                 return -1;
3549
3550         for (p = input->selection_offer->types.data; *p; p++)
3551                 if (strcmp(mime_type, *p) == 0)
3552                         break;
3553
3554         if (*p == NULL)
3555                 return -1;
3556
3557         data_offer_receive_data(input->selection_offer,
3558                                 mime_type, func, data);
3559         return 0;
3560 }
3561
3562 int
3563 input_receive_selection_data_to_fd(struct input *input,
3564                                    const char *mime_type, int fd)
3565 {
3566         if (input->selection_offer)
3567                 wl_data_offer_receive(input->selection_offer->offer,
3568                                       mime_type, fd);
3569
3570         return 0;
3571 }
3572
3573 void
3574 window_move(struct window *window, struct input *input, uint32_t serial)
3575 {
3576         if (!window->xdg_surface)
3577                 return;
3578
3579         xdg_surface_move(window->xdg_surface, input->seat, serial);
3580 }
3581
3582 static void
3583 surface_set_synchronized(struct surface *surface)
3584 {
3585         if (!surface->subsurface)
3586                 return;
3587
3588         if (surface->synchronized)
3589                 return;
3590
3591         wl_subsurface_set_sync(surface->subsurface);
3592         surface->synchronized = 1;
3593 }
3594
3595 static void
3596 surface_set_synchronized_default(struct surface *surface)
3597 {
3598         if (!surface->subsurface)
3599                 return;
3600
3601         if (surface->synchronized == surface->synchronized_default)
3602                 return;
3603
3604         if (surface->synchronized_default)
3605                 wl_subsurface_set_sync(surface->subsurface);
3606         else
3607                 wl_subsurface_set_desync(surface->subsurface);
3608
3609         surface->synchronized = surface->synchronized_default;
3610 }
3611
3612 static void
3613 surface_resize(struct surface *surface)
3614 {
3615         struct widget *widget = surface->widget;
3616         struct wl_compositor *compositor = widget->window->display->compositor;
3617
3618         if (surface->input_region) {
3619                 wl_region_destroy(surface->input_region);
3620                 surface->input_region = NULL;
3621         }
3622
3623         if (surface->opaque_region)
3624                 wl_region_destroy(surface->opaque_region);
3625
3626         surface->opaque_region = wl_compositor_create_region(compositor);
3627
3628         if (widget->resize_handler)
3629                 widget->resize_handler(widget,
3630                                        widget->allocation.width,
3631                                        widget->allocation.height,
3632                                        widget->user_data);
3633
3634         if (surface->subsurface &&
3635             (surface->allocation.x != widget->allocation.x ||
3636              surface->allocation.y != widget->allocation.y)) {
3637                 wl_subsurface_set_position(surface->subsurface,
3638                                            widget->allocation.x,
3639                                            widget->allocation.y);
3640         }
3641         if (surface->allocation.width != widget->allocation.width ||
3642             surface->allocation.height != widget->allocation.height) {
3643                 window_schedule_redraw(widget->window);
3644         }
3645         surface->allocation = widget->allocation;
3646
3647         if (widget->opaque)
3648                 wl_region_add(surface->opaque_region, 0, 0,
3649                               widget->allocation.width,
3650                               widget->allocation.height);
3651 }
3652
3653 static void
3654 hack_prevent_EGL_sub_surface_deadlock(struct window *window)
3655 {
3656         /*
3657          * This hack should be removed, when EGL respects
3658          * eglSwapInterval(0).
3659          *
3660          * If this window has sub-surfaces, especially a free-running
3661          * EGL-widget, we need to post the parent surface once with
3662          * all the old state to guarantee, that the EGL-widget will
3663          * receive its frame callback soon. Otherwise, a forced call
3664          * to eglSwapBuffers may end up blocking, waiting for a frame
3665          * event that will never come, because we will commit the parent
3666          * surface with all new state only after eglSwapBuffers returns.
3667          *
3668          * This assumes, that:
3669          * 1. When the EGL widget's resize hook is called, it pauses.
3670          * 2. When the EGL widget's redraw hook is called, it forces a
3671          *    repaint and a call to eglSwapBuffers(), and maybe resumes.
3672          * In a single threaded application condition 1 is a no-op.
3673          *
3674          * XXX: This should actually be after the surface_resize() calls,
3675          * but cannot, because then it would commit the incomplete state
3676          * accumulated from the widget resize hooks.
3677          */
3678         if (window->subsurface_list.next != &window->main_surface->link ||
3679             window->subsurface_list.prev != &window->main_surface->link)
3680                 wl_surface_commit(window->main_surface->surface);
3681 }
3682
3683 static void
3684 window_do_resize(struct window *window)
3685 {
3686         struct surface *surface;
3687
3688         widget_set_allocation(window->main_surface->widget,
3689                               window->pending_allocation.x,
3690                               window->pending_allocation.y,
3691                               window->pending_allocation.width,
3692                               window->pending_allocation.height);
3693
3694         surface_resize(window->main_surface);
3695
3696         /* The main surface is in the list, too. Main surface's
3697          * resize_handler is responsible for calling widget_set_allocation()
3698          * on all sub-surface root widgets, so they will be resized
3699          * properly.
3700          */
3701         wl_list_for_each(surface, &window->subsurface_list, link) {
3702                 if (surface == window->main_surface)
3703                         continue;
3704
3705                 surface_set_synchronized(surface);
3706                 surface_resize(surface);
3707         }
3708
3709         if (!window->fullscreen && !window->maximized)
3710                 window->saved_allocation = window->pending_allocation;
3711 }
3712
3713 static void
3714 idle_resize(struct window *window)
3715 {
3716         window->resize_needed = 0;
3717         window->redraw_needed = 1;
3718
3719         DBG("from %dx%d to %dx%d\n",
3720             window->main_surface->server_allocation.width,
3721             window->main_surface->server_allocation.height,
3722             window->pending_allocation.width,
3723             window->pending_allocation.height);
3724
3725         hack_prevent_EGL_sub_surface_deadlock(window);
3726
3727         window_do_resize(window);
3728 }
3729
3730 static void
3731 undo_resize(struct window *window)
3732 {
3733         window->pending_allocation.width =
3734                 window->main_surface->server_allocation.width;
3735         window->pending_allocation.height =
3736                 window->main_surface->server_allocation.height;
3737
3738         DBG("back to %dx%d\n",
3739             window->main_surface->server_allocation.width,
3740             window->main_surface->server_allocation.height);
3741
3742         window_do_resize(window);
3743
3744         if (window->pending_allocation.width == 0 &&
3745             window->pending_allocation.height == 0) {
3746                 fprintf(stderr, "Error: Could not draw a surface, "
3747                         "most likely due to insufficient disk space in "
3748                         "%s (XDG_RUNTIME_DIR).\n", getenv("XDG_RUNTIME_DIR"));
3749                 exit(EXIT_FAILURE);
3750         }
3751 }
3752
3753 void
3754 window_schedule_resize(struct window *window, int width, int height)
3755 {
3756         /* We should probably get these numbers from the theme. */
3757         const int min_width = 200, min_height = 200;
3758
3759         window->pending_allocation.x = 0;
3760         window->pending_allocation.y = 0;
3761         window->pending_allocation.width = width;
3762         window->pending_allocation.height = height;
3763
3764         if (window->min_allocation.width == 0) {
3765                 if (width < min_width && window->frame)
3766                         window->min_allocation.width = min_width;
3767                 else
3768                         window->min_allocation.width = width;
3769                 if (height < min_height && window->frame)
3770                         window->min_allocation.height = min_height;
3771                 else
3772                         window->min_allocation.height = height;
3773         }
3774
3775         if (window->pending_allocation.width < window->min_allocation.width)
3776                 window->pending_allocation.width = window->min_allocation.width;
3777         if (window->pending_allocation.height < window->min_allocation.height)
3778                 window->pending_allocation.height = window->min_allocation.height;
3779
3780         window->resize_needed = 1;
3781         window_schedule_redraw(window);
3782 }
3783
3784 void
3785 widget_schedule_resize(struct widget *widget, int32_t width, int32_t height)
3786 {
3787         window_schedule_resize(widget->window, width, height);
3788 }
3789
3790 static int
3791 window_get_shadow_margin(struct window *window)
3792 {
3793         if (window->frame)
3794                 return frame_get_shadow_margin(window->frame->frame);
3795         else
3796                 return 0;
3797 }
3798
3799 static void
3800 handle_surface_configure(void *data, struct xdg_surface *xdg_surface,
3801                          int32_t width, int32_t height,
3802                          struct wl_array *states, uint32_t serial)
3803 {
3804         struct window *window = data;
3805         uint32_t *p;
3806
3807         window->maximized = 0;
3808         window->fullscreen = 0;
3809         window->resizing = 0;
3810         window->focused = 0;
3811
3812         wl_array_for_each(p, states) {
3813                 uint32_t state = *p;
3814                 switch (state) {
3815                 case XDG_SURFACE_STATE_MAXIMIZED:
3816                         window->maximized = 1;
3817                         break;
3818                 case XDG_SURFACE_STATE_FULLSCREEN:
3819                         window->fullscreen = 1;
3820                         break;
3821                 case XDG_SURFACE_STATE_RESIZING:
3822                         window->resizing = 1;
3823                         break;
3824                 case XDG_SURFACE_STATE_ACTIVATED:
3825                         window->focused = 1;
3826                         break;
3827                 default:
3828                         /* Unknown state */
3829                         break;
3830                 }
3831         }
3832
3833         if (window->frame) {
3834                 if (window->maximized) {
3835                         frame_set_flag(window->frame->frame, FRAME_FLAG_MAXIMIZED);
3836                 } else {
3837                         frame_unset_flag(window->frame->frame, FRAME_FLAG_MAXIMIZED);
3838                 }
3839
3840                 if (window->focused) {
3841                         frame_set_flag(window->frame->frame, FRAME_FLAG_ACTIVE);
3842                 } else {
3843                         frame_unset_flag(window->frame->frame, FRAME_FLAG_ACTIVE);
3844                 }
3845         }
3846
3847         if (width > 0 && height > 0) {
3848                 /* The width / height params are for window geometry,
3849                  * but window_schedule_resize takes allocation. Add
3850                  * on the shadow margin to get the difference. */
3851                 int margin = window_get_shadow_margin(window);
3852
3853                 window_schedule_resize(window,
3854                                        width + margin * 2,
3855                                        height + margin * 2);
3856         } else {
3857                 window_schedule_resize(window,
3858                                        window->saved_allocation.width,
3859                                        window->saved_allocation.height);
3860         }
3861
3862         xdg_surface_ack_configure(window->xdg_surface, serial);
3863
3864         if (window->state_changed_handler)
3865                 window->state_changed_handler(window, window->user_data);
3866 }
3867
3868 static void
3869 handle_surface_delete(void *data, struct xdg_surface *xdg_surface)
3870 {
3871         struct window *window = data;
3872         window_close(window);
3873 }
3874
3875 static const struct xdg_surface_listener xdg_surface_listener = {
3876         handle_surface_configure,
3877         handle_surface_delete,
3878 };
3879
3880 static void
3881 window_sync_parent(struct window *window)
3882 {
3883         struct wl_surface *parent_surface;
3884
3885         if (!window->xdg_surface)
3886                 return;
3887
3888         if (window->parent)
3889                 parent_surface = window->parent->main_surface->surface;
3890         else
3891                 parent_surface = NULL;
3892
3893         xdg_surface_set_parent(window->xdg_surface, parent_surface);
3894 }
3895
3896 static void
3897 window_get_geometry(struct window *window, struct rectangle *geometry)
3898 {
3899         if (window->frame)
3900                 frame_input_rect(window->frame->frame,
3901                                  &geometry->x,
3902                                  &geometry->y,
3903                                  &geometry->width,
3904                                  &geometry->height);
3905         else
3906                 window_get_allocation(window, geometry);
3907 }
3908
3909 static void
3910 window_sync_geometry(struct window *window)
3911 {
3912         struct rectangle geometry;
3913
3914         if (!window->xdg_surface)
3915                 return;
3916
3917         window_get_geometry(window, &geometry);
3918
3919         xdg_surface_set_window_geometry(window->xdg_surface,
3920                                         geometry.x,
3921                                         geometry.y,
3922                                         geometry.width,
3923                                         geometry.height);
3924 }
3925
3926 static void
3927 window_flush(struct window *window)
3928 {
3929         struct surface *surface;
3930
3931         if (!window->custom) {
3932                 if (window->xdg_surface) {
3933                         window_sync_parent(window);
3934                         window_sync_geometry(window);
3935                 }
3936         }
3937
3938         wl_list_for_each(surface, &window->subsurface_list, link) {
3939                 if (surface == window->main_surface)
3940                         continue;
3941
3942                 surface_flush(surface);
3943         }
3944
3945         surface_flush(window->main_surface);
3946 }
3947
3948 static void
3949 menu_destroy(struct menu *menu)
3950 {
3951         widget_destroy(menu->widget);
3952         window_destroy(menu->window);
3953         frame_destroy(menu->frame);
3954         free(menu);
3955 }
3956
3957 void
3958 window_get_allocation(struct window *window,
3959                       struct rectangle *allocation)
3960 {
3961         *allocation = window->main_surface->allocation;
3962 }
3963
3964 static void
3965 widget_redraw(struct widget *widget)
3966 {
3967         struct widget *child;
3968
3969         if (widget->redraw_handler)
3970                 widget->redraw_handler(widget, widget->user_data);
3971         wl_list_for_each(child, &widget->child_list, link)
3972                 widget_redraw(child);
3973 }
3974
3975 static void
3976 frame_callback(void *data, struct wl_callback *callback, uint32_t time)
3977 {
3978         struct surface *surface = data;
3979
3980         assert(callback == surface->frame_cb);
3981         DBG_OBJ(callback, "done\n");
3982         wl_callback_destroy(callback);
3983         surface->frame_cb = NULL;
3984
3985         surface->last_time = time;
3986
3987         if (surface->redraw_needed || surface->window->redraw_needed) {
3988                 DBG_OBJ(surface->surface, "window_schedule_redraw_task\n");
3989                 window_schedule_redraw_task(surface->window);
3990         }
3991 }
3992
3993 static const struct wl_callback_listener listener = {
3994         frame_callback
3995 };
3996
3997 static int
3998 surface_redraw(struct surface *surface)
3999 {
4000         DBG_OBJ(surface->surface, "begin\n");
4001
4002         if (!surface->window->redraw_needed && !surface->redraw_needed)
4003                 return 0;
4004
4005         /* Whole-window redraw forces a redraw even if the previous has
4006          * not yet hit the screen.
4007          */
4008         if (surface->frame_cb) {
4009                 if (!surface->window->redraw_needed)
4010                         return 0;
4011
4012                 DBG_OBJ(surface->frame_cb, "cancelled\n");
4013                 wl_callback_destroy(surface->frame_cb);
4014         }
4015
4016         if (surface->widget->use_cairo &&
4017             !widget_get_cairo_surface(surface->widget)) {
4018                 DBG_OBJ(surface->surface, "cancelled due buffer failure\n");
4019                 return -1;
4020         }
4021
4022         surface->frame_cb = wl_surface_frame(surface->surface);
4023         wl_callback_add_listener(surface->frame_cb, &listener, surface);
4024         DBG_OBJ(surface->frame_cb, "new\n");
4025
4026         surface->redraw_needed = 0;
4027         DBG_OBJ(surface->surface, "-> widget_redraw\n");
4028         widget_redraw(surface->widget);
4029         DBG_OBJ(surface->surface, "done\n");
4030         return 0;
4031 }
4032
4033 static void
4034 idle_redraw(struct task *task, uint32_t events)
4035 {
4036         struct window *window = container_of(task, struct window, redraw_task);
4037         struct surface *surface;
4038         int failed = 0;
4039         int resized = 0;
4040
4041         DBG(" --------- \n");
4042
4043         wl_list_init(&window->redraw_task.link);
4044         window->redraw_task_scheduled = 0;
4045
4046         if (window->resize_needed) {
4047                 /* throttle resizing to the main surface display */
4048                 if (window->main_surface->frame_cb) {
4049                         DBG_OBJ(window->main_surface->frame_cb, "pending\n");
4050                         return;
4051                 }
4052
4053                 idle_resize(window);
4054                 resized = 1;
4055         }
4056
4057         if (surface_redraw(window->main_surface) < 0) {
4058                 /*
4059                  * Only main_surface failure will cause us to undo the resize.
4060                  * If sub-surfaces fail, they will just be broken with old
4061                  * content.
4062                  */
4063                 failed = 1;
4064         } else {
4065                 wl_list_for_each(surface, &window->subsurface_list, link) {
4066                         if (surface == window->main_surface)
4067                                 continue;
4068
4069                         surface_redraw(surface);
4070                 }
4071         }
4072
4073         window->redraw_needed = 0;
4074         window_flush(window);
4075
4076         wl_list_for_each(surface, &window->subsurface_list, link)
4077                 surface_set_synchronized_default(surface);
4078
4079         if (resized && failed) {
4080                 /* Restore widget tree to correspond to what is on screen. */
4081                 undo_resize(window);
4082         }
4083 }
4084
4085 static void
4086 window_schedule_redraw_task(struct window *window)
4087 {
4088         if (!window->redraw_task_scheduled) {
4089                 window->redraw_task.run = idle_redraw;
4090                 display_defer(window->display, &window->redraw_task);
4091                 window->redraw_task_scheduled = 1;
4092         }
4093 }
4094
4095 void
4096 window_schedule_redraw(struct window *window)
4097 {
4098         struct surface *surface;
4099
4100         DBG_OBJ(window->main_surface->surface, "window %p\n", window);
4101
4102         wl_list_for_each(surface, &window->subsurface_list, link)
4103                 surface->redraw_needed = 1;
4104
4105         window_schedule_redraw_task(window);
4106 }
4107
4108 int
4109 window_is_fullscreen(struct window *window)
4110 {
4111         return window->fullscreen;
4112 }
4113
4114 void
4115 window_set_fullscreen(struct window *window, int fullscreen)
4116 {
4117         if (!window->xdg_surface)
4118                 return;
4119
4120         if (window->fullscreen == fullscreen)
4121                 return;
4122
4123         if (fullscreen)
4124                 xdg_surface_set_fullscreen(window->xdg_surface, NULL);
4125         else
4126                 xdg_surface_unset_fullscreen(window->xdg_surface);
4127 }
4128
4129 int
4130 window_is_maximized(struct window *window)
4131 {
4132         return window->maximized;
4133 }
4134
4135 void
4136 window_set_maximized(struct window *window, int maximized)
4137 {
4138         if (!window->xdg_surface)
4139                 return;
4140
4141         if (window->maximized == maximized)
4142                 return;
4143
4144         if (maximized)
4145                 xdg_surface_set_maximized(window->xdg_surface);
4146         else
4147                 xdg_surface_unset_maximized(window->xdg_surface);
4148 }
4149
4150 int
4151 window_is_resizing(struct window *window)
4152 {
4153         return window->resizing;
4154 }
4155
4156 void
4157 window_set_minimized(struct window *window)
4158 {
4159         if (!window->xdg_surface)
4160                 return;
4161
4162         xdg_surface_set_minimized(window->xdg_surface);
4163 }
4164
4165 void
4166 window_set_user_data(struct window *window, void *data)
4167 {
4168         window->user_data = data;
4169 }
4170
4171 void *
4172 window_get_user_data(struct window *window)
4173 {
4174         return window->user_data;
4175 }
4176
4177 void
4178 window_set_key_handler(struct window *window,
4179                        window_key_handler_t handler)
4180 {
4181         window->key_handler = handler;
4182 }
4183
4184 void
4185 window_set_keyboard_focus_handler(struct window *window,
4186                                   window_keyboard_focus_handler_t handler)
4187 {
4188         window->keyboard_focus_handler = handler;
4189 }
4190
4191 void
4192 window_set_data_handler(struct window *window, window_data_handler_t handler)
4193 {
4194         window->data_handler = handler;
4195 }
4196
4197 void
4198 window_set_drop_handler(struct window *window, window_drop_handler_t handler)
4199 {
4200         window->drop_handler = handler;
4201 }
4202
4203 void
4204 window_set_close_handler(struct window *window,
4205                          window_close_handler_t handler)
4206 {
4207         window->close_handler = handler;
4208 }
4209
4210 void
4211 window_set_fullscreen_handler(struct window *window,
4212                               window_fullscreen_handler_t handler)
4213 {
4214         window->fullscreen_handler = handler;
4215 }
4216
4217 void
4218 window_set_output_handler(struct window *window,
4219                           window_output_handler_t handler)
4220 {
4221         window->output_handler = handler;
4222 }
4223
4224 void
4225 window_set_state_changed_handler(struct window *window,
4226                                  window_state_changed_handler_t handler)
4227 {
4228         window->state_changed_handler = handler;
4229 }
4230
4231 void
4232 window_set_title(struct window *window, const char *title)
4233 {
4234         free(window->title);
4235         window->title = strdup(title);
4236         if (window->frame) {
4237                 frame_set_title(window->frame->frame, title);
4238                 widget_schedule_redraw(window->frame->widget);
4239         }
4240         if (window->xdg_surface)
4241                 xdg_surface_set_title(window->xdg_surface, title);
4242 }
4243
4244 const char *
4245 window_get_title(struct window *window)
4246 {
4247         return window->title;
4248 }
4249
4250 void
4251 window_set_text_cursor_position(struct window *window, int32_t x, int32_t y)
4252 {
4253         struct text_cursor_position *text_cursor_position =
4254                                         window->display->text_cursor_position;
4255
4256         if (!text_cursor_position)
4257                 return;
4258
4259         text_cursor_position_notify(text_cursor_position,
4260                                     window->main_surface->surface,
4261                                     wl_fixed_from_int(x),
4262                                     wl_fixed_from_int(y));
4263 }
4264
4265 void
4266 window_damage(struct window *window, int32_t x, int32_t y,
4267               int32_t width, int32_t height)
4268 {
4269         wl_surface_damage(window->main_surface->surface, x, y, width, height);
4270 }
4271
4272 static void
4273 surface_enter(void *data,
4274               struct wl_surface *wl_surface, struct wl_output *wl_output)
4275 {
4276         struct window *window = data;
4277         struct output *output;
4278         struct output *output_found = NULL;
4279         struct window_output *window_output;
4280
4281         wl_list_for_each(output, &window->display->output_list, link) {
4282                 if (output->output == wl_output) {
4283                         output_found = output;
4284                         break;
4285                 }
4286         }
4287
4288         if (!output_found)
4289                 return;
4290
4291         window_output = xmalloc(sizeof *window_output);
4292         window_output->output = output_found;
4293
4294         wl_list_insert (&window->window_output_list, &window_output->link);
4295
4296         if (window->output_handler)
4297                 window->output_handler(window, output_found, 1,
4298                                        window->user_data);
4299 }
4300
4301 static void
4302 surface_leave(void *data,
4303               struct wl_surface *wl_surface, struct wl_output *output)
4304 {
4305         struct window *window = data;
4306         struct window_output *window_output;
4307         struct window_output *window_output_found = NULL;
4308
4309         wl_list_for_each(window_output, &window->window_output_list, link) {
4310                 if (window_output->output->output == output) {
4311                         window_output_found = window_output;
4312                         break;
4313                 }
4314         }
4315
4316         if (window_output_found) {
4317                 wl_list_remove(&window_output_found->link);
4318
4319                 if (window->output_handler)
4320                         window->output_handler(window, window_output->output,
4321                                                0, window->user_data);
4322
4323                 free(window_output_found);
4324         }
4325 }
4326
4327 static const struct wl_surface_listener surface_listener = {
4328         surface_enter,
4329         surface_leave
4330 };
4331
4332 static struct surface *
4333 surface_create(struct window *window)
4334 {
4335         struct display *display = window->display;
4336         struct surface *surface;
4337
4338         surface = xmalloc(sizeof *surface);
4339         memset(surface, 0, sizeof *surface);
4340         if (!surface)
4341                 return NULL;
4342
4343         surface->window = window;
4344         surface->surface = wl_compositor_create_surface(display->compositor);
4345         surface->buffer_scale = 1;
4346         wl_surface_add_listener(surface->surface, &surface_listener, window);
4347
4348         wl_list_insert(&window->subsurface_list, &surface->link);
4349
4350         return surface;
4351 }
4352
4353 static enum window_buffer_type
4354 get_preferred_buffer_type(struct display *display)
4355 {
4356 #ifdef HAVE_CAIRO_EGL
4357         if (display->argb_device && !getenv("TOYTOOLKIT_NO_EGL"))
4358                 return WINDOW_BUFFER_TYPE_EGL_WINDOW;
4359 #endif
4360
4361         return WINDOW_BUFFER_TYPE_SHM;
4362 }
4363
4364 static struct window *
4365 window_create_internal(struct display *display, int custom)
4366 {
4367         struct window *window;
4368         struct surface *surface;
4369
4370         window = xzalloc(sizeof *window);
4371         wl_list_init(&window->subsurface_list);
4372         window->display = display;
4373
4374         surface = surface_create(window);
4375         window->main_surface = surface;
4376
4377         assert(custom || display->xdg_shell);
4378
4379         window->custom = custom;
4380         window->preferred_format = WINDOW_PREFERRED_FORMAT_NONE;
4381
4382         surface->buffer_type = get_preferred_buffer_type(display);
4383
4384         wl_surface_set_user_data(surface->surface, window);
4385         wl_list_insert(display->window_list.prev, &window->link);
4386         wl_list_init(&window->redraw_task.link);
4387
4388         wl_list_init (&window->window_output_list);
4389
4390         return window;
4391 }
4392
4393 struct window *
4394 window_create(struct display *display)
4395 {
4396         struct window *window;
4397
4398         window = window_create_internal(display, 0);
4399
4400         window->xdg_surface =
4401                 xdg_shell_get_xdg_surface(window->display->xdg_shell,
4402                                           window->main_surface->surface);
4403         fail_on_null(window->xdg_surface);
4404
4405         xdg_surface_set_user_data(window->xdg_surface, window);
4406         xdg_surface_add_listener(window->xdg_surface,
4407                                  &xdg_surface_listener, window);
4408
4409         return window;
4410 }
4411
4412 struct window *
4413 window_create_custom(struct display *display)
4414 {
4415         return window_create_internal(display, 1);
4416 }
4417
4418 void
4419 window_set_parent(struct window *window,
4420                   struct window *parent_window)
4421 {
4422         window->parent = parent_window;
4423         window_sync_parent(window);
4424 }
4425
4426 struct window *
4427 window_get_parent(struct window *window)
4428 {
4429         return window->parent;
4430 }
4431
4432 static void
4433 menu_set_item(struct menu *menu, int sy)
4434 {
4435         int32_t x, y, width, height;
4436         int next;
4437
4438         frame_interior(menu->frame, &x, &y, &width, &height);
4439         next = (sy - y) / 20;
4440         if (menu->current != next) {
4441                 menu->current = next;
4442                 widget_schedule_redraw(menu->widget);
4443         }
4444 }
4445
4446 static int
4447 menu_motion_handler(struct widget *widget,
4448                     struct input *input, uint32_t time,
4449                     float x, float y, void *data)
4450 {
4451         struct menu *menu = data;
4452
4453         if (widget == menu->widget)
4454                 menu_set_item(data, y);
4455
4456         return CURSOR_LEFT_PTR;
4457 }
4458
4459 static int
4460 menu_enter_handler(struct widget *widget,
4461                    struct input *input, float x, float y, void *data)
4462 {
4463         struct menu *menu = data;
4464
4465         if (widget == menu->widget)
4466                 menu_set_item(data, y);
4467
4468         return CURSOR_LEFT_PTR;
4469 }
4470
4471 static void
4472 menu_leave_handler(struct widget *widget, struct input *input, void *data)
4473 {
4474         struct menu *menu = data;
4475
4476         if (widget == menu->widget)
4477                 menu_set_item(data, -200);
4478 }
4479
4480 static void
4481 menu_button_handler(struct widget *widget,
4482                     struct input *input, uint32_t time,
4483                     uint32_t button, enum wl_pointer_button_state state,
4484                     void *data)
4485
4486 {
4487         struct menu *menu = data;
4488
4489         if (state == WL_POINTER_BUTTON_STATE_RELEASED &&
4490             (menu->release_count > 0 || time - menu->time > 500)) {
4491                 /* Either relase after press-drag-release or
4492                  * click-motion-click. */
4493                 menu->func(menu->user_data, input, menu->current);
4494                 input_ungrab(input);
4495                 menu_destroy(menu);
4496         } else if (state == WL_POINTER_BUTTON_STATE_RELEASED) {
4497                 menu->release_count++;
4498         }
4499 }
4500
4501 static void
4502 menu_touch_up_handler(struct widget *widget,
4503                                           struct input *input,
4504                                           uint32_t serial,
4505                                           uint32_t time,
4506                                           int32_t id,
4507                                           void *data)
4508 {
4509         struct menu *menu = data;
4510
4511         input_ungrab(input);
4512         menu_destroy(menu);
4513 }
4514
4515 static void
4516 menu_redraw_handler(struct widget *widget, void *data)
4517 {
4518         cairo_t *cr;
4519         struct menu *menu = data;
4520         int32_t x, y, width, height, i;
4521
4522         cr = widget_cairo_create(widget);
4523
4524         frame_repaint(menu->frame, cr);
4525         frame_interior(menu->frame, &x, &y, &width, &height);
4526
4527         theme_set_background_source(menu->window->display->theme,
4528                                     cr, THEME_FRAME_ACTIVE);
4529         cairo_rectangle(cr, x, y, width, height);
4530         cairo_fill(cr);
4531
4532         cairo_select_font_face(cr, "sans",
4533                                CAIRO_FONT_SLANT_NORMAL,
4534                                CAIRO_FONT_WEIGHT_NORMAL);
4535         cairo_set_font_size(cr, 12);
4536
4537         for (i = 0; i < menu->count; i++) {
4538                 if (i == menu->current) {
4539                         cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
4540                         cairo_rectangle(cr, x, y + i * 20, width, 20);
4541                         cairo_fill(cr);
4542                         cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
4543                         cairo_move_to(cr, x + 10, y + i * 20 + 16);
4544                         cairo_show_text(cr, menu->entries[i]);
4545                 } else {
4546                         cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
4547                         cairo_move_to(cr, x + 10, y + i * 20 + 16);
4548                         cairo_show_text(cr, menu->entries[i]);
4549                 }
4550         }
4551
4552         cairo_destroy(cr);
4553 }
4554
4555 static void
4556 handle_popup_popup_done(void *data, struct xdg_popup *xdg_popup, uint32_t serial)
4557 {
4558         struct window *window = data;
4559         struct menu *menu = window->main_surface->widget->user_data;
4560
4561         input_ungrab(menu->input);
4562         menu_destroy(menu);
4563 }
4564
4565 static const struct xdg_popup_listener xdg_popup_listener = {
4566         handle_popup_popup_done,
4567 };
4568
4569 static struct menu *
4570 create_menu(struct display *display,
4571             struct input *input, uint32_t time,
4572             menu_func_t func, const char **entries, int count,
4573             void *user_data)
4574 {
4575         struct window *window;
4576         struct menu *menu;
4577
4578         menu = malloc(sizeof *menu);
4579         if (!menu)
4580                 return NULL;
4581
4582         window = window_create_internal(display, 0);
4583         if (!window) {
4584                 free(menu);
4585                 return NULL;
4586         }
4587
4588         menu->window = window;
4589         menu->user_data = user_data;
4590         menu->widget = window_add_widget(menu->window, menu);
4591         menu->frame = frame_create(window->display->theme, 0, 0,
4592                                    FRAME_BUTTON_NONE, NULL);
4593         fail_on_null(menu->frame);
4594         menu->entries = entries;
4595         menu->count = count;
4596         menu->release_count = 0;
4597         menu->current = -1;
4598         menu->time = time;
4599         menu->func = func;
4600         menu->input = input;
4601
4602         input_ungrab(input);
4603
4604         widget_set_redraw_handler(menu->widget, menu_redraw_handler);
4605         widget_set_enter_handler(menu->widget, menu_enter_handler);
4606         widget_set_leave_handler(menu->widget, menu_leave_handler);
4607         widget_set_motion_handler(menu->widget, menu_motion_handler);
4608         widget_set_button_handler(menu->widget, menu_button_handler);
4609         widget_set_touch_up_handler(menu->widget, menu_touch_up_handler);
4610
4611         input_grab(input, menu->widget, 0);
4612         frame_resize_inside(menu->frame, 200, count * 20);
4613         frame_set_flag(menu->frame, FRAME_FLAG_ACTIVE);
4614         window_schedule_resize(window, frame_width(menu->frame),
4615                                frame_height(menu->frame));
4616
4617         return menu;
4618 }
4619
4620 struct window *
4621 window_create_menu(struct display *display,
4622                    struct input *input, uint32_t time,
4623                    menu_func_t func, const char **entries, int count,
4624                    void *user_data)
4625 {
4626         struct menu *menu;
4627         menu = create_menu(display, input, time, func, entries, count, user_data);
4628
4629         if (menu == NULL)
4630                 return NULL;
4631
4632         return menu->window;
4633 }
4634
4635 void
4636 window_show_menu(struct display *display,
4637                  struct input *input, uint32_t time, struct window *parent,
4638                  int32_t x, int32_t y,
4639                  menu_func_t func, const char **entries, int count)
4640 {
4641         struct menu *menu;
4642         struct window *window;
4643         int32_t ix, iy;
4644
4645         menu = create_menu(display, input, time, func, entries, count, parent);
4646
4647         if (menu == NULL)
4648                 return;
4649
4650         window = menu->window;
4651
4652         window_set_buffer_scale (menu->window, window_get_buffer_scale (parent));
4653         window_set_buffer_transform (menu->window, window_get_buffer_transform (parent));
4654
4655         window->x = x;
4656         window->y = y;
4657
4658         frame_interior(menu->frame, &ix, &iy, NULL, NULL);
4659
4660         window->xdg_popup = xdg_shell_get_xdg_popup(display->xdg_shell,
4661                                                     window->main_surface->surface,
4662                                                     parent->main_surface->surface,
4663                                                     input->seat,
4664                                                     display_get_serial(window->display),
4665                                                     window->x - ix,
4666                                                     window->y - iy,
4667                                                     0);
4668         fail_on_null(window->xdg_popup);
4669
4670         xdg_popup_set_user_data(window->xdg_popup, window);
4671         xdg_popup_add_listener(window->xdg_popup,
4672                                &xdg_popup_listener, window);
4673 }
4674
4675 void
4676 window_set_buffer_type(struct window *window, enum window_buffer_type type)
4677 {
4678         window->main_surface->buffer_type = type;
4679 }
4680
4681 enum window_buffer_type
4682 window_get_buffer_type(struct window *window)
4683 {
4684         return window->main_surface->buffer_type;
4685 }
4686
4687 void
4688 window_set_preferred_format(struct window *window,
4689                             enum preferred_format format)
4690 {
4691         window->preferred_format = format;
4692 }
4693
4694 struct widget *
4695 window_add_subsurface(struct window *window, void *data,
4696                       enum subsurface_mode default_mode)
4697 {
4698         struct widget *widget;
4699         struct surface *surface;
4700         struct wl_surface *parent;
4701         struct wl_subcompositor *subcompo = window->display->subcompositor;
4702
4703         surface = surface_create(window);
4704         surface->buffer_type = window_get_buffer_type(window);
4705         widget = widget_create(window, surface, data);
4706         wl_list_init(&widget->link);
4707         surface->widget = widget;
4708
4709         parent = window->main_surface->surface;
4710         surface->subsurface = wl_subcompositor_get_subsurface(subcompo,
4711                                                               surface->surface,
4712                                                               parent);
4713         surface->synchronized = 1;
4714
4715         switch (default_mode) {
4716         case SUBSURFACE_SYNCHRONIZED:
4717                 surface->synchronized_default = 1;
4718                 break;
4719         case SUBSURFACE_DESYNCHRONIZED:
4720                 surface->synchronized_default = 0;
4721                 break;
4722         default:
4723                 assert(!"bad enum subsurface_mode");
4724         }
4725
4726         window->resize_needed = 1;
4727         window_schedule_redraw(window);
4728
4729         return widget;
4730 }
4731
4732 static void
4733 display_handle_geometry(void *data,
4734                         struct wl_output *wl_output,
4735                         int x, int y,
4736                         int physical_width,
4737                         int physical_height,
4738                         int subpixel,
4739                         const char *make,
4740                         const char *model,
4741                         int transform)
4742 {
4743         struct output *output = data;
4744
4745         output->allocation.x = x;
4746         output->allocation.y = y;
4747         output->transform = transform;
4748
4749         if (output->make)
4750                 free(output->make);
4751         output->make = strdup(make);
4752
4753         if (output->model)
4754                 free(output->model);
4755         output->model = strdup(model);
4756 }
4757
4758 static void
4759 display_handle_done(void *data,
4760                      struct wl_output *wl_output)
4761 {
4762 }
4763
4764 static void
4765 display_handle_scale(void *data,
4766                      struct wl_output *wl_output,
4767                      int32_t scale)
4768 {
4769         struct output *output = data;
4770
4771         output->scale = scale;
4772 }
4773
4774 static void
4775 display_handle_mode(void *data,
4776                     struct wl_output *wl_output,
4777                     uint32_t flags,
4778                     int width,
4779                     int height,
4780                     int refresh)
4781 {
4782         struct output *output = data;
4783         struct display *display = output->display;
4784
4785         if (flags & WL_OUTPUT_MODE_CURRENT) {
4786                 output->allocation.width = width;
4787                 output->allocation.height = height;
4788                 if (display->output_configure_handler)
4789                         (*display->output_configure_handler)(
4790                                                 output, display->user_data);
4791         }
4792 }
4793
4794 static const struct wl_output_listener output_listener = {
4795         display_handle_geometry,
4796         display_handle_mode,
4797         display_handle_done,
4798         display_handle_scale
4799 };
4800
4801 static void
4802 display_add_output(struct display *d, uint32_t id)
4803 {
4804         struct output *output;
4805
4806         output = xzalloc(sizeof *output);
4807         output->display = d;
4808         output->scale = 1;
4809         output->output =
4810                 wl_registry_bind(d->registry, id, &wl_output_interface, 2);
4811         output->server_output_id = id;
4812         wl_list_insert(d->output_list.prev, &output->link);
4813
4814         wl_output_add_listener(output->output, &output_listener, output);
4815 }
4816
4817 static void
4818 output_destroy(struct output *output)
4819 {
4820         if (output->destroy_handler)
4821                 (*output->destroy_handler)(output, output->user_data);
4822
4823         wl_output_destroy(output->output);
4824         wl_list_remove(&output->link);
4825         free(output);
4826 }
4827
4828 static void
4829 display_destroy_output(struct display *d, uint32_t id)
4830 {
4831         struct output *output;
4832
4833         wl_list_for_each(output, &d->output_list, link) {
4834                 if (output->server_output_id == id) {
4835                         output_destroy(output);
4836                         break;
4837                 }
4838         }
4839 }
4840
4841 void
4842 display_set_global_handler(struct display *display,
4843                            display_global_handler_t handler)
4844 {
4845         struct global *global;
4846
4847         display->global_handler = handler;
4848         if (!handler)
4849                 return;
4850
4851         wl_list_for_each(global, &display->global_list, link)
4852                 display->global_handler(display,
4853                                         global->name, global->interface,
4854                                         global->version, display->user_data);
4855 }
4856
4857 void
4858 display_set_global_handler_remove(struct display *display,
4859                            display_global_handler_t remove_handler)
4860 {
4861         display->global_handler_remove = remove_handler;
4862         if (!remove_handler)
4863                 return;
4864 }
4865
4866 void
4867 display_set_output_configure_handler(struct display *display,
4868                                      display_output_handler_t handler)
4869 {
4870         struct output *output;
4871
4872         display->output_configure_handler = handler;
4873         if (!handler)
4874                 return;
4875
4876         wl_list_for_each(output, &display->output_list, link) {
4877                 if (output->allocation.width == 0 &&
4878                     output->allocation.height == 0)
4879                         continue;
4880
4881                 (*display->output_configure_handler)(output,
4882                                                      display->user_data);
4883         }
4884 }
4885
4886 void
4887 output_set_user_data(struct output *output, void *data)
4888 {
4889         output->user_data = data;
4890 }
4891
4892 void *
4893 output_get_user_data(struct output *output)
4894 {
4895         return output->user_data;
4896 }
4897
4898 void
4899 output_set_destroy_handler(struct output *output,
4900                            display_output_handler_t handler)
4901 {
4902         output->destroy_handler = handler;
4903         /* FIXME: implement this, once we have way to remove outputs */
4904 }
4905
4906 void
4907 output_get_allocation(struct output *output, struct rectangle *base)
4908 {
4909         struct rectangle allocation = output->allocation;
4910
4911         switch (output->transform) {
4912         case WL_OUTPUT_TRANSFORM_90:
4913         case WL_OUTPUT_TRANSFORM_270:
4914         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
4915         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
4916                 /* Swap width and height */
4917                 allocation.width = output->allocation.height;
4918                 allocation.height = output->allocation.width;
4919                 break;
4920         }
4921
4922         *base = allocation;
4923 }
4924
4925 struct wl_output *
4926 output_get_wl_output(struct output *output)
4927 {
4928         return output->output;
4929 }
4930
4931 enum wl_output_transform
4932 output_get_transform(struct output *output)
4933 {
4934         return output->transform;
4935 }
4936
4937 uint32_t
4938 output_get_scale(struct output *output)
4939 {
4940         return output->scale;
4941 }
4942
4943 const char *
4944 output_get_make(struct output *output)
4945 {
4946         return output->make;
4947 }
4948
4949 const char *
4950 output_get_model(struct output *output)
4951 {
4952         return output->model;
4953 }
4954
4955 static void
4956 fini_xkb(struct input *input)
4957 {
4958         xkb_state_unref(input->xkb.state);
4959         xkb_map_unref(input->xkb.keymap);
4960 }
4961
4962 #define MIN(a,b) ((a) < (b) ? a : b)
4963
4964 static void
4965 display_add_input(struct display *d, uint32_t id)
4966 {
4967         struct input *input;
4968
4969         input = xzalloc(sizeof *input);
4970         input->display = d;
4971         input->seat = wl_registry_bind(d->registry, id, &wl_seat_interface,
4972                                        MIN(d->seat_version, 3));
4973         input->touch_focus = NULL;
4974         input->pointer_focus = NULL;
4975         input->keyboard_focus = NULL;
4976         wl_list_init(&input->touch_point_list);
4977         wl_list_insert(d->input_list.prev, &input->link);
4978
4979         wl_seat_add_listener(input->seat, &seat_listener, input);
4980         wl_seat_set_user_data(input->seat, input);
4981
4982         if (d->data_device_manager) {
4983                 input->data_device =
4984                         wl_data_device_manager_get_data_device(d->data_device_manager,
4985                                                                input->seat);
4986                 wl_data_device_add_listener(input->data_device,
4987                                             &data_device_listener,
4988                                             input);
4989         }
4990
4991         input->pointer_surface = wl_compositor_create_surface(d->compositor);
4992
4993         input->repeat_timer_fd = timerfd_create(CLOCK_MONOTONIC,
4994                                                 TFD_CLOEXEC | TFD_NONBLOCK);
4995         input->repeat_task.run = keyboard_repeat_func;
4996         display_watch_fd(d, input->repeat_timer_fd,
4997                          EPOLLIN, &input->repeat_task);
4998 }
4999
5000 static void
5001 input_destroy(struct input *input)
5002 {
5003         input_remove_keyboard_focus(input);
5004         input_remove_pointer_focus(input);
5005
5006         if (input->drag_offer)
5007                 data_offer_destroy(input->drag_offer);
5008
5009         if (input->selection_offer)
5010                 data_offer_destroy(input->selection_offer);
5011
5012         if (input->data_device)
5013                 wl_data_device_destroy(input->data_device);
5014
5015         if (input->display->seat_version >= 3) {
5016                 if (input->pointer)
5017                         wl_pointer_release(input->pointer);
5018                 if (input->keyboard)
5019                         wl_keyboard_release(input->keyboard);
5020         }
5021
5022         fini_xkb(input);
5023
5024         wl_surface_destroy(input->pointer_surface);
5025
5026         wl_list_remove(&input->link);
5027         wl_seat_destroy(input->seat);
5028         close(input->repeat_timer_fd);
5029         free(input);
5030 }
5031
5032 static void
5033 init_workspace_manager(struct display *d, uint32_t id)
5034 {
5035         d->workspace_manager =
5036                 wl_registry_bind(d->registry, id,
5037                                  &workspace_manager_interface, 1);
5038         if (d->workspace_manager != NULL)
5039                 workspace_manager_add_listener(d->workspace_manager,
5040                                                &workspace_manager_listener,
5041                                                d);
5042 }
5043
5044 static void
5045 shm_format(void *data, struct wl_shm *wl_shm, uint32_t format)
5046 {
5047         struct display *d = data;
5048
5049         if (format == WL_SHM_FORMAT_RGB565)
5050                 d->has_rgb565 = 1;
5051 }
5052
5053 struct wl_shm_listener shm_listener = {
5054         shm_format
5055 };
5056
5057 static void
5058 xdg_shell_ping(void *data, struct xdg_shell *shell, uint32_t serial)
5059 {
5060         xdg_shell_pong(shell, serial);
5061 }
5062
5063 static const struct xdg_shell_listener xdg_shell_listener = {
5064         xdg_shell_ping,
5065 };
5066
5067 #define XDG_VERSION 3 /* The version of xdg-shell that we implement */
5068 #ifdef static_assert
5069 static_assert(XDG_VERSION == XDG_SHELL_VERSION_CURRENT,
5070               "Interface version doesn't match implementation version");
5071 #endif
5072
5073 static void
5074 registry_handle_global(void *data, struct wl_registry *registry, uint32_t id,
5075                        const char *interface, uint32_t version)
5076 {
5077         struct display *d = data;
5078         struct global *global;
5079
5080         global = xmalloc(sizeof *global);
5081         global->name = id;
5082         global->interface = strdup(interface);
5083         global->version = version;
5084         wl_list_insert(d->global_list.prev, &global->link);
5085
5086         if (strcmp(interface, "wl_compositor") == 0) {
5087                 d->compositor = wl_registry_bind(registry, id,
5088                                                  &wl_compositor_interface, 3);
5089         } else if (strcmp(interface, "wl_output") == 0) {
5090                 display_add_output(d, id);
5091         } else if (strcmp(interface, "wl_seat") == 0) {
5092                 d->seat_version = version;
5093                 display_add_input(d, id);
5094         } else if (strcmp(interface, "wl_shm") == 0) {
5095                 d->shm = wl_registry_bind(registry, id, &wl_shm_interface, 1);
5096                 wl_shm_add_listener(d->shm, &shm_listener, d);
5097         } else if (strcmp(interface, "wl_data_device_manager") == 0) {
5098                 d->data_device_manager =
5099                         wl_registry_bind(registry, id,
5100                                          &wl_data_device_manager_interface, 1);
5101         } else if (strcmp(interface, "xdg_shell") == 0) {
5102                 d->xdg_shell = wl_registry_bind(registry, id,
5103                                                 &xdg_shell_interface, 1);
5104                 xdg_shell_use_unstable_version(d->xdg_shell, XDG_VERSION);
5105                 xdg_shell_add_listener(d->xdg_shell, &xdg_shell_listener, d);
5106         } else if (strcmp(interface, "text_cursor_position") == 0) {
5107                 d->text_cursor_position =
5108                         wl_registry_bind(registry, id,
5109                                          &text_cursor_position_interface, 1);
5110         } else if (strcmp(interface, "workspace_manager") == 0) {
5111                 init_workspace_manager(d, id);
5112         } else if (strcmp(interface, "wl_subcompositor") == 0) {
5113                 d->subcompositor =
5114                         wl_registry_bind(registry, id,
5115                                          &wl_subcompositor_interface, 1);
5116         }
5117
5118         if (d->global_handler)
5119                 d->global_handler(d, id, interface, version, d->user_data);
5120 }
5121
5122 static void
5123 registry_handle_global_remove(void *data, struct wl_registry *registry,
5124                               uint32_t name)
5125 {
5126         struct display *d = data;
5127         struct global *global;
5128         struct global *tmp;
5129
5130         wl_list_for_each_safe(global, tmp, &d->global_list, link) {
5131                 if (global->name != name)
5132                         continue;
5133
5134                 if (strcmp(global->interface, "wl_output") == 0)
5135                         display_destroy_output(d, name);
5136
5137                 /* XXX: Should destroy remaining bound globals */
5138
5139                 if (d->global_handler_remove)
5140                         d->global_handler_remove(d, name, global->interface,
5141                                         global->version, d->user_data);
5142
5143                 wl_list_remove(&global->link);
5144                 free(global->interface);
5145                 free(global);
5146         }
5147 }
5148
5149 void *
5150 display_bind(struct display *display, uint32_t name,
5151              const struct wl_interface *interface, uint32_t version)
5152 {
5153         return wl_registry_bind(display->registry, name, interface, version);
5154 }
5155
5156 static const struct wl_registry_listener registry_listener = {
5157         registry_handle_global,
5158         registry_handle_global_remove
5159 };
5160
5161 #ifdef HAVE_CAIRO_EGL
5162 static int
5163 init_egl(struct display *d)
5164 {
5165         EGLint major, minor;
5166         EGLint n;
5167
5168 #ifdef USE_CAIRO_GLESV2
5169 #  define GL_BIT EGL_OPENGL_ES2_BIT
5170 #else
5171 #  define GL_BIT EGL_OPENGL_BIT
5172 #endif
5173
5174         static const EGLint argb_cfg_attribs[] = {
5175                 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
5176                 EGL_RED_SIZE, 1,
5177                 EGL_GREEN_SIZE, 1,
5178                 EGL_BLUE_SIZE, 1,
5179                 EGL_ALPHA_SIZE, 1,
5180                 EGL_DEPTH_SIZE, 1,
5181                 EGL_RENDERABLE_TYPE, GL_BIT,
5182                 EGL_NONE
5183         };
5184
5185 #ifdef USE_CAIRO_GLESV2
5186         static const EGLint context_attribs[] = {
5187                 EGL_CONTEXT_CLIENT_VERSION, 2,
5188                 EGL_NONE
5189         };
5190         EGLint api = EGL_OPENGL_ES_API;
5191 #else
5192         EGLint *context_attribs = NULL;
5193         EGLint api = EGL_OPENGL_API;
5194 #endif
5195
5196         d->dpy = eglGetDisplay(d->display);
5197         if (!eglInitialize(d->dpy, &major, &minor)) {
5198                 fprintf(stderr, "failed to initialize EGL\n");
5199                 return -1;
5200         }
5201
5202         if (!eglBindAPI(api)) {
5203                 fprintf(stderr, "failed to bind EGL client API\n");
5204                 return -1;
5205         }
5206
5207         if (!eglChooseConfig(d->dpy, argb_cfg_attribs,
5208                              &d->argb_config, 1, &n) || n != 1) {
5209                 fprintf(stderr, "failed to choose argb EGL config\n");
5210                 return -1;
5211         }
5212
5213         d->argb_ctx = eglCreateContext(d->dpy, d->argb_config,
5214                                        EGL_NO_CONTEXT, context_attribs);
5215         if (d->argb_ctx == NULL) {
5216                 fprintf(stderr, "failed to create EGL context\n");
5217                 return -1;
5218         }
5219
5220         d->argb_device = cairo_egl_device_create(d->dpy, d->argb_ctx);
5221         if (cairo_device_status(d->argb_device) != CAIRO_STATUS_SUCCESS) {
5222                 fprintf(stderr, "failed to get cairo EGL argb device\n");
5223                 return -1;
5224         }
5225
5226         return 0;
5227 }
5228
5229 static void
5230 fini_egl(struct display *display)
5231 {
5232         cairo_device_destroy(display->argb_device);
5233
5234         eglMakeCurrent(display->dpy, EGL_NO_SURFACE, EGL_NO_SURFACE,
5235                        EGL_NO_CONTEXT);
5236
5237         eglTerminate(display->dpy);
5238         eglReleaseThread();
5239 }
5240 #endif
5241
5242 static void
5243 init_dummy_surface(struct display *display)
5244 {
5245         int len;
5246         void *data;
5247
5248         len = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, 1);
5249         data = malloc(len);
5250         display->dummy_surface =
5251                 cairo_image_surface_create_for_data(data, CAIRO_FORMAT_ARGB32,
5252                                                     1, 1, len);
5253         display->dummy_surface_data = data;
5254 }
5255
5256 static void
5257 handle_display_data(struct task *task, uint32_t events)
5258 {
5259         struct display *display =
5260                 container_of(task, struct display, display_task);
5261         struct epoll_event ep;
5262         int ret;
5263
5264         display->display_fd_events = events;
5265
5266         if (events & EPOLLERR || events & EPOLLHUP) {
5267                 display_exit(display);
5268                 return;
5269         }
5270
5271         if (events & EPOLLIN) {
5272                 ret = wl_display_dispatch(display->display);
5273                 if (ret == -1) {
5274                         display_exit(display);
5275                         return;
5276                 }
5277         }
5278
5279         if (events & EPOLLOUT) {
5280                 ret = wl_display_flush(display->display);
5281                 if (ret == 0) {
5282                         ep.events = EPOLLIN | EPOLLERR | EPOLLHUP;
5283                         ep.data.ptr = &display->display_task;
5284                         epoll_ctl(display->epoll_fd, EPOLL_CTL_MOD,
5285                                   display->display_fd, &ep);
5286                 } else if (ret == -1 && errno != EAGAIN) {
5287                         display_exit(display);
5288                         return;
5289                 }
5290         }
5291 }
5292
5293 static void
5294 log_handler(const char *format, va_list args)
5295 {
5296         vfprintf(stderr, format, args);
5297 }
5298
5299 struct display *
5300 display_create(int *argc, char *argv[])
5301 {
5302         struct display *d;
5303
5304         wl_log_set_handler_client(log_handler);
5305
5306         d = zalloc(sizeof *d);
5307         if (d == NULL)
5308                 return NULL;
5309
5310         d->display = wl_display_connect(NULL);
5311         if (d->display == NULL) {
5312                 fprintf(stderr, "failed to connect to Wayland display: %m\n");
5313                 free(d);
5314                 return NULL;
5315         }
5316
5317         d->xkb_context = xkb_context_new(0);
5318         if (d->xkb_context == NULL) {
5319                 fprintf(stderr, "Failed to create XKB context\n");
5320                 free(d);
5321                 return NULL;
5322         }
5323
5324         d->epoll_fd = os_epoll_create_cloexec();
5325         d->display_fd = wl_display_get_fd(d->display);
5326         d->display_task.run = handle_display_data;
5327         display_watch_fd(d, d->display_fd, EPOLLIN | EPOLLERR | EPOLLHUP,
5328                          &d->display_task);
5329
5330         wl_list_init(&d->deferred_list);
5331         wl_list_init(&d->input_list);
5332         wl_list_init(&d->output_list);
5333         wl_list_init(&d->global_list);
5334
5335         d->workspace = 0;
5336         d->workspace_count = 1;
5337
5338         d->registry = wl_display_get_registry(d->display);
5339         wl_registry_add_listener(d->registry, &registry_listener, d);
5340
5341         if (wl_display_dispatch(d->display) < 0) {
5342                 fprintf(stderr, "Failed to process Wayland connection: %m\n");
5343                 return NULL;
5344         }
5345
5346 #ifdef HAVE_CAIRO_EGL
5347         if (init_egl(d) < 0)
5348                 fprintf(stderr, "EGL does not seem to work, "
5349                         "falling back to software rendering and wl_shm.\n");
5350 #endif
5351
5352         create_cursors(d);
5353
5354         d->theme = theme_create();
5355
5356         wl_list_init(&d->window_list);
5357
5358         init_dummy_surface(d);
5359
5360         return d;
5361 }
5362
5363 static void
5364 display_destroy_outputs(struct display *display)
5365 {
5366         struct output *tmp;
5367         struct output *output;
5368
5369         wl_list_for_each_safe(output, tmp, &display->output_list, link)
5370                 output_destroy(output);
5371 }
5372
5373 static void
5374 display_destroy_inputs(struct display *display)
5375 {
5376         struct input *tmp;
5377         struct input *input;
5378
5379         wl_list_for_each_safe(input, tmp, &display->input_list, link)
5380                 input_destroy(input);
5381 }
5382
5383 void
5384 display_destroy(struct display *display)
5385 {
5386         if (!wl_list_empty(&display->window_list))
5387                 fprintf(stderr, "toytoolkit warning: %d windows exist.\n",
5388                         wl_list_length(&display->window_list));
5389
5390         if (!wl_list_empty(&display->deferred_list))
5391                 fprintf(stderr, "toytoolkit warning: deferred tasks exist.\n");
5392
5393         cairo_surface_destroy(display->dummy_surface);
5394         free(display->dummy_surface_data);
5395
5396         display_destroy_outputs(display);
5397         display_destroy_inputs(display);
5398
5399         xkb_context_unref(display->xkb_context);
5400
5401         theme_destroy(display->theme);
5402         destroy_cursors(display);
5403
5404 #ifdef HAVE_CAIRO_EGL
5405         if (display->argb_device)
5406                 fini_egl(display);
5407 #endif
5408
5409         if (display->subcompositor)
5410                 wl_subcompositor_destroy(display->subcompositor);
5411
5412         if (display->xdg_shell)
5413                 xdg_shell_destroy(display->xdg_shell);
5414
5415         if (display->shm)
5416                 wl_shm_destroy(display->shm);
5417
5418         if (display->data_device_manager)
5419                 wl_data_device_manager_destroy(display->data_device_manager);
5420
5421         wl_compositor_destroy(display->compositor);
5422         wl_registry_destroy(display->registry);
5423
5424         close(display->epoll_fd);
5425
5426         if (!(display->display_fd_events & EPOLLERR) &&
5427             !(display->display_fd_events & EPOLLHUP))
5428                 wl_display_flush(display->display);
5429
5430         wl_display_disconnect(display->display);
5431         free(display);
5432 }
5433
5434 void
5435 display_set_user_data(struct display *display, void *data)
5436 {
5437         display->user_data = data;
5438 }
5439
5440 void *
5441 display_get_user_data(struct display *display)
5442 {
5443         return display->user_data;
5444 }
5445
5446 struct wl_display *
5447 display_get_display(struct display *display)
5448 {
5449         return display->display;
5450 }
5451
5452 int
5453 display_has_subcompositor(struct display *display)
5454 {
5455         if (display->subcompositor)
5456                 return 1;
5457
5458         wl_display_roundtrip(display->display);
5459
5460         return display->subcompositor != NULL;
5461 }
5462
5463 cairo_device_t *
5464 display_get_cairo_device(struct display *display)
5465 {
5466         return display->argb_device;
5467 }
5468
5469 struct output *
5470 display_get_output(struct display *display)
5471 {
5472         return container_of(display->output_list.next, struct output, link);
5473 }
5474
5475 struct wl_compositor *
5476 display_get_compositor(struct display *display)
5477 {
5478         return display->compositor;
5479 }
5480
5481 uint32_t
5482 display_get_serial(struct display *display)
5483 {
5484         return display->serial;
5485 }
5486
5487 EGLDisplay
5488 display_get_egl_display(struct display *d)
5489 {
5490         return d->dpy;
5491 }
5492
5493 struct wl_data_source *
5494 display_create_data_source(struct display *display)
5495 {
5496         if (display->data_device_manager)
5497                 return wl_data_device_manager_create_data_source(display->data_device_manager);
5498         else
5499                 return NULL;
5500 }
5501
5502 EGLConfig
5503 display_get_argb_egl_config(struct display *d)
5504 {
5505         return d->argb_config;
5506 }
5507
5508 int
5509 display_acquire_window_surface(struct display *display,
5510                                struct window *window,
5511                                EGLContext ctx)
5512 {
5513         struct surface *surface = window->main_surface;
5514
5515         if (surface->buffer_type != WINDOW_BUFFER_TYPE_EGL_WINDOW)
5516                 return -1;
5517
5518         widget_get_cairo_surface(window->main_surface->widget);
5519         return surface->toysurface->acquire(surface->toysurface, ctx);
5520 }
5521
5522 void
5523 display_release_window_surface(struct display *display,
5524                                struct window *window)
5525 {
5526         struct surface *surface = window->main_surface;
5527
5528         if (surface->buffer_type != WINDOW_BUFFER_TYPE_EGL_WINDOW)
5529                 return;
5530
5531         surface->toysurface->release(surface->toysurface);
5532 }
5533
5534 void
5535 display_defer(struct display *display, struct task *task)
5536 {
5537         wl_list_insert(&display->deferred_list, &task->link);
5538 }
5539
5540 void
5541 display_watch_fd(struct display *display,
5542                  int fd, uint32_t events, struct task *task)
5543 {
5544         struct epoll_event ep;
5545
5546         ep.events = events;
5547         ep.data.ptr = task;
5548         epoll_ctl(display->epoll_fd, EPOLL_CTL_ADD, fd, &ep);
5549 }
5550
5551 void
5552 display_unwatch_fd(struct display *display, int fd)
5553 {
5554         epoll_ctl(display->epoll_fd, EPOLL_CTL_DEL, fd, NULL);
5555 }
5556
5557 void
5558 display_run(struct display *display)
5559 {
5560         struct task *task;
5561         struct epoll_event ep[16];
5562         int i, count, ret;
5563
5564         display->running = 1;
5565         while (1) {
5566                 while (!wl_list_empty(&display->deferred_list)) {
5567                         task = container_of(display->deferred_list.prev,
5568                                             struct task, link);
5569                         wl_list_remove(&task->link);
5570                         task->run(task, 0);
5571                 }
5572
5573                 wl_display_dispatch_pending(display->display);
5574
5575                 if (!display->running)
5576                         break;
5577
5578                 ret = wl_display_flush(display->display);
5579                 if (ret < 0 && errno == EAGAIN) {
5580                         ep[0].events =
5581                                 EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLHUP;
5582                         ep[0].data.ptr = &display->display_task;
5583
5584                         epoll_ctl(display->epoll_fd, EPOLL_CTL_MOD,
5585                                   display->display_fd, &ep[0]);
5586                 } else if (ret < 0) {
5587                         break;
5588                 }
5589
5590                 count = epoll_wait(display->epoll_fd,
5591                                    ep, ARRAY_LENGTH(ep), -1);
5592                 for (i = 0; i < count; i++) {
5593                         task = ep[i].data.ptr;
5594                         task->run(task, ep[i].events);
5595                 }
5596         }
5597 }
5598
5599 void
5600 display_exit(struct display *display)
5601 {
5602         display->running = 0;
5603 }
5604
5605 void
5606 keysym_modifiers_add(struct wl_array *modifiers_map,
5607                      const char *name)
5608 {
5609         size_t len = strlen(name) + 1;
5610         char *p;
5611
5612         p = wl_array_add(modifiers_map, len);
5613
5614         if (p == NULL)
5615                 return;
5616
5617         strncpy(p, name, len);
5618 }
5619
5620 static xkb_mod_index_t
5621 keysym_modifiers_get_index(struct wl_array *modifiers_map,
5622                            const char *name)
5623 {
5624         xkb_mod_index_t index = 0;
5625         char *p = modifiers_map->data;
5626
5627         while ((const char *)p < (const char *)(modifiers_map->data + modifiers_map->size)) {
5628                 if (strcmp(p, name) == 0)
5629                         return index;
5630
5631                 index++;
5632                 p += strlen(p) + 1;
5633         }
5634
5635         return XKB_MOD_INVALID;
5636 }
5637
5638 xkb_mod_mask_t
5639 keysym_modifiers_get_mask(struct wl_array *modifiers_map,
5640                           const char *name)
5641 {
5642         xkb_mod_index_t index = keysym_modifiers_get_index(modifiers_map, name);
5643
5644         if (index == XKB_MOD_INVALID)
5645                 return XKB_MOD_INVALID;
5646
5647         return 1 << index;
5648 }
5649
5650 void *
5651 fail_on_null(void *p)
5652 {
5653         if (p == NULL) {
5654                 fprintf(stderr, "%s: out of memory\n", program_invocation_short_name);
5655                 exit(EXIT_FAILURE);
5656         }
5657
5658         return p;
5659 }
5660
5661 void *
5662 xmalloc(size_t s)
5663 {
5664         return fail_on_null(malloc(s));
5665 }
5666
5667 void *
5668 xzalloc(size_t s)
5669 {
5670         return fail_on_null(zalloc(s));
5671 }
5672
5673 char *
5674 xstrdup(const char *s)
5675 {
5676         return fail_on_null(strdup(s));
5677 }
5678
5679 void *
5680 xrealloc(char *p, size_t s)
5681 {
5682         return fail_on_null(realloc(p, s));
5683 }