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