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