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