xdg-shell: Turn the resizing heuristics into an explicit state
[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                 xdg_surface_resize(window->xdg_surface,
2391                                    input_get_seat(input),
2392                                    window->display->serial,
2393                                    location);
2394
2395                 frame_status_clear(frame->frame, FRAME_STATUS_RESIZE);
2396         }
2397 }
2398
2399 static void
2400 frame_button_handler(struct widget *widget,
2401                      struct input *input, uint32_t time,
2402                      uint32_t button, enum wl_pointer_button_state state,
2403                      void *data)
2404
2405 {
2406         struct window_frame *frame = data;
2407         enum theme_location location;
2408
2409         location = frame_pointer_button(frame->frame, input, button, state);
2410         frame_handle_status(frame, input, time, location);
2411 }
2412
2413 static void
2414 frame_touch_down_handler(struct widget *widget, struct input *input,
2415                          uint32_t serial, uint32_t time, int32_t id,
2416                          float x, float y, void *data)
2417 {
2418         struct window_frame *frame = data;
2419
2420         frame_touch_down(frame->frame, input, id, x, y);
2421         frame_handle_status(frame, input, time, THEME_LOCATION_CLIENT_AREA);
2422 }
2423
2424 static void
2425 frame_touch_up_handler(struct widget *widget,
2426                          struct input *input, uint32_t serial, uint32_t time,
2427                          int32_t id, void *data)
2428 {
2429         struct window_frame *frame = data;
2430
2431         frame_touch_up(frame->frame, input, id);
2432         frame_handle_status(frame, input, time, THEME_LOCATION_CLIENT_AREA);
2433 }
2434
2435 struct widget *
2436 window_frame_create(struct window *window, void *data)
2437 {
2438         struct window_frame *frame;
2439         uint32_t buttons;
2440
2441         if (window->custom) {
2442                 buttons = FRAME_BUTTON_NONE;
2443         } else {
2444                 buttons = FRAME_BUTTON_ALL;
2445         }
2446
2447         frame = xzalloc(sizeof *frame);
2448         frame->frame = frame_create(window->display->theme, 0, 0,
2449                                     buttons, window->title);
2450
2451         frame->widget = window_add_widget(window, frame);
2452         frame->child = widget_add_widget(frame->widget, data);
2453
2454         widget_set_redraw_handler(frame->widget, frame_redraw_handler);
2455         widget_set_resize_handler(frame->widget, frame_resize_handler);
2456         widget_set_enter_handler(frame->widget, frame_enter_handler);
2457         widget_set_leave_handler(frame->widget, frame_leave_handler);
2458         widget_set_motion_handler(frame->widget, frame_motion_handler);
2459         widget_set_button_handler(frame->widget, frame_button_handler);
2460         widget_set_touch_down_handler(frame->widget, frame_touch_down_handler);
2461         widget_set_touch_up_handler(frame->widget, frame_touch_up_handler);
2462
2463         window->frame = frame;
2464
2465         return frame->child;
2466 }
2467
2468 void
2469 window_frame_set_child_size(struct widget *widget, int child_width,
2470                             int child_height)
2471 {
2472         struct display *display = widget->window->display;
2473         struct theme *t = display->theme;
2474         int decoration_width, decoration_height;
2475         int width, height;
2476         int margin = widget->window->maximized ? 0 : t->margin;
2477
2478         if (!widget->window->fullscreen) {
2479                 decoration_width = (t->width + margin) * 2;
2480                 decoration_height = t->width +
2481                         t->titlebar_height + margin * 2;
2482
2483                 width = child_width + decoration_width;
2484                 height = child_height + decoration_height;
2485         } else {
2486                 width = child_width;
2487                 height = child_height;
2488         }
2489
2490         window_schedule_resize(widget->window, width, height);
2491 }
2492
2493 static void
2494 window_frame_destroy(struct window_frame *frame)
2495 {
2496         frame_destroy(frame->frame);
2497
2498         /* frame->child must be destroyed by the application */
2499         widget_destroy(frame->widget);
2500         free(frame);
2501 }
2502
2503 static void
2504 input_set_focus_widget(struct input *input, struct widget *focus,
2505                        float x, float y)
2506 {
2507         struct widget *old, *widget;
2508         int cursor;
2509
2510         if (focus == input->focus_widget)
2511                 return;
2512
2513         old = input->focus_widget;
2514         if (old) {
2515                 widget = old;
2516                 if (input->grab)
2517                         widget = input->grab;
2518                 if (widget->leave_handler)
2519                         widget->leave_handler(old, input, widget->user_data);
2520                 input->focus_widget = NULL;
2521         }
2522
2523         if (focus) {
2524                 widget = focus;
2525                 if (input->grab)
2526                         widget = input->grab;
2527                 input->focus_widget = focus;
2528                 if (widget->enter_handler)
2529                         cursor = widget->enter_handler(focus, input, x, y,
2530                                                        widget->user_data);
2531                 else
2532                         cursor = widget->default_cursor;
2533
2534                 input_set_pointer_image(input, cursor);
2535         }
2536 }
2537
2538 void
2539 touch_grab(struct input  *input, int32_t touch_id)
2540 {
2541         input->touch_grab = 1;
2542         input->touch_grab_id = touch_id;
2543 }
2544
2545 void
2546 touch_ungrab(struct input *input)
2547 {
2548         struct touch_point *tp, *tmp;
2549
2550         input->touch_grab = 0;
2551
2552         wl_list_for_each_safe(tp, tmp,
2553                         &input->touch_point_list, link) {
2554                 if (tp->id != input->touch_grab_id)
2555                         continue;
2556                 wl_list_remove(&tp->link);
2557                 free(tp);
2558
2559                 return;
2560         }
2561 }
2562
2563 void
2564 input_grab(struct input *input, struct widget *widget, uint32_t button)
2565 {
2566         input->grab = widget;
2567         input->grab_button = button;
2568
2569         input_set_focus_widget(input, widget, input->sx, input->sy);
2570 }
2571
2572 void
2573 input_ungrab(struct input *input)
2574 {
2575         struct widget *widget;
2576
2577         input->grab = NULL;
2578         if (input->pointer_focus) {
2579                 widget = window_find_widget(input->pointer_focus,
2580                                             input->sx, input->sy);
2581                 input_set_focus_widget(input, widget, input->sx, input->sy);
2582         }
2583 }
2584
2585 static void
2586 input_remove_pointer_focus(struct input *input)
2587 {
2588         struct window *window = input->pointer_focus;
2589
2590         if (!window)
2591                 return;
2592
2593         input_set_focus_widget(input, NULL, 0, 0);
2594
2595         input->pointer_focus = NULL;
2596         input->current_cursor = CURSOR_UNSET;
2597 }
2598
2599 static void
2600 pointer_handle_enter(void *data, struct wl_pointer *pointer,
2601                      uint32_t serial, struct wl_surface *surface,
2602                      wl_fixed_t sx_w, wl_fixed_t sy_w)
2603 {
2604         struct input *input = data;
2605         struct window *window;
2606         struct widget *widget;
2607         float sx = wl_fixed_to_double(sx_w);
2608         float sy = wl_fixed_to_double(sy_w);
2609
2610         if (!surface) {
2611                 /* enter event for a window we've just destroyed */
2612                 return;
2613         }
2614
2615         window = wl_surface_get_user_data(surface);
2616         if (surface != window->main_surface->surface) {
2617                 DBG("Ignoring input event from subsurface %p\n", surface);
2618                 return;
2619         }
2620
2621         input->display->serial = serial;
2622         input->pointer_enter_serial = serial;
2623         input->pointer_focus = window;
2624
2625         input->sx = sx;
2626         input->sy = sy;
2627
2628         widget = window_find_widget(window, sx, sy);
2629         input_set_focus_widget(input, widget, sx, sy);
2630 }
2631
2632 static void
2633 pointer_handle_leave(void *data, struct wl_pointer *pointer,
2634                      uint32_t serial, struct wl_surface *surface)
2635 {
2636         struct input *input = data;
2637
2638         input->display->serial = serial;
2639         input_remove_pointer_focus(input);
2640 }
2641
2642 static void
2643 pointer_handle_motion(void *data, struct wl_pointer *pointer,
2644                       uint32_t time, wl_fixed_t sx_w, wl_fixed_t sy_w)
2645 {
2646         struct input *input = data;
2647         struct window *window = input->pointer_focus;
2648         struct widget *widget;
2649         int cursor;
2650         float sx = wl_fixed_to_double(sx_w);
2651         float sy = wl_fixed_to_double(sy_w);
2652
2653         if (!window)
2654                 return;
2655
2656         input->sx = sx;
2657         input->sy = sy;
2658
2659         /* when making the window smaller - e.g. after a unmaximise we might
2660          * still have a pending motion event that the compositor has picked
2661          * based on the old surface dimensions
2662          */
2663         if (sx > window->main_surface->allocation.width ||
2664             sy > window->main_surface->allocation.height)
2665                 return;
2666
2667         if (!(input->grab && input->grab_button)) {
2668                 widget = window_find_widget(window, sx, sy);
2669                 input_set_focus_widget(input, widget, sx, sy);
2670         }
2671
2672         if (input->grab)
2673                 widget = input->grab;
2674         else
2675                 widget = input->focus_widget;
2676         if (widget) {
2677                 if (widget->motion_handler)
2678                         cursor = widget->motion_handler(input->focus_widget,
2679                                                         input, time, sx, sy,
2680                                                         widget->user_data);
2681                 else
2682                         cursor = widget->default_cursor;
2683         } else
2684                 cursor = CURSOR_LEFT_PTR;
2685
2686         input_set_pointer_image(input, cursor);
2687 }
2688
2689 static void
2690 pointer_handle_button(void *data, struct wl_pointer *pointer, uint32_t serial,
2691                       uint32_t time, uint32_t button, uint32_t state_w)
2692 {
2693         struct input *input = data;
2694         struct widget *widget;
2695         enum wl_pointer_button_state state = state_w;
2696
2697         input->display->serial = serial;
2698         if (input->focus_widget && input->grab == NULL &&
2699             state == WL_POINTER_BUTTON_STATE_PRESSED)
2700                 input_grab(input, input->focus_widget, button);
2701
2702         widget = input->grab;
2703         if (widget && widget->button_handler)
2704                 (*widget->button_handler)(widget,
2705                                           input, time,
2706                                           button, state,
2707                                           input->grab->user_data);
2708
2709         if (input->grab && input->grab_button == button &&
2710             state == WL_POINTER_BUTTON_STATE_RELEASED)
2711                 input_ungrab(input);
2712 }
2713
2714 static void
2715 pointer_handle_axis(void *data, struct wl_pointer *pointer,
2716                     uint32_t time, uint32_t axis, wl_fixed_t value)
2717 {
2718         struct input *input = data;
2719         struct widget *widget;
2720
2721         widget = input->focus_widget;
2722         if (input->grab)
2723                 widget = input->grab;
2724         if (widget && widget->axis_handler)
2725                 (*widget->axis_handler)(widget,
2726                                         input, time,
2727                                         axis, value,
2728                                         widget->user_data);
2729 }
2730
2731 static const struct wl_pointer_listener pointer_listener = {
2732         pointer_handle_enter,
2733         pointer_handle_leave,
2734         pointer_handle_motion,
2735         pointer_handle_button,
2736         pointer_handle_axis,
2737 };
2738
2739 static void
2740 input_remove_keyboard_focus(struct input *input)
2741 {
2742         struct window *window = input->keyboard_focus;
2743         struct itimerspec its;
2744
2745         its.it_interval.tv_sec = 0;
2746         its.it_interval.tv_nsec = 0;
2747         its.it_value.tv_sec = 0;
2748         its.it_value.tv_nsec = 0;
2749         timerfd_settime(input->repeat_timer_fd, 0, &its, NULL);
2750
2751         if (!window)
2752                 return;
2753
2754         if (window->keyboard_focus_handler)
2755                 (*window->keyboard_focus_handler)(window, NULL,
2756                                                   window->user_data);
2757
2758         input->keyboard_focus = NULL;
2759 }
2760
2761 static void
2762 keyboard_repeat_func(struct task *task, uint32_t events)
2763 {
2764         struct input *input =
2765                 container_of(task, struct input, repeat_task);
2766         struct window *window = input->keyboard_focus;
2767         uint64_t exp;
2768
2769         if (read(input->repeat_timer_fd, &exp, sizeof exp) != sizeof exp)
2770                 /* If we change the timer between the fd becoming
2771                  * readable and getting here, there'll be nothing to
2772                  * read and we get EAGAIN. */
2773                 return;
2774
2775         if (window && window->key_handler) {
2776                 (*window->key_handler)(window, input, input->repeat_time,
2777                                        input->repeat_key, input->repeat_sym,
2778                                        WL_KEYBOARD_KEY_STATE_PRESSED,
2779                                        window->user_data);
2780         }
2781 }
2782
2783 static void
2784 keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard,
2785                        uint32_t format, int fd, uint32_t size)
2786 {
2787         struct input *input = data;
2788         struct xkb_keymap *keymap;
2789         struct xkb_state *state;
2790         char *map_str;
2791
2792         if (!data) {
2793                 close(fd);
2794                 return;
2795         }
2796
2797         if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) {
2798                 close(fd);
2799                 return;
2800         }
2801
2802         map_str = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
2803         if (map_str == MAP_FAILED) {
2804                 close(fd);
2805                 return;
2806         }
2807
2808         keymap = xkb_map_new_from_string(input->display->xkb_context,
2809                                          map_str,
2810                                          XKB_KEYMAP_FORMAT_TEXT_V1,
2811                                          0);
2812         munmap(map_str, size);
2813         close(fd);
2814
2815         if (!keymap) {
2816                 fprintf(stderr, "failed to compile keymap\n");
2817                 return;
2818         }
2819
2820         state = xkb_state_new(keymap);
2821         if (!state) {
2822                 fprintf(stderr, "failed to create XKB state\n");
2823                 xkb_map_unref(keymap);
2824                 return;
2825         }
2826
2827         xkb_keymap_unref(input->xkb.keymap);
2828         xkb_state_unref(input->xkb.state);
2829         input->xkb.keymap = keymap;
2830         input->xkb.state = state;
2831
2832         input->xkb.control_mask =
2833                 1 << xkb_map_mod_get_index(input->xkb.keymap, "Control");
2834         input->xkb.alt_mask =
2835                 1 << xkb_map_mod_get_index(input->xkb.keymap, "Mod1");
2836         input->xkb.shift_mask =
2837                 1 << xkb_map_mod_get_index(input->xkb.keymap, "Shift");
2838 }
2839
2840 static void
2841 keyboard_handle_enter(void *data, struct wl_keyboard *keyboard,
2842                       uint32_t serial, struct wl_surface *surface,
2843                       struct wl_array *keys)
2844 {
2845         struct input *input = data;
2846         struct window *window;
2847
2848         input->display->serial = serial;
2849         input->keyboard_focus = wl_surface_get_user_data(surface);
2850
2851         window = input->keyboard_focus;
2852         if (window->keyboard_focus_handler)
2853                 (*window->keyboard_focus_handler)(window,
2854                                                   input, window->user_data);
2855 }
2856
2857 static void
2858 keyboard_handle_leave(void *data, struct wl_keyboard *keyboard,
2859                       uint32_t serial, struct wl_surface *surface)
2860 {
2861         struct input *input = data;
2862
2863         input->display->serial = serial;
2864         input_remove_keyboard_focus(input);
2865 }
2866
2867 static void
2868 keyboard_handle_key(void *data, struct wl_keyboard *keyboard,
2869                     uint32_t serial, uint32_t time, uint32_t key,
2870                     uint32_t state_w)
2871 {
2872         struct input *input = data;
2873         struct window *window = input->keyboard_focus;
2874         uint32_t code, num_syms;
2875         enum wl_keyboard_key_state state = state_w;
2876         const xkb_keysym_t *syms;
2877         xkb_keysym_t sym;
2878         struct itimerspec its;
2879
2880         input->display->serial = serial;
2881         code = key + 8;
2882         if (!window || !input->xkb.state)
2883                 return;
2884
2885         /* We only use input grabs for pointer events for now, so just
2886          * ignore key presses if a grab is active.  We expand the key
2887          * event delivery mechanism to route events to widgets to
2888          * properly handle key grabs.  In the meantime, this prevents
2889          * key event devlivery while a grab is active. */
2890         if (input->grab && input->grab_button == 0)
2891                 return;
2892
2893         num_syms = xkb_key_get_syms(input->xkb.state, code, &syms);
2894
2895         sym = XKB_KEY_NoSymbol;
2896         if (num_syms == 1)
2897                 sym = syms[0];
2898
2899
2900         if (sym == XKB_KEY_F5 && input->modifiers == MOD_ALT_MASK) {
2901                 if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
2902                         window_set_maximized(window, !window->maximized);
2903         } else if (sym == XKB_KEY_F11 &&
2904                    window->fullscreen_handler &&
2905                    state == WL_KEYBOARD_KEY_STATE_PRESSED) {
2906                 window->fullscreen_handler(window, window->user_data);
2907         } else if (sym == XKB_KEY_F4 &&
2908                    input->modifiers == MOD_ALT_MASK &&
2909                    state == WL_KEYBOARD_KEY_STATE_PRESSED) {
2910                 window_close(window);
2911         } else if (window->key_handler) {
2912                 (*window->key_handler)(window, input, time, key,
2913                                        sym, state, window->user_data);
2914         }
2915
2916         if (state == WL_KEYBOARD_KEY_STATE_RELEASED &&
2917             key == input->repeat_key) {
2918                 its.it_interval.tv_sec = 0;
2919                 its.it_interval.tv_nsec = 0;
2920                 its.it_value.tv_sec = 0;
2921                 its.it_value.tv_nsec = 0;
2922                 timerfd_settime(input->repeat_timer_fd, 0, &its, NULL);
2923         } else if (state == WL_KEYBOARD_KEY_STATE_PRESSED &&
2924                    xkb_keymap_key_repeats(input->xkb.keymap, code)) {
2925                 input->repeat_sym = sym;
2926                 input->repeat_key = key;
2927                 input->repeat_time = time;
2928                 its.it_interval.tv_sec = 0;
2929                 its.it_interval.tv_nsec = 25 * 1000 * 1000;
2930                 its.it_value.tv_sec = 0;
2931                 its.it_value.tv_nsec = 400 * 1000 * 1000;
2932                 timerfd_settime(input->repeat_timer_fd, 0, &its, NULL);
2933         }
2934 }
2935
2936 static void
2937 keyboard_handle_modifiers(void *data, struct wl_keyboard *keyboard,
2938                           uint32_t serial, uint32_t mods_depressed,
2939                           uint32_t mods_latched, uint32_t mods_locked,
2940                           uint32_t group)
2941 {
2942         struct input *input = data;
2943         xkb_mod_mask_t mask;
2944
2945         /* If we're not using a keymap, then we don't handle PC-style modifiers */
2946         if (!input->xkb.keymap)
2947                 return;
2948
2949         xkb_state_update_mask(input->xkb.state, mods_depressed, mods_latched,
2950                               mods_locked, 0, 0, group);
2951         mask = xkb_state_serialize_mods(input->xkb.state,
2952                                         XKB_STATE_DEPRESSED |
2953                                         XKB_STATE_LATCHED);
2954         input->modifiers = 0;
2955         if (mask & input->xkb.control_mask)
2956                 input->modifiers |= MOD_CONTROL_MASK;
2957         if (mask & input->xkb.alt_mask)
2958                 input->modifiers |= MOD_ALT_MASK;
2959         if (mask & input->xkb.shift_mask)
2960                 input->modifiers |= MOD_SHIFT_MASK;
2961 }
2962
2963 static const struct wl_keyboard_listener keyboard_listener = {
2964         keyboard_handle_keymap,
2965         keyboard_handle_enter,
2966         keyboard_handle_leave,
2967         keyboard_handle_key,
2968         keyboard_handle_modifiers,
2969 };
2970
2971 static void
2972 touch_handle_down(void *data, struct wl_touch *wl_touch,
2973                   uint32_t serial, uint32_t time, struct wl_surface *surface,
2974                   int32_t id, wl_fixed_t x_w, wl_fixed_t y_w)
2975 {
2976         struct input *input = data;
2977         struct widget *widget;
2978         float sx = wl_fixed_to_double(x_w);
2979         float sy = wl_fixed_to_double(y_w);
2980
2981         input->display->serial = serial;
2982         input->touch_focus = wl_surface_get_user_data(surface);
2983         if (!input->touch_focus) {
2984                 DBG("Failed to find to touch focus for surface %p\n", surface);
2985                 return;
2986         }
2987
2988         if (surface != input->touch_focus->main_surface->surface) {
2989                 DBG("Ignoring input event from subsurface %p\n", surface);
2990                 input->touch_focus = NULL;
2991                 return;
2992         }
2993
2994         if (input->grab)
2995                 widget = input->grab;
2996         else
2997                 widget = window_find_widget(input->touch_focus,
2998                                             wl_fixed_to_double(x_w),
2999                                             wl_fixed_to_double(y_w));
3000         if (widget) {
3001                 struct touch_point *tp = xmalloc(sizeof *tp);
3002                 if (tp) {
3003                         tp->id = id;
3004                         tp->widget = widget;
3005                         tp->x = sx;
3006                         tp->y = sy;
3007                         wl_list_insert(&input->touch_point_list, &tp->link);
3008
3009                         if (widget->touch_down_handler)
3010                                 (*widget->touch_down_handler)(widget, input, 
3011                                                               serial, time, id,
3012                                                               sx, sy,
3013                                                               widget->user_data);
3014                 }
3015         }
3016 }
3017
3018 static void
3019 touch_handle_up(void *data, struct wl_touch *wl_touch,
3020                 uint32_t serial, uint32_t time, int32_t id)
3021 {
3022         struct input *input = data;
3023         struct touch_point *tp, *tmp;
3024
3025         if (!input->touch_focus) {
3026                 DBG("No touch focus found for touch up event!\n");
3027                 return;
3028         }
3029
3030         wl_list_for_each_safe(tp, tmp, &input->touch_point_list, link) {
3031                 if (tp->id != id)
3032                         continue;
3033
3034                 if (tp->widget->touch_up_handler)
3035                         (*tp->widget->touch_up_handler)(tp->widget, input, serial,
3036                                                         time, id,
3037                                                         tp->widget->user_data);
3038
3039                 wl_list_remove(&tp->link);
3040                 free(tp);
3041
3042                 return;
3043         }
3044 }
3045
3046 static void
3047 touch_handle_motion(void *data, struct wl_touch *wl_touch,
3048                     uint32_t time, int32_t id, wl_fixed_t x_w, wl_fixed_t y_w)
3049 {
3050         struct input *input = data;
3051         struct touch_point *tp;
3052         float sx = wl_fixed_to_double(x_w);
3053         float sy = wl_fixed_to_double(y_w);
3054
3055         DBG("touch_handle_motion: %i %i\n", id, wl_list_length(&input->touch_point_list));
3056
3057         if (!input->touch_focus) {
3058                 DBG("No touch focus found for touch motion event!\n");
3059                 return;
3060         }
3061
3062         wl_list_for_each(tp, &input->touch_point_list, link) {
3063                 if (tp->id != id)
3064                         continue;
3065
3066                 tp->x = sx;
3067                 tp->y = sy;
3068                 if (tp->widget->touch_motion_handler)
3069                         (*tp->widget->touch_motion_handler)(tp->widget, input, time,
3070                                                             id, sx, sy,
3071                                                             tp->widget->user_data);
3072                 return;
3073         }
3074 }
3075
3076 static void
3077 touch_handle_frame(void *data, struct wl_touch *wl_touch)
3078 {
3079         struct input *input = data;
3080         struct touch_point *tp, *tmp;
3081
3082         DBG("touch_handle_frame\n");
3083
3084         if (!input->touch_focus) {
3085                 DBG("No touch focus found for touch frame event!\n");
3086                 return;
3087         }
3088
3089         wl_list_for_each_safe(tp, tmp, &input->touch_point_list, link) {
3090                 if (tp->widget->touch_frame_handler)
3091                         (*tp->widget->touch_frame_handler)(tp->widget, input, 
3092                                                            tp->widget->user_data);
3093         }
3094 }
3095
3096 static void
3097 touch_handle_cancel(void *data, struct wl_touch *wl_touch)
3098 {
3099         struct input *input = data;
3100         struct touch_point *tp, *tmp;
3101
3102         DBG("touch_handle_cancel\n");
3103
3104         if (!input->touch_focus) {
3105                 DBG("No touch focus found for touch cancel event!\n");
3106                 return;
3107         }
3108
3109         wl_list_for_each_safe(tp, tmp, &input->touch_point_list, link) {
3110                 if (tp->widget->touch_cancel_handler)
3111                         (*tp->widget->touch_cancel_handler)(tp->widget, input,
3112                                                             tp->widget->user_data);
3113
3114                 wl_list_remove(&tp->link);
3115                 free(tp);
3116         }
3117 }
3118
3119 static const struct wl_touch_listener touch_listener = {
3120         touch_handle_down,
3121         touch_handle_up,
3122         touch_handle_motion,
3123         touch_handle_frame,
3124         touch_handle_cancel,
3125 };
3126
3127 static void
3128 seat_handle_capabilities(void *data, struct wl_seat *seat,
3129                          enum wl_seat_capability caps)
3130 {
3131         struct input *input = data;
3132
3133         if ((caps & WL_SEAT_CAPABILITY_POINTER) && !input->pointer) {
3134                 input->pointer = wl_seat_get_pointer(seat);
3135                 wl_pointer_set_user_data(input->pointer, input);
3136                 wl_pointer_add_listener(input->pointer, &pointer_listener,
3137                                         input);
3138         } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && input->pointer) {
3139                 wl_pointer_destroy(input->pointer);
3140                 input->pointer = NULL;
3141         }
3142
3143         if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !input->keyboard) {
3144                 input->keyboard = wl_seat_get_keyboard(seat);
3145                 wl_keyboard_set_user_data(input->keyboard, input);
3146                 wl_keyboard_add_listener(input->keyboard, &keyboard_listener,
3147                                          input);
3148         } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && input->keyboard) {
3149                 wl_keyboard_destroy(input->keyboard);
3150                 input->keyboard = NULL;
3151         }
3152
3153         if ((caps & WL_SEAT_CAPABILITY_TOUCH) && !input->touch) {
3154                 input->touch = wl_seat_get_touch(seat);
3155                 wl_touch_set_user_data(input->touch, input);
3156                 wl_touch_add_listener(input->touch, &touch_listener, input);
3157         } else if (!(caps & WL_SEAT_CAPABILITY_TOUCH) && input->touch) {
3158                 wl_touch_destroy(input->touch);
3159                 input->touch = NULL;
3160         }
3161 }
3162
3163 static void
3164 seat_handle_name(void *data, struct wl_seat *seat,
3165                  const char *name)
3166 {
3167
3168 }
3169
3170 static const struct wl_seat_listener seat_listener = {
3171         seat_handle_capabilities,
3172         seat_handle_name
3173 };
3174
3175 void
3176 input_get_position(struct input *input, int32_t *x, int32_t *y)
3177 {
3178         *x = input->sx;
3179         *y = input->sy;
3180 }
3181
3182 int
3183 input_get_touch(struct input *input, int32_t id, float *x, float *y)
3184 {
3185         struct touch_point *tp;
3186
3187         wl_list_for_each(tp, &input->touch_point_list, link) {
3188                 if (tp->id != id)
3189                         continue;
3190
3191                 *x = tp->x;
3192                 *y = tp->y;
3193                 return 0;
3194         }
3195
3196         return -1;
3197 }
3198
3199 struct display *
3200 input_get_display(struct input *input)
3201 {
3202         return input->display;
3203 }
3204
3205 struct wl_seat *
3206 input_get_seat(struct input *input)
3207 {
3208         return input->seat;
3209 }
3210
3211 uint32_t
3212 input_get_modifiers(struct input *input)
3213 {
3214         return input->modifiers;
3215 }
3216
3217 struct widget *
3218 input_get_focus_widget(struct input *input)
3219 {
3220         return input->focus_widget;
3221 }
3222
3223 struct data_offer {
3224         struct wl_data_offer *offer;
3225         struct input *input;
3226         struct wl_array types;
3227         int refcount;
3228
3229         struct task io_task;
3230         int fd;
3231         data_func_t func;
3232         int32_t x, y;
3233         void *user_data;
3234 };
3235
3236 static void
3237 data_offer_offer(void *data, struct wl_data_offer *wl_data_offer, const char *type)
3238 {
3239         struct data_offer *offer = data;
3240         char **p;
3241
3242         p = wl_array_add(&offer->types, sizeof *p);
3243         *p = strdup(type);
3244 }
3245
3246 static const struct wl_data_offer_listener data_offer_listener = {
3247         data_offer_offer,
3248 };
3249
3250 static void
3251 data_offer_destroy(struct data_offer *offer)
3252 {
3253         char **p;
3254
3255         offer->refcount--;
3256         if (offer->refcount == 0) {
3257                 wl_data_offer_destroy(offer->offer);
3258                 for (p = offer->types.data; *p; p++)
3259                         free(*p);
3260                 wl_array_release(&offer->types);
3261                 free(offer);
3262         }
3263 }
3264
3265 static void
3266 data_device_data_offer(void *data,
3267                        struct wl_data_device *data_device,
3268                        struct wl_data_offer *_offer)
3269 {
3270         struct data_offer *offer;
3271
3272         offer = xmalloc(sizeof *offer);
3273
3274         wl_array_init(&offer->types);
3275         offer->refcount = 1;
3276         offer->input = data;
3277         offer->offer = _offer;
3278         wl_data_offer_add_listener(offer->offer,
3279                                    &data_offer_listener, offer);
3280 }
3281
3282 static void
3283 data_device_enter(void *data, struct wl_data_device *data_device,
3284                   uint32_t serial, struct wl_surface *surface,
3285                   wl_fixed_t x_w, wl_fixed_t y_w,
3286                   struct wl_data_offer *offer)
3287 {
3288         struct input *input = data;
3289         struct window *window;
3290         void *types_data;
3291         float x = wl_fixed_to_double(x_w);
3292         float y = wl_fixed_to_double(y_w);
3293         char **p;
3294
3295         window = wl_surface_get_user_data(surface);
3296         input->drag_enter_serial = serial;
3297         input->drag_focus = window,
3298         input->drag_x = x;
3299         input->drag_y = y;
3300
3301         if (!input->touch_grab)
3302                 input->pointer_enter_serial = serial;
3303
3304         if (offer) {
3305                 input->drag_offer = wl_data_offer_get_user_data(offer);
3306
3307                 p = wl_array_add(&input->drag_offer->types, sizeof *p);
3308                 *p = NULL;
3309
3310                 types_data = input->drag_offer->types.data;
3311         } else {
3312                 input->drag_offer = NULL;
3313                 types_data = NULL;
3314         }
3315
3316         if (window->data_handler)
3317                 window->data_handler(window, input, x, y, types_data,
3318                                      window->user_data);
3319 }
3320
3321 static void
3322 data_device_leave(void *data, struct wl_data_device *data_device)
3323 {
3324         struct input *input = data;
3325
3326         if (input->drag_offer) {
3327                 data_offer_destroy(input->drag_offer);
3328                 input->drag_offer = NULL;
3329         }
3330 }
3331
3332 static void
3333 data_device_motion(void *data, struct wl_data_device *data_device,
3334                    uint32_t time, wl_fixed_t x_w, wl_fixed_t y_w)
3335 {
3336         struct input *input = data;
3337         struct window *window = input->drag_focus;
3338         float x = wl_fixed_to_double(x_w);
3339         float y = wl_fixed_to_double(y_w);
3340         void *types_data;
3341
3342         input->drag_x = x;
3343         input->drag_y = y;
3344
3345         if (input->drag_offer)
3346                 types_data = input->drag_offer->types.data;
3347         else
3348                 types_data = NULL;
3349
3350         if (window->data_handler)
3351                 window->data_handler(window, input, x, y, types_data,
3352                                      window->user_data);
3353 }
3354
3355 static void
3356 data_device_drop(void *data, struct wl_data_device *data_device)
3357 {
3358         struct input *input = data;
3359         struct window *window = input->drag_focus;
3360         float x, y;
3361
3362         x = input->drag_x;
3363         y = input->drag_y;
3364
3365         if (window->drop_handler)
3366                 window->drop_handler(window, input,
3367                                      x, y, window->user_data);
3368
3369         if (input->touch_grab)
3370                 touch_ungrab(input);
3371 }
3372
3373 static void
3374 data_device_selection(void *data,
3375                       struct wl_data_device *wl_data_device,
3376                       struct wl_data_offer *offer)
3377 {
3378         struct input *input = data;
3379         char **p;
3380
3381         if (input->selection_offer)
3382                 data_offer_destroy(input->selection_offer);
3383
3384         if (offer) {
3385                 input->selection_offer = wl_data_offer_get_user_data(offer);
3386                 p = wl_array_add(&input->selection_offer->types, sizeof *p);
3387                 *p = NULL;
3388         } else {
3389                 input->selection_offer = NULL;
3390         }
3391 }
3392
3393 static const struct wl_data_device_listener data_device_listener = {
3394         data_device_data_offer,
3395         data_device_enter,
3396         data_device_leave,
3397         data_device_motion,
3398         data_device_drop,
3399         data_device_selection
3400 };
3401
3402 static void
3403 input_set_pointer_image_index(struct input *input, int index)
3404 {
3405         struct wl_buffer *buffer;
3406         struct wl_cursor *cursor;
3407         struct wl_cursor_image *image;
3408
3409         if (!input->pointer)
3410                 return;
3411
3412         cursor = input->display->cursors[input->current_cursor];
3413         if (!cursor)
3414                 return;
3415
3416         if (index >= (int) cursor->image_count) {
3417                 fprintf(stderr, "cursor index out of range\n");
3418                 return;
3419         }
3420
3421         image = cursor->images[index];
3422         buffer = wl_cursor_image_get_buffer(image);
3423         if (!buffer)
3424                 return;
3425
3426         wl_surface_attach(input->pointer_surface, buffer, 0, 0);
3427         wl_surface_damage(input->pointer_surface, 0, 0,
3428                           image->width, image->height);
3429         wl_surface_commit(input->pointer_surface);
3430         wl_pointer_set_cursor(input->pointer, input->pointer_enter_serial,
3431                               input->pointer_surface,
3432                               image->hotspot_x, image->hotspot_y);
3433 }
3434
3435 static const struct wl_callback_listener pointer_surface_listener;
3436
3437 static void
3438 pointer_surface_frame_callback(void *data, struct wl_callback *callback,
3439                                uint32_t time)
3440 {
3441         struct input *input = data;
3442         struct wl_cursor *cursor;
3443         int i;
3444
3445         if (callback) {
3446                 assert(callback == input->cursor_frame_cb);
3447                 wl_callback_destroy(callback);
3448                 input->cursor_frame_cb = NULL;
3449         }
3450
3451         if (!input->pointer)
3452                 return;
3453
3454         if (input->current_cursor == CURSOR_BLANK) {
3455                 wl_pointer_set_cursor(input->pointer,
3456                                       input->pointer_enter_serial,
3457                                       NULL, 0, 0);
3458                 return;
3459         }
3460
3461         if (input->current_cursor == CURSOR_UNSET)
3462                 return;
3463         cursor = input->display->cursors[input->current_cursor];
3464         if (!cursor)
3465                 return;
3466
3467         /* FIXME We don't have the current time on the first call so we set
3468          * the animation start to the time of the first frame callback. */
3469         if (time == 0)
3470                 input->cursor_anim_start = 0;
3471         else if (input->cursor_anim_start == 0)
3472                 input->cursor_anim_start = time;
3473
3474         if (time == 0 || input->cursor_anim_start == 0)
3475                 i = 0;
3476         else
3477                 i = wl_cursor_frame(cursor, time - input->cursor_anim_start);
3478
3479         if (cursor->image_count > 1) {
3480                 input->cursor_frame_cb =
3481                         wl_surface_frame(input->pointer_surface);
3482                 wl_callback_add_listener(input->cursor_frame_cb,
3483                                          &pointer_surface_listener, input);
3484         }
3485
3486         input_set_pointer_image_index(input, i);
3487 }
3488
3489 static const struct wl_callback_listener pointer_surface_listener = {
3490         pointer_surface_frame_callback
3491 };
3492
3493 void
3494 input_set_pointer_image(struct input *input, int pointer)
3495 {
3496         int force = 0;
3497
3498         if (!input->pointer)
3499                 return;
3500
3501         if (input->pointer_enter_serial > input->cursor_serial)
3502                 force = 1;
3503
3504         if (!force && pointer == input->current_cursor)
3505                 return;
3506
3507         input->current_cursor = pointer;
3508         input->cursor_serial = input->pointer_enter_serial;
3509         if (!input->cursor_frame_cb)
3510                 pointer_surface_frame_callback(input, NULL, 0);
3511         else if (force) {
3512                 /* The current frame callback may be stuck if, for instance,
3513                  * the set cursor request was processed by the server after
3514                  * this client lost the focus. In this case the cursor surface
3515                  * might not be mapped and the frame callback wouldn't ever
3516                  * complete. Send a set_cursor and attach to try to map the
3517                  * cursor surface again so that the callback will finish */
3518                 input_set_pointer_image_index(input, 0);
3519         }
3520 }
3521
3522 struct wl_data_device *
3523 input_get_data_device(struct input *input)
3524 {
3525         return input->data_device;
3526 }
3527
3528 void
3529 input_set_selection(struct input *input,
3530                     struct wl_data_source *source, uint32_t time)
3531 {
3532         if (input->data_device)
3533                 wl_data_device_set_selection(input->data_device, source, time);
3534 }
3535
3536 void
3537 input_accept(struct input *input, const char *type)
3538 {
3539         wl_data_offer_accept(input->drag_offer->offer,
3540                              input->drag_enter_serial, type);
3541 }
3542
3543 static void
3544 offer_io_func(struct task *task, uint32_t events)
3545 {
3546         struct data_offer *offer =
3547                 container_of(task, struct data_offer, io_task);
3548         unsigned int len;
3549         char buffer[4096];
3550
3551         len = read(offer->fd, buffer, sizeof buffer);
3552         offer->func(buffer, len,
3553                     offer->x, offer->y, offer->user_data);
3554
3555         if (len == 0) {
3556                 close(offer->fd);
3557                 data_offer_destroy(offer);
3558         }
3559 }
3560
3561 static void
3562 data_offer_receive_data(struct data_offer *offer, const char *mime_type,
3563                         data_func_t func, void *user_data)
3564 {
3565         int p[2];
3566
3567         if (pipe2(p, O_CLOEXEC) == -1)
3568                 return;
3569
3570         wl_data_offer_receive(offer->offer, mime_type, p[1]);
3571         close(p[1]);
3572
3573         offer->io_task.run = offer_io_func;
3574         offer->fd = p[0];
3575         offer->func = func;
3576         offer->refcount++;
3577         offer->user_data = user_data;
3578
3579         display_watch_fd(offer->input->display,
3580                          offer->fd, EPOLLIN, &offer->io_task);
3581 }
3582
3583 void
3584 input_receive_drag_data(struct input *input, const char *mime_type,
3585                         data_func_t func, void *data)
3586 {
3587         data_offer_receive_data(input->drag_offer, mime_type, func, data);
3588         input->drag_offer->x = input->drag_x;
3589         input->drag_offer->y = input->drag_y;
3590 }
3591
3592 int
3593 input_receive_drag_data_to_fd(struct input *input,
3594                               const char *mime_type, int fd)
3595 {
3596         if (input->drag_offer)
3597                 wl_data_offer_receive(input->drag_offer->offer, mime_type, fd);
3598
3599         return 0;
3600 }
3601
3602 int
3603 input_receive_selection_data(struct input *input, const char *mime_type,
3604                              data_func_t func, void *data)
3605 {
3606         char **p;
3607
3608         if (input->selection_offer == NULL)
3609                 return -1;
3610
3611         for (p = input->selection_offer->types.data; *p; p++)
3612                 if (strcmp(mime_type, *p) == 0)
3613                         break;
3614
3615         if (*p == NULL)
3616                 return -1;
3617
3618         data_offer_receive_data(input->selection_offer,
3619                                 mime_type, func, data);
3620         return 0;
3621 }
3622
3623 int
3624 input_receive_selection_data_to_fd(struct input *input,
3625                                    const char *mime_type, int fd)
3626 {
3627         if (input->selection_offer)
3628                 wl_data_offer_receive(input->selection_offer->offer,
3629                                       mime_type, fd);
3630
3631         return 0;
3632 }
3633
3634 void
3635 window_move(struct window *window, struct input *input, uint32_t serial)
3636 {
3637         if (!window->xdg_surface)
3638                 return;
3639
3640         xdg_surface_move(window->xdg_surface, input->seat, serial);
3641 }
3642
3643 static void
3644 surface_set_synchronized(struct surface *surface)
3645 {
3646         if (!surface->subsurface)
3647                 return;
3648
3649         if (surface->synchronized)
3650                 return;
3651
3652         wl_subsurface_set_sync(surface->subsurface);
3653         surface->synchronized = 1;
3654 }
3655
3656 static void
3657 surface_set_synchronized_default(struct surface *surface)
3658 {
3659         if (!surface->subsurface)
3660                 return;
3661
3662         if (surface->synchronized == surface->synchronized_default)
3663                 return;
3664
3665         if (surface->synchronized_default)
3666                 wl_subsurface_set_sync(surface->subsurface);
3667         else
3668                 wl_subsurface_set_desync(surface->subsurface);
3669
3670         surface->synchronized = surface->synchronized_default;
3671 }
3672
3673 static void
3674 surface_resize(struct surface *surface)
3675 {
3676         struct widget *widget = surface->widget;
3677         struct wl_compositor *compositor = widget->window->display->compositor;
3678
3679         if (surface->input_region) {
3680                 wl_region_destroy(surface->input_region);
3681                 surface->input_region = NULL;
3682         }
3683
3684         if (surface->opaque_region)
3685                 wl_region_destroy(surface->opaque_region);
3686
3687         surface->opaque_region = wl_compositor_create_region(compositor);
3688
3689         if (widget->resize_handler)
3690                 widget->resize_handler(widget,
3691                                        widget->allocation.width,
3692                                        widget->allocation.height,
3693                                        widget->user_data);
3694
3695         if (surface->subsurface &&
3696             (surface->allocation.x != widget->allocation.x ||
3697              surface->allocation.y != widget->allocation.y)) {
3698                 wl_subsurface_set_position(surface->subsurface,
3699                                            widget->allocation.x,
3700                                            widget->allocation.y);
3701         }
3702         if (surface->allocation.width != widget->allocation.width ||
3703             surface->allocation.height != widget->allocation.height) {
3704                 window_schedule_redraw(widget->window);
3705         }
3706         surface->allocation = widget->allocation;
3707
3708         if (widget->opaque)
3709                 wl_region_add(surface->opaque_region, 0, 0,
3710                               widget->allocation.width,
3711                               widget->allocation.height);
3712 }
3713
3714 static void
3715 hack_prevent_EGL_sub_surface_deadlock(struct window *window)
3716 {
3717         /*
3718          * This hack should be removed, when EGL respects
3719          * eglSwapInterval(0).
3720          *
3721          * If this window has sub-surfaces, especially a free-running
3722          * EGL-widget, we need to post the parent surface once with
3723          * all the old state to guarantee, that the EGL-widget will
3724          * receive its frame callback soon. Otherwise, a forced call
3725          * to eglSwapBuffers may end up blocking, waiting for a frame
3726          * event that will never come, because we will commit the parent
3727          * surface with all new state only after eglSwapBuffers returns.
3728          *
3729          * This assumes, that:
3730          * 1. When the EGL widget's resize hook is called, it pauses.
3731          * 2. When the EGL widget's redraw hook is called, it forces a
3732          *    repaint and a call to eglSwapBuffers(), and maybe resumes.
3733          * In a single threaded application condition 1 is a no-op.
3734          *
3735          * XXX: This should actually be after the surface_resize() calls,
3736          * but cannot, because then it would commit the incomplete state
3737          * accumulated from the widget resize hooks.
3738          */
3739         if (window->subsurface_list.next != &window->main_surface->link ||
3740             window->subsurface_list.prev != &window->main_surface->link)
3741                 wl_surface_commit(window->main_surface->surface);
3742 }
3743
3744 static void
3745 window_do_resize(struct window *window)
3746 {
3747         struct surface *surface;
3748
3749         widget_set_allocation(window->main_surface->widget,
3750                               window->pending_allocation.x,
3751                               window->pending_allocation.y,
3752                               window->pending_allocation.width,
3753                               window->pending_allocation.height);
3754
3755         surface_resize(window->main_surface);
3756
3757         /* The main surface is in the list, too. Main surface's
3758          * resize_handler is responsible for calling widget_set_allocation()
3759          * on all sub-surface root widgets, so they will be resized
3760          * properly.
3761          */
3762         wl_list_for_each(surface, &window->subsurface_list, link) {
3763                 if (surface == window->main_surface)
3764                         continue;
3765
3766                 surface_set_synchronized(surface);
3767                 surface_resize(surface);
3768         }
3769
3770         if (!window->fullscreen && !window->maximized)
3771                 window->saved_allocation = window->pending_allocation;
3772 }
3773
3774 static void
3775 idle_resize(struct window *window)
3776 {
3777         window->resize_needed = 0;
3778         window->redraw_needed = 1;
3779
3780         DBG("from %dx%d to %dx%d\n",
3781             window->main_surface->server_allocation.width,
3782             window->main_surface->server_allocation.height,
3783             window->pending_allocation.width,
3784             window->pending_allocation.height);
3785
3786         hack_prevent_EGL_sub_surface_deadlock(window);
3787
3788         window_do_resize(window);
3789 }
3790
3791 static void
3792 undo_resize(struct window *window)
3793 {
3794         window->pending_allocation.width =
3795                 window->main_surface->server_allocation.width;
3796         window->pending_allocation.height =
3797                 window->main_surface->server_allocation.height;
3798
3799         DBG("back to %dx%d\n",
3800             window->main_surface->server_allocation.width,
3801             window->main_surface->server_allocation.height);
3802
3803         window_do_resize(window);
3804
3805         if (window->pending_allocation.width == 0 &&
3806             window->pending_allocation.height == 0) {
3807                 fprintf(stderr, "Error: Could not draw a surface, "
3808                         "most likely due to insufficient disk space in "
3809                         "%s (XDG_RUNTIME_DIR).\n", getenv("XDG_RUNTIME_DIR"));
3810                 exit(EXIT_FAILURE);
3811         }
3812 }
3813
3814 void
3815 window_schedule_resize(struct window *window, int width, int height)
3816 {
3817         /* We should probably get these numbers from the theme. */
3818         const int min_width = 200, min_height = 200;
3819
3820         window->pending_allocation.x = 0;
3821         window->pending_allocation.y = 0;
3822         window->pending_allocation.width = width;
3823         window->pending_allocation.height = height;
3824
3825         if (window->min_allocation.width == 0) {
3826                 if (width < min_width && window->frame)
3827                         window->min_allocation.width = min_width;
3828                 else
3829                         window->min_allocation.width = width;
3830                 if (height < min_height && window->frame)
3831                         window->min_allocation.height = min_height;
3832                 else
3833                         window->min_allocation.height = height;
3834         }
3835
3836         if (window->pending_allocation.width < window->min_allocation.width)
3837                 window->pending_allocation.width = window->min_allocation.width;
3838         if (window->pending_allocation.height < window->min_allocation.height)
3839                 window->pending_allocation.height = window->min_allocation.height;
3840
3841         window->resize_needed = 1;
3842         window_schedule_redraw(window);
3843 }
3844
3845 void
3846 widget_schedule_resize(struct widget *widget, int32_t width, int32_t height)
3847 {
3848         window_schedule_resize(widget->window, width, height);
3849 }
3850
3851 static void
3852 handle_surface_configure(void *data, struct xdg_surface *xdg_surface,
3853                          int32_t width, int32_t height,
3854                          struct wl_array *states, uint32_t serial)
3855 {
3856         struct window *window = data;
3857         uint32_t *p;
3858
3859         if (width > 0 && height > 0) {
3860                 window_schedule_resize(window, width, height);
3861         } else {
3862                 window_schedule_resize(window,
3863                                        window->saved_allocation.width,
3864                                        window->saved_allocation.height);
3865         }
3866
3867         window->maximized = 0;
3868         window->fullscreen = 0;
3869         window->resizing = 0;
3870
3871         wl_array_for_each(p, states) {
3872                 uint32_t state = *p;
3873                 switch (state) {
3874                 case XDG_SURFACE_STATE_MAXIMIZED:
3875                         window->maximized = 1;
3876                         break;
3877                 case XDG_SURFACE_STATE_FULLSCREEN:
3878                         window->fullscreen = 1;
3879                         break;
3880                 case XDG_SURFACE_STATE_RESIZING:
3881                         window->resizing = 1;
3882                         break;
3883                 default:
3884                         /* Unknown state */
3885                         break;
3886                 }
3887         }
3888
3889         window->next_attach_serial = serial;
3890 }
3891
3892 static void
3893 handle_surface_activated(void *data, struct xdg_surface *xdg_surface)
3894 {
3895         struct window *window = data;
3896         window->focused = 1;
3897 }
3898
3899 static void
3900 handle_surface_deactivated(void *data, struct xdg_surface *xdg_surface)
3901 {
3902         struct window *window = data;
3903         window->focused = 0;
3904 }
3905
3906 static void
3907 handle_surface_delete(void *data, struct xdg_surface *xdg_surface)
3908 {
3909         struct window *window = data;
3910         window_close(window);
3911 }
3912
3913 static const struct xdg_surface_listener xdg_surface_listener = {
3914         handle_surface_configure,
3915         handle_surface_activated,
3916         handle_surface_deactivated,
3917         handle_surface_delete,
3918 };
3919
3920 static void
3921 window_sync_parent(struct window *window)
3922 {
3923         struct wl_surface *parent_surface;
3924
3925         if (!window->xdg_surface)
3926                 return;
3927
3928         if (window->parent)
3929                 parent_surface = window->parent->main_surface->surface;
3930         else
3931                 parent_surface = NULL;
3932
3933         xdg_surface_set_parent(window->xdg_surface, parent_surface);
3934 }
3935
3936 static void
3937 window_sync_margin(struct window *window)
3938 {
3939         int margin;
3940
3941         if (!window->xdg_surface)
3942                 return;
3943
3944         if (!window->frame)
3945                 return;
3946
3947         margin = frame_get_shadow_margin(window->frame->frame);
3948
3949         /* Shadow size is the same on every side. */
3950         xdg_surface_set_margin(window->xdg_surface,
3951                                      margin,
3952                                      margin,
3953                                      margin,
3954                                      margin);
3955 }
3956
3957 static void
3958 window_flush(struct window *window)
3959 {
3960         struct surface *surface;
3961
3962         if (!window->custom) {
3963                 if (window->xdg_surface) {
3964                         window_sync_parent(window);
3965                         window_sync_margin(window);
3966                 }
3967         }
3968
3969         wl_list_for_each(surface, &window->subsurface_list, link) {
3970                 if (surface == window->main_surface)
3971                         continue;
3972
3973                 surface_flush(surface);
3974         }
3975
3976         surface_flush(window->main_surface);
3977 }
3978
3979 static void
3980 menu_destroy(struct menu *menu)
3981 {
3982         widget_destroy(menu->widget);
3983         window_destroy(menu->window);
3984         frame_destroy(menu->frame);
3985         free(menu);
3986 }
3987
3988 void
3989 window_get_allocation(struct window *window,
3990                       struct rectangle *allocation)
3991 {
3992         *allocation = window->main_surface->allocation;
3993 }
3994
3995 static void
3996 widget_redraw(struct widget *widget)
3997 {
3998         struct widget *child;
3999
4000         if (widget->redraw_handler)
4001                 widget->redraw_handler(widget, widget->user_data);
4002         wl_list_for_each(child, &widget->child_list, link)
4003                 widget_redraw(child);
4004 }
4005
4006 static void
4007 frame_callback(void *data, struct wl_callback *callback, uint32_t time)
4008 {
4009         struct surface *surface = data;
4010
4011         assert(callback == surface->frame_cb);
4012         DBG_OBJ(callback, "done\n");
4013         wl_callback_destroy(callback);
4014         surface->frame_cb = NULL;
4015
4016         surface->last_time = time;
4017
4018         if (surface->redraw_needed || surface->window->redraw_needed) {
4019                 DBG_OBJ(surface->surface, "window_schedule_redraw_task\n");
4020                 window_schedule_redraw_task(surface->window);
4021         }
4022 }
4023
4024 static const struct wl_callback_listener listener = {
4025         frame_callback
4026 };
4027
4028 static int
4029 surface_redraw(struct surface *surface)
4030 {
4031         DBG_OBJ(surface->surface, "begin\n");
4032
4033         if (!surface->window->redraw_needed && !surface->redraw_needed)
4034                 return 0;
4035
4036         /* Whole-window redraw forces a redraw even if the previous has
4037          * not yet hit the screen.
4038          */
4039         if (surface->frame_cb) {
4040                 if (!surface->window->redraw_needed)
4041                         return 0;
4042
4043                 DBG_OBJ(surface->frame_cb, "cancelled\n");
4044                 wl_callback_destroy(surface->frame_cb);
4045         }
4046
4047         if (surface->widget->use_cairo &&
4048             !widget_get_cairo_surface(surface->widget)) {
4049                 DBG_OBJ(surface->surface, "cancelled due buffer failure\n");
4050                 return -1;
4051         }
4052
4053         surface->frame_cb = wl_surface_frame(surface->surface);
4054         wl_callback_add_listener(surface->frame_cb, &listener, surface);
4055         DBG_OBJ(surface->frame_cb, "new\n");
4056
4057         surface->redraw_needed = 0;
4058         DBG_OBJ(surface->surface, "-> widget_redraw\n");
4059         widget_redraw(surface->widget);
4060         DBG_OBJ(surface->surface, "done\n");
4061         return 0;
4062 }
4063
4064 static void
4065 idle_redraw(struct task *task, uint32_t events)
4066 {
4067         struct window *window = container_of(task, struct window, redraw_task);
4068         struct surface *surface;
4069         int failed = 0;
4070         int resized = 0;
4071
4072         DBG(" --------- \n");
4073
4074         wl_list_init(&window->redraw_task.link);
4075         window->redraw_task_scheduled = 0;
4076
4077         if (window->resize_needed) {
4078                 /* throttle resizing to the main surface display */
4079                 if (window->main_surface->frame_cb) {
4080                         DBG_OBJ(window->main_surface->frame_cb, "pending\n");
4081                         return;
4082                 }
4083
4084                 idle_resize(window);
4085                 resized = 1;
4086         }
4087
4088         if (surface_redraw(window->main_surface) < 0) {
4089                 /*
4090                  * Only main_surface failure will cause us to undo the resize.
4091                  * If sub-surfaces fail, they will just be broken with old
4092                  * content.
4093                  */
4094                 failed = 1;
4095         } else {
4096                 wl_list_for_each(surface, &window->subsurface_list, link) {
4097                         if (surface == window->main_surface)
4098                                 continue;
4099
4100                         surface_redraw(surface);
4101                 }
4102         }
4103
4104         window->redraw_needed = 0;
4105         window_flush(window);
4106
4107         wl_list_for_each(surface, &window->subsurface_list, link)
4108                 surface_set_synchronized_default(surface);
4109
4110         if (resized && failed) {
4111                 /* Restore widget tree to correspond to what is on screen. */
4112                 undo_resize(window);
4113         }
4114 }
4115
4116 static void
4117 window_schedule_redraw_task(struct window *window)
4118 {
4119         if (!window->redraw_task_scheduled) {
4120                 window->redraw_task.run = idle_redraw;
4121                 display_defer(window->display, &window->redraw_task);
4122                 window->redraw_task_scheduled = 1;
4123         }
4124 }
4125
4126 void
4127 window_schedule_redraw(struct window *window)
4128 {
4129         struct surface *surface;
4130
4131         DBG_OBJ(window->main_surface->surface, "window %p\n", window);
4132
4133         wl_list_for_each(surface, &window->subsurface_list, link)
4134                 surface->redraw_needed = 1;
4135
4136         window_schedule_redraw_task(window);
4137 }
4138
4139 int
4140 window_is_fullscreen(struct window *window)
4141 {
4142         return window->fullscreen;
4143 }
4144
4145 void
4146 window_set_fullscreen(struct window *window, int fullscreen)
4147 {
4148         if (!window->xdg_surface)
4149                 return;
4150
4151         if (window->fullscreen == fullscreen)
4152                 return;
4153
4154         if (fullscreen)
4155                 xdg_surface_set_fullscreen(window->xdg_surface, NULL);
4156         else
4157                 xdg_surface_unset_fullscreen(window->xdg_surface);
4158 }
4159
4160 int
4161 window_is_maximized(struct window *window)
4162 {
4163         return window->maximized;
4164 }
4165
4166 void
4167 window_set_maximized(struct window *window, int maximized)
4168 {
4169         if (!window->xdg_surface)
4170                 return;
4171
4172         if (window->maximized == maximized)
4173                 return;
4174
4175         if (maximized)
4176                 xdg_surface_set_maximized(window->xdg_surface);
4177         else
4178                 xdg_surface_unset_maximized(window->xdg_surface);
4179 }
4180
4181 void
4182 window_set_minimized(struct window *window)
4183 {
4184         if (!window->xdg_surface)
4185                 return;
4186
4187         xdg_surface_set_minimized(window->xdg_surface);
4188 }
4189
4190 void
4191 window_set_user_data(struct window *window, void *data)
4192 {
4193         window->user_data = data;
4194 }
4195
4196 void *
4197 window_get_user_data(struct window *window)
4198 {
4199         return window->user_data;
4200 }
4201
4202 void
4203 window_set_key_handler(struct window *window,
4204                        window_key_handler_t handler)
4205 {
4206         window->key_handler = handler;
4207 }
4208
4209 void
4210 window_set_keyboard_focus_handler(struct window *window,
4211                                   window_keyboard_focus_handler_t handler)
4212 {
4213         window->keyboard_focus_handler = handler;
4214 }
4215
4216 void
4217 window_set_data_handler(struct window *window, window_data_handler_t handler)
4218 {
4219         window->data_handler = handler;
4220 }
4221
4222 void
4223 window_set_drop_handler(struct window *window, window_drop_handler_t handler)
4224 {
4225         window->drop_handler = handler;
4226 }
4227
4228 void
4229 window_set_close_handler(struct window *window,
4230                          window_close_handler_t handler)
4231 {
4232         window->close_handler = handler;
4233 }
4234
4235 void
4236 window_set_fullscreen_handler(struct window *window,
4237                               window_fullscreen_handler_t handler)
4238 {
4239         window->fullscreen_handler = handler;
4240 }
4241
4242 void
4243 window_set_output_handler(struct window *window,
4244                           window_output_handler_t handler)
4245 {
4246         window->output_handler = handler;
4247 }
4248
4249 void
4250 window_set_title(struct window *window, const char *title)
4251 {
4252         free(window->title);
4253         window->title = strdup(title);
4254         if (window->frame) {
4255                 frame_set_title(window->frame->frame, title);
4256                 widget_schedule_redraw(window->frame->widget);
4257         }
4258         if (window->xdg_surface)
4259                 xdg_surface_set_title(window->xdg_surface, title);
4260 }
4261
4262 const char *
4263 window_get_title(struct window *window)
4264 {
4265         return window->title;
4266 }
4267
4268 void
4269 window_set_text_cursor_position(struct window *window, int32_t x, int32_t y)
4270 {
4271         struct text_cursor_position *text_cursor_position =
4272                                         window->display->text_cursor_position;
4273
4274         if (!text_cursor_position)
4275                 return;
4276
4277         text_cursor_position_notify(text_cursor_position,
4278                                     window->main_surface->surface,
4279                                     wl_fixed_from_int(x),
4280                                     wl_fixed_from_int(y));
4281 }
4282
4283 void
4284 window_damage(struct window *window, int32_t x, int32_t y,
4285               int32_t width, int32_t height)
4286 {
4287         wl_surface_damage(window->main_surface->surface, x, y, width, height);
4288 }
4289
4290 static void
4291 surface_enter(void *data,
4292               struct wl_surface *wl_surface, struct wl_output *wl_output)
4293 {
4294         struct window *window = data;
4295         struct output *output;
4296         struct output *output_found = NULL;
4297         struct window_output *window_output;
4298
4299         wl_list_for_each(output, &window->display->output_list, link) {
4300                 if (output->output == wl_output) {
4301                         output_found = output;
4302                         break;
4303                 }
4304         }
4305
4306         if (!output_found)
4307                 return;
4308
4309         window_output = xmalloc(sizeof *window_output);
4310         window_output->output = output_found;
4311
4312         wl_list_insert (&window->window_output_list, &window_output->link);
4313
4314         if (window->output_handler)
4315                 window->output_handler(window, output_found, 1,
4316                                        window->user_data);
4317 }
4318
4319 static void
4320 surface_leave(void *data,
4321               struct wl_surface *wl_surface, struct wl_output *output)
4322 {
4323         struct window *window = data;
4324         struct window_output *window_output;
4325         struct window_output *window_output_found = NULL;
4326
4327         wl_list_for_each(window_output, &window->window_output_list, link) {
4328                 if (window_output->output->output == output) {
4329                         window_output_found = window_output;
4330                         break;
4331                 }
4332         }
4333
4334         if (window_output_found) {
4335                 wl_list_remove(&window_output_found->link);
4336
4337                 if (window->output_handler)
4338                         window->output_handler(window, window_output->output,
4339                                                0, window->user_data);
4340
4341                 free(window_output_found);
4342         }
4343 }
4344
4345 static const struct wl_surface_listener surface_listener = {
4346         surface_enter,
4347         surface_leave
4348 };
4349
4350 static struct surface *
4351 surface_create(struct window *window)
4352 {
4353         struct display *display = window->display;
4354         struct surface *surface;
4355
4356         surface = xmalloc(sizeof *surface);
4357         memset(surface, 0, sizeof *surface);
4358         if (!surface)
4359                 return NULL;
4360
4361         surface->window = window;
4362         surface->surface = wl_compositor_create_surface(display->compositor);
4363         surface->buffer_scale = 1;
4364         wl_surface_add_listener(surface->surface, &surface_listener, window);
4365
4366         wl_list_insert(&window->subsurface_list, &surface->link);
4367
4368         return surface;
4369 }
4370
4371 static enum window_buffer_type
4372 get_preferred_buffer_type(struct display *display)
4373 {
4374 #ifdef HAVE_CAIRO_EGL
4375         if (display->argb_device && !getenv("TOYTOOLKIT_NO_EGL"))
4376                 return WINDOW_BUFFER_TYPE_EGL_WINDOW;
4377 #endif
4378
4379         return WINDOW_BUFFER_TYPE_SHM;
4380 }
4381
4382 static struct window *
4383 window_create_internal(struct display *display, int custom)
4384 {
4385         struct window *window;
4386         struct surface *surface;
4387
4388         window = xzalloc(sizeof *window);
4389         wl_list_init(&window->subsurface_list);
4390         window->display = display;
4391
4392         surface = surface_create(window);
4393         window->main_surface = surface;
4394
4395         assert(custom || display->xdg_shell);
4396
4397         window->custom = custom;
4398         window->preferred_format = WINDOW_PREFERRED_FORMAT_NONE;
4399
4400         surface->buffer_type = get_preferred_buffer_type(display);
4401
4402         wl_surface_set_user_data(surface->surface, window);
4403         wl_list_insert(display->window_list.prev, &window->link);
4404         wl_list_init(&window->redraw_task.link);
4405
4406         wl_list_init (&window->window_output_list);
4407
4408         return window;
4409 }
4410
4411 struct window *
4412 window_create(struct display *display)
4413 {
4414         struct window *window;
4415
4416         window = window_create_internal(display, 0);
4417
4418         window->xdg_surface =
4419                 xdg_shell_get_xdg_surface(window->display->xdg_shell,
4420                                           window->main_surface->surface);
4421         fail_on_null(window->xdg_surface);
4422
4423         xdg_surface_set_user_data(window->xdg_surface, window);
4424         xdg_surface_add_listener(window->xdg_surface,
4425                                  &xdg_surface_listener, window);
4426
4427         return window;
4428 }
4429
4430 struct window *
4431 window_create_custom(struct display *display)
4432 {
4433         return window_create_internal(display, 1);
4434 }
4435
4436 void
4437 window_set_parent(struct window *window,
4438                   struct window *parent_window)
4439 {
4440         window->parent = parent_window;
4441         window_sync_parent(window);
4442 }
4443
4444 struct window *
4445 window_get_parent(struct window *window)
4446 {
4447         return window->parent;
4448 }
4449
4450 static void
4451 menu_set_item(struct menu *menu, int sy)
4452 {
4453         int32_t x, y, width, height;
4454         int next;
4455
4456         frame_interior(menu->frame, &x, &y, &width, &height);
4457         next = (sy - y) / 20;
4458         if (menu->current != next) {
4459                 menu->current = next;
4460                 widget_schedule_redraw(menu->widget);
4461         }
4462 }
4463
4464 static int
4465 menu_motion_handler(struct widget *widget,
4466                     struct input *input, uint32_t time,
4467                     float x, float y, void *data)
4468 {
4469         struct menu *menu = data;
4470
4471         if (widget == menu->widget)
4472                 menu_set_item(data, y);
4473
4474         return CURSOR_LEFT_PTR;
4475 }
4476
4477 static int
4478 menu_enter_handler(struct widget *widget,
4479                    struct input *input, float x, float y, void *data)
4480 {
4481         struct menu *menu = data;
4482
4483         if (widget == menu->widget)
4484                 menu_set_item(data, y);
4485
4486         return CURSOR_LEFT_PTR;
4487 }
4488
4489 static void
4490 menu_leave_handler(struct widget *widget, struct input *input, void *data)
4491 {
4492         struct menu *menu = data;
4493
4494         if (widget == menu->widget)
4495                 menu_set_item(data, -200);
4496 }
4497
4498 static void
4499 menu_button_handler(struct widget *widget,
4500                     struct input *input, uint32_t time,
4501                     uint32_t button, enum wl_pointer_button_state state,
4502                     void *data)
4503
4504 {
4505         struct menu *menu = data;
4506
4507         if (state == WL_POINTER_BUTTON_STATE_RELEASED &&
4508             (menu->release_count > 0 || time - menu->time > 500)) {
4509                 /* Either relase after press-drag-release or
4510                  * click-motion-click. */
4511                 menu->func(menu->parent, input,
4512                            menu->current, menu->parent->user_data);
4513                 input_ungrab(input);
4514                 menu_destroy(menu);
4515         } else if (state == WL_POINTER_BUTTON_STATE_RELEASED) {
4516                 menu->release_count++;
4517         }
4518 }
4519
4520 static void
4521 menu_touch_up_handler(struct widget *widget,
4522                                           struct input *input,
4523                                           uint32_t serial,
4524                                           uint32_t time,
4525                                           int32_t id,
4526                                           void *data)
4527 {
4528         struct menu *menu = data;
4529
4530         input_ungrab(input);
4531         menu_destroy(menu);
4532 }
4533
4534 static void
4535 menu_redraw_handler(struct widget *widget, void *data)
4536 {
4537         cairo_t *cr;
4538         struct menu *menu = data;
4539         int32_t x, y, width, height, i;
4540
4541         cr = widget_cairo_create(widget);
4542
4543         frame_repaint(menu->frame, cr);
4544         frame_interior(menu->frame, &x, &y, &width, &height);
4545
4546         theme_set_background_source(menu->window->display->theme,
4547                                     cr, THEME_FRAME_ACTIVE);
4548         cairo_rectangle(cr, x, y, width, height);
4549         cairo_fill(cr);
4550
4551         cairo_select_font_face(cr, "sans",
4552                                CAIRO_FONT_SLANT_NORMAL,
4553                                CAIRO_FONT_WEIGHT_NORMAL);
4554         cairo_set_font_size(cr, 12);
4555
4556         for (i = 0; i < menu->count; i++) {
4557                 if (i == menu->current) {
4558                         cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
4559                         cairo_rectangle(cr, x, y + i * 20, width, 20);
4560                         cairo_fill(cr);
4561                         cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
4562                         cairo_move_to(cr, x + 10, y + i * 20 + 16);
4563                         cairo_show_text(cr, menu->entries[i]);
4564                 } else {
4565                         cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
4566                         cairo_move_to(cr, x + 10, y + i * 20 + 16);
4567                         cairo_show_text(cr, menu->entries[i]);
4568                 }
4569         }
4570
4571         cairo_destroy(cr);
4572 }
4573
4574 static void
4575 handle_popup_popup_done(void *data, struct xdg_popup *xdg_popup, uint32_t serial)
4576 {
4577         struct window *window = data;
4578         struct menu *menu = window->main_surface->widget->user_data;
4579
4580         input_ungrab(menu->input);
4581         menu_destroy(menu);
4582 }
4583
4584 static const struct xdg_popup_listener xdg_popup_listener = {
4585         handle_popup_popup_done,
4586 };
4587
4588 void
4589 window_show_menu(struct display *display,
4590                  struct input *input, uint32_t time, struct window *parent,
4591                  int32_t x, int32_t y,
4592                  menu_func_t func, const char **entries, int count)
4593 {
4594         struct window *window;
4595         struct menu *menu;
4596         int32_t ix, iy;
4597
4598         menu = malloc(sizeof *menu);
4599         if (!menu)
4600                 return;
4601
4602         window = window_create_internal(parent->display, 0);
4603         if (!window) {
4604                 free(menu);
4605                 return;
4606         }
4607
4608         menu->window = window;
4609         menu->parent = parent;
4610         menu->widget = window_add_widget(menu->window, menu);
4611         window_set_buffer_scale (menu->window, window_get_buffer_scale (parent));
4612         window_set_buffer_transform (menu->window, window_get_buffer_transform (parent));
4613         menu->frame = frame_create(window->display->theme, 0, 0,
4614                                    FRAME_BUTTON_NONE, NULL);
4615         fail_on_null(menu->frame);
4616         menu->entries = entries;
4617         menu->count = count;
4618         menu->release_count = 0;
4619         menu->current = -1;
4620         menu->time = time;
4621         menu->func = func;
4622         menu->input = input;
4623         window->x = x;
4624         window->y = y;
4625
4626         input_ungrab(input);
4627
4628         widget_set_redraw_handler(menu->widget, menu_redraw_handler);
4629         widget_set_enter_handler(menu->widget, menu_enter_handler);
4630         widget_set_leave_handler(menu->widget, menu_leave_handler);
4631         widget_set_motion_handler(menu->widget, menu_motion_handler);
4632         widget_set_button_handler(menu->widget, menu_button_handler);
4633         widget_set_touch_up_handler(menu->widget, menu_touch_up_handler);
4634
4635         input_grab(input, menu->widget, 0);
4636         frame_resize_inside(menu->frame, 200, count * 20);
4637         frame_set_flag(menu->frame, FRAME_FLAG_ACTIVE);
4638         window_schedule_resize(window, frame_width(menu->frame),
4639                                frame_height(menu->frame));
4640
4641         frame_interior(menu->frame, &ix, &iy, NULL, NULL);
4642
4643         window->xdg_popup = xdg_shell_get_xdg_popup(display->xdg_shell,
4644                                                     window->main_surface->surface,
4645                                                     parent->main_surface->surface,
4646                                                     input->seat,
4647                                                     display_get_serial(window->display),
4648                                                     window->x - ix,
4649                                                     window->y - iy,
4650                                                     0);
4651         fail_on_null(window->xdg_popup);
4652
4653         xdg_popup_set_user_data(window->xdg_popup, window);
4654         xdg_popup_add_listener(window->xdg_popup,
4655                                &xdg_popup_listener, window);
4656 }
4657
4658 void
4659 window_set_buffer_type(struct window *window, enum window_buffer_type type)
4660 {
4661         window->main_surface->buffer_type = type;
4662 }
4663
4664 enum window_buffer_type
4665 window_get_buffer_type(struct window *window)
4666 {
4667         return window->main_surface->buffer_type;
4668 }
4669
4670 void
4671 window_set_preferred_format(struct window *window,
4672                             enum preferred_format format)
4673 {
4674         window->preferred_format = format;
4675 }
4676
4677 struct widget *
4678 window_add_subsurface(struct window *window, void *data,
4679                       enum subsurface_mode default_mode)
4680 {
4681         struct widget *widget;
4682         struct surface *surface;
4683         struct wl_surface *parent;
4684         struct wl_subcompositor *subcompo = window->display->subcompositor;
4685
4686         surface = surface_create(window);
4687         surface->buffer_type = window_get_buffer_type(window);
4688         widget = widget_create(window, surface, data);
4689         wl_list_init(&widget->link);
4690         surface->widget = widget;
4691
4692         parent = window->main_surface->surface;
4693         surface->subsurface = wl_subcompositor_get_subsurface(subcompo,
4694                                                               surface->surface,
4695                                                               parent);
4696         surface->synchronized = 1;
4697
4698         switch (default_mode) {
4699         case SUBSURFACE_SYNCHRONIZED:
4700                 surface->synchronized_default = 1;
4701                 break;
4702         case SUBSURFACE_DESYNCHRONIZED:
4703                 surface->synchronized_default = 0;
4704                 break;
4705         default:
4706                 assert(!"bad enum subsurface_mode");
4707         }
4708
4709         window->resize_needed = 1;
4710         window_schedule_redraw(window);
4711
4712         return widget;
4713 }
4714
4715 static void
4716 display_handle_geometry(void *data,
4717                         struct wl_output *wl_output,
4718                         int x, int y,
4719                         int physical_width,
4720                         int physical_height,
4721                         int subpixel,
4722                         const char *make,
4723                         const char *model,
4724                         int transform)
4725 {
4726         struct output *output = data;
4727
4728         output->allocation.x = x;
4729         output->allocation.y = y;
4730         output->transform = transform;
4731
4732         if (output->make)
4733                 free(output->make);
4734         output->make = strdup(make);
4735
4736         if (output->model)
4737                 free(output->model);
4738         output->model = strdup(model);
4739 }
4740
4741 static void
4742 display_handle_done(void *data,
4743                      struct wl_output *wl_output)
4744 {
4745 }
4746
4747 static void
4748 display_handle_scale(void *data,
4749                      struct wl_output *wl_output,
4750                      int32_t scale)
4751 {
4752         struct output *output = data;
4753
4754         output->scale = scale;
4755 }
4756
4757 static void
4758 display_handle_mode(void *data,
4759                     struct wl_output *wl_output,
4760                     uint32_t flags,
4761                     int width,
4762                     int height,
4763                     int refresh)
4764 {
4765         struct output *output = data;
4766         struct display *display = output->display;
4767
4768         if (flags & WL_OUTPUT_MODE_CURRENT) {
4769                 output->allocation.width = width;
4770                 output->allocation.height = height;
4771                 if (display->output_configure_handler)
4772                         (*display->output_configure_handler)(
4773                                                 output, display->user_data);
4774         }
4775 }
4776
4777 static const struct wl_output_listener output_listener = {
4778         display_handle_geometry,
4779         display_handle_mode,
4780         display_handle_done,
4781         display_handle_scale
4782 };
4783
4784 static void
4785 display_add_output(struct display *d, uint32_t id)
4786 {
4787         struct output *output;
4788
4789         output = xzalloc(sizeof *output);
4790         output->display = d;
4791         output->scale = 1;
4792         output->output =
4793                 wl_registry_bind(d->registry, id, &wl_output_interface, 2);
4794         output->server_output_id = id;
4795         wl_list_insert(d->output_list.prev, &output->link);
4796
4797         wl_output_add_listener(output->output, &output_listener, output);
4798 }
4799
4800 static void
4801 output_destroy(struct output *output)
4802 {
4803         if (output->destroy_handler)
4804                 (*output->destroy_handler)(output, output->user_data);
4805
4806         wl_output_destroy(output->output);
4807         wl_list_remove(&output->link);
4808         free(output);
4809 }
4810
4811 static void
4812 display_destroy_output(struct display *d, uint32_t id)
4813 {
4814         struct output *output;
4815
4816         wl_list_for_each(output, &d->output_list, link) {
4817                 if (output->server_output_id == id) {
4818                         output_destroy(output);
4819                         break;
4820                 }
4821         }
4822 }
4823
4824 void
4825 display_set_global_handler(struct display *display,
4826                            display_global_handler_t handler)
4827 {
4828         struct global *global;
4829
4830         display->global_handler = handler;
4831         if (!handler)
4832                 return;
4833
4834         wl_list_for_each(global, &display->global_list, link)
4835                 display->global_handler(display,
4836                                         global->name, global->interface,
4837                                         global->version, display->user_data);
4838 }
4839
4840 void
4841 display_set_global_handler_remove(struct display *display,
4842                            display_global_handler_t remove_handler)
4843 {
4844         display->global_handler_remove = remove_handler;
4845         if (!remove_handler)
4846                 return;
4847 }
4848
4849 void
4850 display_set_output_configure_handler(struct display *display,
4851                                      display_output_handler_t handler)
4852 {
4853         struct output *output;
4854
4855         display->output_configure_handler = handler;
4856         if (!handler)
4857                 return;
4858
4859         wl_list_for_each(output, &display->output_list, link) {
4860                 if (output->allocation.width == 0 &&
4861                     output->allocation.height == 0)
4862                         continue;
4863
4864                 (*display->output_configure_handler)(output,
4865                                                      display->user_data);
4866         }
4867 }
4868
4869 void
4870 output_set_user_data(struct output *output, void *data)
4871 {
4872         output->user_data = data;
4873 }
4874
4875 void *
4876 output_get_user_data(struct output *output)
4877 {
4878         return output->user_data;
4879 }
4880
4881 void
4882 output_set_destroy_handler(struct output *output,
4883                            display_output_handler_t handler)
4884 {
4885         output->destroy_handler = handler;
4886         /* FIXME: implement this, once we have way to remove outputs */
4887 }
4888
4889 void
4890 output_get_allocation(struct output *output, struct rectangle *base)
4891 {
4892         struct rectangle allocation = output->allocation;
4893
4894         switch (output->transform) {
4895         case WL_OUTPUT_TRANSFORM_90:
4896         case WL_OUTPUT_TRANSFORM_270:
4897         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
4898         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
4899                 /* Swap width and height */
4900                 allocation.width = output->allocation.height;
4901                 allocation.height = output->allocation.width;
4902                 break;
4903         }
4904
4905         *base = allocation;
4906 }
4907
4908 struct wl_output *
4909 output_get_wl_output(struct output *output)
4910 {
4911         return output->output;
4912 }
4913
4914 enum wl_output_transform
4915 output_get_transform(struct output *output)
4916 {
4917         return output->transform;
4918 }
4919
4920 uint32_t
4921 output_get_scale(struct output *output)
4922 {
4923         return output->scale;
4924 }
4925
4926 const char *
4927 output_get_make(struct output *output)
4928 {
4929         return output->make;
4930 }
4931
4932 const char *
4933 output_get_model(struct output *output)
4934 {
4935         return output->model;
4936 }
4937
4938 static void
4939 fini_xkb(struct input *input)
4940 {
4941         xkb_state_unref(input->xkb.state);
4942         xkb_map_unref(input->xkb.keymap);
4943 }
4944
4945 #define MIN(a,b) ((a) < (b) ? a : b)
4946
4947 static void
4948 display_add_input(struct display *d, uint32_t id)
4949 {
4950         struct input *input;
4951
4952         input = xzalloc(sizeof *input);
4953         input->display = d;
4954         input->seat = wl_registry_bind(d->registry, id, &wl_seat_interface,
4955                                        MIN(d->seat_version, 3));
4956         input->touch_focus = NULL;
4957         input->pointer_focus = NULL;
4958         input->keyboard_focus = NULL;
4959         wl_list_init(&input->touch_point_list);
4960         wl_list_insert(d->input_list.prev, &input->link);
4961
4962         wl_seat_add_listener(input->seat, &seat_listener, input);
4963         wl_seat_set_user_data(input->seat, input);
4964
4965         if (d->data_device_manager) {
4966                 input->data_device =
4967                         wl_data_device_manager_get_data_device(d->data_device_manager,
4968                                                                input->seat);
4969                 wl_data_device_add_listener(input->data_device,
4970                                             &data_device_listener,
4971                                             input);
4972         }
4973
4974         input->pointer_surface = wl_compositor_create_surface(d->compositor);
4975
4976         input->repeat_timer_fd = timerfd_create(CLOCK_MONOTONIC,
4977                                                 TFD_CLOEXEC | TFD_NONBLOCK);
4978         input->repeat_task.run = keyboard_repeat_func;
4979         display_watch_fd(d, input->repeat_timer_fd,
4980                          EPOLLIN, &input->repeat_task);
4981 }
4982
4983 static void
4984 input_destroy(struct input *input)
4985 {
4986         input_remove_keyboard_focus(input);
4987         input_remove_pointer_focus(input);
4988
4989         if (input->drag_offer)
4990                 data_offer_destroy(input->drag_offer);
4991
4992         if (input->selection_offer)
4993                 data_offer_destroy(input->selection_offer);
4994
4995         if (input->data_device)
4996                 wl_data_device_destroy(input->data_device);
4997
4998         if (input->display->seat_version >= 3) {
4999                 if (input->pointer)
5000                         wl_pointer_release(input->pointer);
5001                 if (input->keyboard)
5002                         wl_keyboard_release(input->keyboard);
5003         }
5004
5005         fini_xkb(input);
5006
5007         wl_surface_destroy(input->pointer_surface);
5008
5009         wl_list_remove(&input->link);
5010         wl_seat_destroy(input->seat);
5011         close(input->repeat_timer_fd);
5012         free(input);
5013 }
5014
5015 static void
5016 init_workspace_manager(struct display *d, uint32_t id)
5017 {
5018         d->workspace_manager =
5019                 wl_registry_bind(d->registry, id,
5020                                  &workspace_manager_interface, 1);
5021         if (d->workspace_manager != NULL)
5022                 workspace_manager_add_listener(d->workspace_manager,
5023                                                &workspace_manager_listener,
5024                                                d);
5025 }
5026
5027 static void
5028 shm_format(void *data, struct wl_shm *wl_shm, uint32_t format)
5029 {
5030         struct display *d = data;
5031
5032         if (format == WL_SHM_FORMAT_RGB565)
5033                 d->has_rgb565 = 1;
5034 }
5035
5036 struct wl_shm_listener shm_listener = {
5037         shm_format
5038 };
5039
5040 static void
5041 xdg_shell_ping(void *data, struct xdg_shell *shell, uint32_t serial)
5042 {
5043         xdg_shell_pong(shell, serial);
5044 }
5045
5046 static const struct xdg_shell_listener xdg_shell_listener = {
5047         xdg_shell_ping,
5048 };
5049
5050 #define XDG_VERSION 3 /* The version of xdg-shell that we implement */
5051 #ifdef static_assert
5052 static_assert(XDG_VERSION == XDG_SHELL_VERSION_CURRENT,
5053               "Interface version doesn't match implementation version");
5054 #endif
5055
5056 static void
5057 registry_handle_global(void *data, struct wl_registry *registry, uint32_t id,
5058                        const char *interface, uint32_t version)
5059 {
5060         struct display *d = data;
5061         struct global *global;
5062
5063         global = xmalloc(sizeof *global);
5064         global->name = id;
5065         global->interface = strdup(interface);
5066         global->version = version;
5067         wl_list_insert(d->global_list.prev, &global->link);
5068
5069         if (strcmp(interface, "wl_compositor") == 0) {
5070                 d->compositor = wl_registry_bind(registry, id,
5071                                                  &wl_compositor_interface, 3);
5072         } else if (strcmp(interface, "wl_output") == 0) {
5073                 display_add_output(d, id);
5074         } else if (strcmp(interface, "wl_seat") == 0) {
5075                 d->seat_version = version;
5076                 display_add_input(d, id);
5077         } else if (strcmp(interface, "wl_shm") == 0) {
5078                 d->shm = wl_registry_bind(registry, id, &wl_shm_interface, 1);
5079                 wl_shm_add_listener(d->shm, &shm_listener, d);
5080         } else if (strcmp(interface, "wl_data_device_manager") == 0) {
5081                 d->data_device_manager =
5082                         wl_registry_bind(registry, id,
5083                                          &wl_data_device_manager_interface, 1);
5084         } else if (strcmp(interface, "xdg_shell") == 0) {
5085                 d->xdg_shell = wl_registry_bind(registry, id,
5086                                                 &xdg_shell_interface, 1);
5087                 xdg_shell_use_unstable_version(d->xdg_shell, XDG_VERSION);
5088                 xdg_shell_add_listener(d->xdg_shell, &xdg_shell_listener, d);
5089         } else if (strcmp(interface, "text_cursor_position") == 0) {
5090                 d->text_cursor_position =
5091                         wl_registry_bind(registry, id,
5092                                          &text_cursor_position_interface, 1);
5093         } else if (strcmp(interface, "workspace_manager") == 0) {
5094                 init_workspace_manager(d, id);
5095         } else if (strcmp(interface, "wl_subcompositor") == 0) {
5096                 d->subcompositor =
5097                         wl_registry_bind(registry, id,
5098                                          &wl_subcompositor_interface, 1);
5099         }
5100
5101         if (d->global_handler)
5102                 d->global_handler(d, id, interface, version, d->user_data);
5103 }
5104
5105 static void
5106 registry_handle_global_remove(void *data, struct wl_registry *registry,
5107                               uint32_t name)
5108 {
5109         struct display *d = data;
5110         struct global *global;
5111         struct global *tmp;
5112
5113         wl_list_for_each_safe(global, tmp, &d->global_list, link) {
5114                 if (global->name != name)
5115                         continue;
5116
5117                 if (strcmp(global->interface, "wl_output") == 0)
5118                         display_destroy_output(d, name);
5119
5120                 /* XXX: Should destroy remaining bound globals */
5121
5122                 if (d->global_handler_remove)
5123                         d->global_handler_remove(d, name, global->interface,
5124                                         global->version, d->user_data);
5125
5126                 wl_list_remove(&global->link);
5127                 free(global->interface);
5128                 free(global);
5129         }
5130 }
5131
5132 void *
5133 display_bind(struct display *display, uint32_t name,
5134              const struct wl_interface *interface, uint32_t version)
5135 {
5136         return wl_registry_bind(display->registry, name, interface, version);
5137 }
5138
5139 static const struct wl_registry_listener registry_listener = {
5140         registry_handle_global,
5141         registry_handle_global_remove
5142 };
5143
5144 #ifdef HAVE_CAIRO_EGL
5145 static int
5146 init_egl(struct display *d)
5147 {
5148         EGLint major, minor;
5149         EGLint n;
5150
5151 #ifdef USE_CAIRO_GLESV2
5152 #  define GL_BIT EGL_OPENGL_ES2_BIT
5153 #else
5154 #  define GL_BIT EGL_OPENGL_BIT
5155 #endif
5156
5157         static const EGLint argb_cfg_attribs[] = {
5158                 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
5159                 EGL_RED_SIZE, 1,
5160                 EGL_GREEN_SIZE, 1,
5161                 EGL_BLUE_SIZE, 1,
5162                 EGL_ALPHA_SIZE, 1,
5163                 EGL_DEPTH_SIZE, 1,
5164                 EGL_RENDERABLE_TYPE, GL_BIT,
5165                 EGL_NONE
5166         };
5167
5168 #ifdef USE_CAIRO_GLESV2
5169         static const EGLint context_attribs[] = {
5170                 EGL_CONTEXT_CLIENT_VERSION, 2,
5171                 EGL_NONE
5172         };
5173         EGLint api = EGL_OPENGL_ES_API;
5174 #else
5175         EGLint *context_attribs = NULL;
5176         EGLint api = EGL_OPENGL_API;
5177 #endif
5178
5179         d->dpy = eglGetDisplay(d->display);
5180         if (!eglInitialize(d->dpy, &major, &minor)) {
5181                 fprintf(stderr, "failed to initialize EGL\n");
5182                 return -1;
5183         }
5184
5185         if (!eglBindAPI(api)) {
5186                 fprintf(stderr, "failed to bind EGL client API\n");
5187                 return -1;
5188         }
5189
5190         if (!eglChooseConfig(d->dpy, argb_cfg_attribs,
5191                              &d->argb_config, 1, &n) || n != 1) {
5192                 fprintf(stderr, "failed to choose argb EGL config\n");
5193                 return -1;
5194         }
5195
5196         d->argb_ctx = eglCreateContext(d->dpy, d->argb_config,
5197                                        EGL_NO_CONTEXT, context_attribs);
5198         if (d->argb_ctx == NULL) {
5199                 fprintf(stderr, "failed to create EGL context\n");
5200                 return -1;
5201         }
5202
5203         d->argb_device = cairo_egl_device_create(d->dpy, d->argb_ctx);
5204         if (cairo_device_status(d->argb_device) != CAIRO_STATUS_SUCCESS) {
5205                 fprintf(stderr, "failed to get cairo EGL argb device\n");
5206                 return -1;
5207         }
5208
5209         return 0;
5210 }
5211
5212 static void
5213 fini_egl(struct display *display)
5214 {
5215         cairo_device_destroy(display->argb_device);
5216
5217         eglMakeCurrent(display->dpy, EGL_NO_SURFACE, EGL_NO_SURFACE,
5218                        EGL_NO_CONTEXT);
5219
5220         eglTerminate(display->dpy);
5221         eglReleaseThread();
5222 }
5223 #endif
5224
5225 static void
5226 init_dummy_surface(struct display *display)
5227 {
5228         int len;
5229         void *data;
5230
5231         len = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, 1);
5232         data = malloc(len);
5233         display->dummy_surface =
5234                 cairo_image_surface_create_for_data(data, CAIRO_FORMAT_ARGB32,
5235                                                     1, 1, len);
5236         display->dummy_surface_data = data;
5237 }
5238
5239 static void
5240 handle_display_data(struct task *task, uint32_t events)
5241 {
5242         struct display *display =
5243                 container_of(task, struct display, display_task);
5244         struct epoll_event ep;
5245         int ret;
5246
5247         display->display_fd_events = events;
5248
5249         if (events & EPOLLERR || events & EPOLLHUP) {
5250                 display_exit(display);
5251                 return;
5252         }
5253
5254         if (events & EPOLLIN) {
5255                 ret = wl_display_dispatch(display->display);
5256                 if (ret == -1) {
5257                         display_exit(display);
5258                         return;
5259                 }
5260         }
5261
5262         if (events & EPOLLOUT) {
5263                 ret = wl_display_flush(display->display);
5264                 if (ret == 0) {
5265                         ep.events = EPOLLIN | EPOLLERR | EPOLLHUP;
5266                         ep.data.ptr = &display->display_task;
5267                         epoll_ctl(display->epoll_fd, EPOLL_CTL_MOD,
5268                                   display->display_fd, &ep);
5269                 } else if (ret == -1 && errno != EAGAIN) {
5270                         display_exit(display);
5271                         return;
5272                 }
5273         }
5274 }
5275
5276 static void
5277 log_handler(const char *format, va_list args)
5278 {
5279         vfprintf(stderr, format, args);
5280 }
5281
5282 struct display *
5283 display_create(int *argc, char *argv[])
5284 {
5285         struct display *d;
5286
5287         wl_log_set_handler_client(log_handler);
5288
5289         d = zalloc(sizeof *d);
5290         if (d == NULL)
5291                 return NULL;
5292
5293         d->display = wl_display_connect(NULL);
5294         if (d->display == NULL) {
5295                 fprintf(stderr, "failed to connect to Wayland display: %m\n");
5296                 free(d);
5297                 return NULL;
5298         }
5299
5300         d->xkb_context = xkb_context_new(0);
5301         if (d->xkb_context == NULL) {
5302                 fprintf(stderr, "Failed to create XKB context\n");
5303                 free(d);
5304                 return NULL;
5305         }
5306
5307         d->epoll_fd = os_epoll_create_cloexec();
5308         d->display_fd = wl_display_get_fd(d->display);
5309         d->display_task.run = handle_display_data;
5310         display_watch_fd(d, d->display_fd, EPOLLIN | EPOLLERR | EPOLLHUP,
5311                          &d->display_task);
5312
5313         wl_list_init(&d->deferred_list);
5314         wl_list_init(&d->input_list);
5315         wl_list_init(&d->output_list);
5316         wl_list_init(&d->global_list);
5317
5318         d->workspace = 0;
5319         d->workspace_count = 1;
5320
5321         d->registry = wl_display_get_registry(d->display);
5322         wl_registry_add_listener(d->registry, &registry_listener, d);
5323
5324         if (wl_display_dispatch(d->display) < 0) {
5325                 fprintf(stderr, "Failed to process Wayland connection: %m\n");
5326                 return NULL;
5327         }
5328
5329 #ifdef HAVE_CAIRO_EGL
5330         if (init_egl(d) < 0)
5331                 fprintf(stderr, "EGL does not seem to work, "
5332                         "falling back to software rendering and wl_shm.\n");
5333 #endif
5334
5335         create_cursors(d);
5336
5337         d->theme = theme_create();
5338
5339         wl_list_init(&d->window_list);
5340
5341         init_dummy_surface(d);
5342
5343         return d;
5344 }
5345
5346 static void
5347 display_destroy_outputs(struct display *display)
5348 {
5349         struct output *tmp;
5350         struct output *output;
5351
5352         wl_list_for_each_safe(output, tmp, &display->output_list, link)
5353                 output_destroy(output);
5354 }
5355
5356 static void
5357 display_destroy_inputs(struct display *display)
5358 {
5359         struct input *tmp;
5360         struct input *input;
5361
5362         wl_list_for_each_safe(input, tmp, &display->input_list, link)
5363                 input_destroy(input);
5364 }
5365
5366 void
5367 display_destroy(struct display *display)
5368 {
5369         if (!wl_list_empty(&display->window_list))
5370                 fprintf(stderr, "toytoolkit warning: %d windows exist.\n",
5371                         wl_list_length(&display->window_list));
5372
5373         if (!wl_list_empty(&display->deferred_list))
5374                 fprintf(stderr, "toytoolkit warning: deferred tasks exist.\n");
5375
5376         cairo_surface_destroy(display->dummy_surface);
5377         free(display->dummy_surface_data);
5378
5379         display_destroy_outputs(display);
5380         display_destroy_inputs(display);
5381
5382         xkb_context_unref(display->xkb_context);
5383
5384         theme_destroy(display->theme);
5385         destroy_cursors(display);
5386
5387 #ifdef HAVE_CAIRO_EGL
5388         if (display->argb_device)
5389                 fini_egl(display);
5390 #endif
5391
5392         if (display->subcompositor)
5393                 wl_subcompositor_destroy(display->subcompositor);
5394
5395         if (display->xdg_shell)
5396                 xdg_shell_destroy(display->xdg_shell);
5397
5398         if (display->shm)
5399                 wl_shm_destroy(display->shm);
5400
5401         if (display->data_device_manager)
5402                 wl_data_device_manager_destroy(display->data_device_manager);
5403
5404         wl_compositor_destroy(display->compositor);
5405         wl_registry_destroy(display->registry);
5406
5407         close(display->epoll_fd);
5408
5409         if (!(display->display_fd_events & EPOLLERR) &&
5410             !(display->display_fd_events & EPOLLHUP))
5411                 wl_display_flush(display->display);
5412
5413         wl_display_disconnect(display->display);
5414         free(display);
5415 }
5416
5417 void
5418 display_set_user_data(struct display *display, void *data)
5419 {
5420         display->user_data = data;
5421 }
5422
5423 void *
5424 display_get_user_data(struct display *display)
5425 {
5426         return display->user_data;
5427 }
5428
5429 struct wl_display *
5430 display_get_display(struct display *display)
5431 {
5432         return display->display;
5433 }
5434
5435 int
5436 display_has_subcompositor(struct display *display)
5437 {
5438         if (display->subcompositor)
5439                 return 1;
5440
5441         wl_display_roundtrip(display->display);
5442
5443         return display->subcompositor != NULL;
5444 }
5445
5446 cairo_device_t *
5447 display_get_cairo_device(struct display *display)
5448 {
5449         return display->argb_device;
5450 }
5451
5452 struct output *
5453 display_get_output(struct display *display)
5454 {
5455         return container_of(display->output_list.next, struct output, link);
5456 }
5457
5458 struct wl_compositor *
5459 display_get_compositor(struct display *display)
5460 {
5461         return display->compositor;
5462 }
5463
5464 uint32_t
5465 display_get_serial(struct display *display)
5466 {
5467         return display->serial;
5468 }
5469
5470 EGLDisplay
5471 display_get_egl_display(struct display *d)
5472 {
5473         return d->dpy;
5474 }
5475
5476 struct wl_data_source *
5477 display_create_data_source(struct display *display)
5478 {
5479         if (display->data_device_manager)
5480                 return wl_data_device_manager_create_data_source(display->data_device_manager);
5481         else
5482                 return NULL;
5483 }
5484
5485 EGLConfig
5486 display_get_argb_egl_config(struct display *d)
5487 {
5488         return d->argb_config;
5489 }
5490
5491 int
5492 display_acquire_window_surface(struct display *display,
5493                                struct window *window,
5494                                EGLContext ctx)
5495 {
5496         struct surface *surface = window->main_surface;
5497
5498         if (surface->buffer_type != WINDOW_BUFFER_TYPE_EGL_WINDOW)
5499                 return -1;
5500
5501         widget_get_cairo_surface(window->main_surface->widget);
5502         return surface->toysurface->acquire(surface->toysurface, ctx);
5503 }
5504
5505 void
5506 display_release_window_surface(struct display *display,
5507                                struct window *window)
5508 {
5509         struct surface *surface = window->main_surface;
5510
5511         if (surface->buffer_type != WINDOW_BUFFER_TYPE_EGL_WINDOW)
5512                 return;
5513
5514         surface->toysurface->release(surface->toysurface);
5515 }
5516
5517 void
5518 display_defer(struct display *display, struct task *task)
5519 {
5520         wl_list_insert(&display->deferred_list, &task->link);
5521 }
5522
5523 void
5524 display_watch_fd(struct display *display,
5525                  int fd, uint32_t events, struct task *task)
5526 {
5527         struct epoll_event ep;
5528
5529         ep.events = events;
5530         ep.data.ptr = task;
5531         epoll_ctl(display->epoll_fd, EPOLL_CTL_ADD, fd, &ep);
5532 }
5533
5534 void
5535 display_unwatch_fd(struct display *display, int fd)
5536 {
5537         epoll_ctl(display->epoll_fd, EPOLL_CTL_DEL, fd, NULL);
5538 }
5539
5540 void
5541 display_run(struct display *display)
5542 {
5543         struct task *task;
5544         struct epoll_event ep[16];
5545         int i, count, ret;
5546
5547         display->running = 1;
5548         while (1) {
5549                 while (!wl_list_empty(&display->deferred_list)) {
5550                         task = container_of(display->deferred_list.prev,
5551                                             struct task, link);
5552                         wl_list_remove(&task->link);
5553                         task->run(task, 0);
5554                 }
5555
5556                 wl_display_dispatch_pending(display->display);
5557
5558                 if (!display->running)
5559                         break;
5560
5561                 ret = wl_display_flush(display->display);
5562                 if (ret < 0 && errno == EAGAIN) {
5563                         ep[0].events =
5564                                 EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLHUP;
5565                         ep[0].data.ptr = &display->display_task;
5566
5567                         epoll_ctl(display->epoll_fd, EPOLL_CTL_MOD,
5568                                   display->display_fd, &ep[0]);
5569                 } else if (ret < 0) {
5570                         break;
5571                 }
5572
5573                 count = epoll_wait(display->epoll_fd,
5574                                    ep, ARRAY_LENGTH(ep), -1);
5575                 for (i = 0; i < count; i++) {
5576                         task = ep[i].data.ptr;
5577                         task->run(task, ep[i].events);
5578                 }
5579         }
5580 }
5581
5582 void
5583 display_exit(struct display *display)
5584 {
5585         display->running = 0;
5586 }
5587
5588 void
5589 keysym_modifiers_add(struct wl_array *modifiers_map,
5590                      const char *name)
5591 {
5592         size_t len = strlen(name) + 1;
5593         char *p;
5594
5595         p = wl_array_add(modifiers_map, len);
5596
5597         if (p == NULL)
5598                 return;
5599
5600         strncpy(p, name, len);
5601 }
5602
5603 static xkb_mod_index_t
5604 keysym_modifiers_get_index(struct wl_array *modifiers_map,
5605                            const char *name)
5606 {
5607         xkb_mod_index_t index = 0;
5608         char *p = modifiers_map->data;
5609
5610         while ((const char *)p < (const char *)(modifiers_map->data + modifiers_map->size)) {
5611                 if (strcmp(p, name) == 0)
5612                         return index;
5613
5614                 index++;
5615                 p += strlen(p) + 1;
5616         }
5617
5618         return XKB_MOD_INVALID;
5619 }
5620
5621 xkb_mod_mask_t
5622 keysym_modifiers_get_mask(struct wl_array *modifiers_map,
5623                           const char *name)
5624 {
5625         xkb_mod_index_t index = keysym_modifiers_get_index(modifiers_map, name);
5626
5627         if (index == XKB_MOD_INVALID)
5628                 return XKB_MOD_INVALID;
5629
5630         return 1 << index;
5631 }
5632
5633 void *
5634 fail_on_null(void *p)
5635 {
5636         if (p == NULL) {
5637                 fprintf(stderr, "%s: out of memory\n", program_invocation_short_name);
5638                 exit(EXIT_FAILURE);
5639         }
5640
5641         return p;
5642 }
5643
5644 void *
5645 xmalloc(size_t s)
5646 {
5647         return fail_on_null(malloc(s));
5648 }
5649
5650 void *
5651 xzalloc(size_t s)
5652 {
5653         return fail_on_null(zalloc(s));
5654 }
5655
5656 char *
5657 xstrdup(const char *s)
5658 {
5659         return fail_on_null(strdup(s));
5660 }
5661
5662 void *
5663 xrealloc(char *p, size_t s)
5664 {
5665         return fail_on_null(realloc(p, s));
5666 }