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