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