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