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