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