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