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