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