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