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