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