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