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