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