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