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