westoy: Add an option to explicitly disable cairo on a widget
[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                 free(widget->tooltip);
1658                 widget->tooltip = NULL;
1659         }
1660
1661         wl_list_for_each(input, &display->input_list, link) {
1662                 if (input->focus_widget == widget)
1663                         input->focus_widget = NULL;
1664         }
1665
1666         wl_list_remove(&widget->link);
1667         free(widget);
1668 }
1669
1670 void
1671 widget_set_default_cursor(struct widget *widget, int cursor)
1672 {
1673         widget->default_cursor = cursor;
1674 }
1675
1676 void
1677 widget_get_allocation(struct widget *widget, struct rectangle *allocation)
1678 {
1679         *allocation = widget->allocation;
1680 }
1681
1682 void
1683 widget_set_size(struct widget *widget, int32_t width, int32_t height)
1684 {
1685         widget->allocation.width = width;
1686         widget->allocation.height = height;
1687 }
1688
1689 void
1690 widget_set_allocation(struct widget *widget,
1691                       int32_t x, int32_t y, int32_t width, int32_t height)
1692 {
1693         widget->allocation.x = x;
1694         widget->allocation.y = y;
1695         widget_set_size(widget, width, height);
1696 }
1697
1698 void
1699 widget_set_transparent(struct widget *widget, int transparent)
1700 {
1701         widget->opaque = !transparent;
1702 }
1703
1704 void *
1705 widget_get_user_data(struct widget *widget)
1706 {
1707         return widget->user_data;
1708 }
1709
1710 static cairo_surface_t *
1711 widget_get_cairo_surface(struct widget *widget)
1712 {
1713         struct surface *surface = widget->surface;
1714         struct window *window = widget->window;
1715
1716         assert(widget->use_cairo);
1717
1718         if (!surface->cairo_surface) {
1719                 if (surface == window->main_surface)
1720                         window_create_main_surface(window);
1721                 else
1722                         surface_create_surface(surface, 0, 0, 0);
1723         }
1724
1725         return surface->cairo_surface;
1726 }
1727
1728 static void
1729 widget_cairo_update_transform(struct widget *widget, cairo_t *cr)
1730 {
1731         struct surface *surface = widget->surface;
1732         double angle;
1733         cairo_matrix_t m;
1734         enum wl_output_transform transform;
1735         int surface_width, surface_height;
1736         int translate_x, translate_y;
1737         int32_t scale;
1738
1739         surface_width = surface->allocation.width;
1740         surface_height = surface->allocation.height;
1741
1742         transform = surface->buffer_transform;
1743         scale = surface->buffer_scale;
1744
1745         switch (transform) {
1746         case WL_OUTPUT_TRANSFORM_FLIPPED:
1747         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
1748         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
1749         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
1750                 cairo_matrix_init(&m, -1, 0, 0, 1, 0, 0);
1751                 break;
1752         default:
1753                 cairo_matrix_init_identity(&m);
1754                 break;
1755         }
1756
1757         switch (transform) {
1758         case WL_OUTPUT_TRANSFORM_NORMAL:
1759         default:
1760                 angle = 0;
1761                 translate_x = 0;
1762                 translate_y = 0;
1763                 break;
1764         case WL_OUTPUT_TRANSFORM_FLIPPED:
1765                 angle = 0;
1766                 translate_x = surface_width;
1767                 translate_y = 0;
1768                 break;
1769         case WL_OUTPUT_TRANSFORM_90:
1770                 angle = M_PI_2;
1771                 translate_x = surface_height;
1772                 translate_y = 0;
1773                 break;
1774         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
1775                 angle = M_PI_2;
1776                 translate_x = surface_height;
1777                 translate_y = surface_width;
1778                 break;
1779         case WL_OUTPUT_TRANSFORM_180:
1780                 angle = M_PI;
1781                 translate_x = surface_width;
1782                 translate_y = surface_height;
1783                 break;
1784         case WL_OUTPUT_TRANSFORM_FLIPPED_180:
1785                 angle = M_PI;
1786                 translate_x = 0;
1787                 translate_y = surface_height;
1788                 break;
1789         case WL_OUTPUT_TRANSFORM_270:
1790                 angle = M_PI + M_PI_2;
1791                 translate_x = 0;
1792                 translate_y = surface_width;
1793                 break;
1794         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
1795                 angle = M_PI + M_PI_2;
1796                 translate_x = 0;
1797                 translate_y = 0;
1798                 break;
1799         }
1800
1801         cairo_scale(cr, scale, scale);
1802         cairo_translate(cr, translate_x, translate_y);
1803         cairo_rotate(cr, angle);
1804         cairo_transform(cr, &m);
1805 }
1806
1807 cairo_t *
1808 widget_cairo_create(struct widget *widget)
1809 {
1810         struct surface *surface = widget->surface;
1811         cairo_surface_t *cairo_surface;
1812         cairo_t *cr;
1813
1814         cairo_surface = widget_get_cairo_surface(widget);
1815         cr = cairo_create(cairo_surface);
1816
1817         widget_cairo_update_transform(widget, cr);
1818
1819         cairo_translate(cr, -surface->allocation.x, -surface->allocation.y);
1820
1821         return cr;
1822 }
1823
1824 struct wl_surface *
1825 widget_get_wl_surface(struct widget *widget)
1826 {
1827         return widget->surface->surface;
1828 }
1829
1830 struct wl_subsurface *
1831 widget_get_wl_subsurface(struct widget *widget)
1832 {
1833         return widget->surface->subsurface;
1834 }
1835
1836 uint32_t
1837 widget_get_last_time(struct widget *widget)
1838 {
1839         return widget->surface->last_time;
1840 }
1841
1842 void
1843 widget_input_region_add(struct widget *widget, const struct rectangle *rect)
1844 {
1845         struct wl_compositor *comp = widget->window->display->compositor;
1846         struct surface *surface = widget->surface;
1847
1848         if (!surface->input_region)
1849                 surface->input_region = wl_compositor_create_region(comp);
1850
1851         if (rect) {
1852                 wl_region_add(surface->input_region,
1853                               rect->x, rect->y, rect->width, rect->height);
1854         }
1855 }
1856
1857 void
1858 widget_set_resize_handler(struct widget *widget,
1859                           widget_resize_handler_t handler)
1860 {
1861         widget->resize_handler = handler;
1862 }
1863
1864 void
1865 widget_set_redraw_handler(struct widget *widget,
1866                           widget_redraw_handler_t handler)
1867 {
1868         widget->redraw_handler = handler;
1869 }
1870
1871 void
1872 widget_set_enter_handler(struct widget *widget, widget_enter_handler_t handler)
1873 {
1874         widget->enter_handler = handler;
1875 }
1876
1877 void
1878 widget_set_leave_handler(struct widget *widget, widget_leave_handler_t handler)
1879 {
1880         widget->leave_handler = handler;
1881 }
1882
1883 void
1884 widget_set_motion_handler(struct widget *widget,
1885                           widget_motion_handler_t handler)
1886 {
1887         widget->motion_handler = handler;
1888 }
1889
1890 void
1891 widget_set_button_handler(struct widget *widget,
1892                           widget_button_handler_t handler)
1893 {
1894         widget->button_handler = handler;
1895 }
1896
1897 void
1898 widget_set_touch_up_handler(struct widget *widget,
1899                             widget_touch_up_handler_t handler)
1900 {
1901         widget->touch_up_handler = handler;
1902 }
1903
1904 void
1905 widget_set_touch_down_handler(struct widget *widget,
1906                               widget_touch_down_handler_t handler)
1907 {
1908         widget->touch_down_handler = handler;
1909 }
1910
1911 void
1912 widget_set_touch_motion_handler(struct widget *widget,
1913                                 widget_touch_motion_handler_t handler)
1914 {
1915         widget->touch_motion_handler = handler;
1916 }
1917
1918 void
1919 widget_set_touch_frame_handler(struct widget *widget,
1920                                widget_touch_frame_handler_t handler)
1921 {
1922         widget->touch_frame_handler = handler;
1923 }
1924
1925 void
1926 widget_set_touch_cancel_handler(struct widget *widget,
1927                                 widget_touch_cancel_handler_t handler)
1928 {
1929         widget->touch_cancel_handler = handler;
1930 }
1931
1932 void
1933 widget_set_axis_handler(struct widget *widget,
1934                         widget_axis_handler_t handler)
1935 {
1936         widget->axis_handler = handler;
1937 }
1938
1939 static void
1940 window_schedule_redraw_task(struct window *window);
1941
1942 void
1943 widget_schedule_redraw(struct widget *widget)
1944 {
1945         DBG_OBJ(widget->surface->surface, "widget %p\n", widget);
1946         widget->surface->redraw_needed = 1;
1947         window_schedule_redraw_task(widget->window);
1948 }
1949
1950 void
1951 widget_set_use_cairo(struct widget *widget,
1952                      int use_cairo)
1953 {
1954         widget->use_cairo = use_cairo;
1955 }
1956
1957 cairo_surface_t *
1958 window_get_surface(struct window *window)
1959 {
1960         cairo_surface_t *cairo_surface;
1961
1962         cairo_surface = widget_get_cairo_surface(window->main_surface->widget);
1963
1964         return cairo_surface_reference(cairo_surface);
1965 }
1966
1967 struct wl_surface *
1968 window_get_wl_surface(struct window *window)
1969 {
1970         return window->main_surface->surface;
1971 }
1972
1973 static void
1974 tooltip_redraw_handler(struct widget *widget, void *data)
1975 {
1976         cairo_t *cr;
1977         const int32_t r = 3;
1978         struct tooltip *tooltip = data;
1979         int32_t width, height;
1980
1981         cr = widget_cairo_create(widget);
1982         cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
1983         cairo_set_source_rgba(cr, 0.0, 0.0, 0.0, 0.0);
1984         cairo_paint(cr);
1985
1986         width = widget->allocation.width;
1987         height = widget->allocation.height;
1988         rounded_rect(cr, 0, 0, width, height, r);
1989
1990         cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
1991         cairo_set_source_rgba(cr, 0.0, 0.0, 0.4, 0.8);
1992         cairo_fill(cr);
1993
1994         cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
1995         cairo_move_to(cr, 10, 16);
1996         cairo_show_text(cr, tooltip->entry);
1997         cairo_destroy(cr);
1998 }
1999
2000 static cairo_text_extents_t
2001 get_text_extents(struct tooltip *tooltip)
2002 {
2003         cairo_t *cr;
2004         cairo_text_extents_t extents;
2005
2006         /* Use the dummy_surface because tooltip's surface was not
2007          * created yet, and parent does not have a valid surface
2008          * outside repaint, either.
2009          */
2010         cr = cairo_create(tooltip->window->display->dummy_surface);
2011         cairo_text_extents(cr, tooltip->entry, &extents);
2012         cairo_destroy(cr);
2013
2014         return extents;
2015 }
2016
2017 static int
2018 window_create_tooltip(struct tooltip *tooltip)
2019 {
2020         struct widget *parent = tooltip->parent;
2021         struct display *display = parent->window->display;
2022         struct window *window;
2023         const int offset_y = 27;
2024         const int margin = 3;
2025         cairo_text_extents_t extents;
2026
2027         if (tooltip->widget)
2028                 return 0;
2029
2030         window = window_create_transient(display, parent->window, tooltip->x,
2031                                          tooltip->y + offset_y,
2032                                          WL_SHELL_SURFACE_TRANSIENT_INACTIVE);
2033         if (!window)
2034                 return -1;
2035
2036         tooltip->window = window;
2037         tooltip->widget = window_add_widget(tooltip->window, tooltip);
2038
2039         extents = get_text_extents(tooltip);
2040         widget_set_redraw_handler(tooltip->widget, tooltip_redraw_handler);
2041         window_schedule_resize(window, extents.width + 20, 20 + margin * 2);
2042
2043         return 0;
2044 }
2045
2046 void
2047 widget_destroy_tooltip(struct widget *parent)
2048 {
2049         struct tooltip *tooltip = parent->tooltip;
2050
2051         parent->tooltip_count = 0;
2052         if (!tooltip)
2053                 return;
2054
2055         if (tooltip->widget) {
2056                 widget_destroy(tooltip->widget);
2057                 window_destroy(tooltip->window);
2058                 tooltip->widget = NULL;
2059                 tooltip->window = NULL;
2060         }
2061
2062         close(tooltip->tooltip_fd);
2063         free(tooltip->entry);
2064         free(tooltip);
2065         parent->tooltip = NULL;
2066 }
2067
2068 static void
2069 tooltip_func(struct task *task, uint32_t events)
2070 {
2071         struct tooltip *tooltip =
2072                 container_of(task, struct tooltip, tooltip_task);
2073         uint64_t exp;
2074
2075         if (read(tooltip->tooltip_fd, &exp, sizeof (uint64_t)) != sizeof (uint64_t))
2076                 abort();
2077         window_create_tooltip(tooltip);
2078 }
2079
2080 #define TOOLTIP_TIMEOUT 500
2081 static int
2082 tooltip_timer_reset(struct tooltip *tooltip)
2083 {
2084         struct itimerspec its;
2085
2086         its.it_interval.tv_sec = 0;
2087         its.it_interval.tv_nsec = 0;
2088         its.it_value.tv_sec = TOOLTIP_TIMEOUT / 1000;
2089         its.it_value.tv_nsec = (TOOLTIP_TIMEOUT % 1000) * 1000 * 1000;
2090         if (timerfd_settime(tooltip->tooltip_fd, 0, &its, NULL) < 0) {
2091                 fprintf(stderr, "could not set timerfd\n: %m");
2092                 return -1;
2093         }
2094
2095         return 0;
2096 }
2097
2098 int
2099 widget_set_tooltip(struct widget *parent, char *entry, float x, float y)
2100 {
2101         struct tooltip *tooltip = parent->tooltip;
2102
2103         parent->tooltip_count++;
2104         if (tooltip) {
2105                 tooltip->x = x;
2106                 tooltip->y = y;
2107                 tooltip_timer_reset(tooltip);
2108                 return 0;
2109         }
2110
2111         /* the handler might be triggered too fast via input device motion, so
2112          * we need this check here to make sure tooltip is fully initialized */
2113         if (parent->tooltip_count > 1)
2114                 return 0;
2115
2116         tooltip = malloc(sizeof *tooltip);
2117         if (!tooltip)
2118                 return -1;
2119
2120         parent->tooltip = tooltip;
2121         tooltip->parent = parent;
2122         tooltip->widget = NULL;
2123         tooltip->window = NULL;
2124         tooltip->x = x;
2125         tooltip->y = y;
2126         tooltip->entry = strdup(entry);
2127         tooltip->tooltip_fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
2128         if (tooltip->tooltip_fd < 0) {
2129                 fprintf(stderr, "could not create timerfd\n: %m");
2130                 return -1;
2131         }
2132
2133         tooltip->tooltip_task.run = tooltip_func;
2134         display_watch_fd(parent->window->display, tooltip->tooltip_fd,
2135                          EPOLLIN, &tooltip->tooltip_task);
2136         tooltip_timer_reset(tooltip);
2137
2138         return 0;
2139 }
2140
2141 static void
2142 workspace_manager_state(void *data,
2143                         struct workspace_manager *workspace_manager,
2144                         uint32_t current,
2145                         uint32_t count)
2146 {
2147         struct display *display = data;
2148
2149         display->workspace = current;
2150         display->workspace_count = count;
2151 }
2152
2153 static const struct workspace_manager_listener workspace_manager_listener = {
2154         workspace_manager_state
2155 };
2156
2157 static void
2158 frame_resize_handler(struct widget *widget,
2159                      int32_t width, int32_t height, void *data)
2160 {
2161         struct window_frame *frame = data;
2162         struct widget *child = frame->child;
2163         struct rectangle interior;
2164         struct rectangle input;
2165         struct rectangle opaque;
2166
2167         if (widget->window->type == TYPE_FULLSCREEN) {
2168                 interior.x = 0;
2169                 interior.y = 0;
2170                 interior.width = width;
2171                 interior.height = height;
2172         } else {
2173                 if (widget->window->type == TYPE_MAXIMIZED) {
2174                         frame_set_flag(frame->frame, FRAME_FLAG_MAXIMIZED);
2175                 } else {
2176                         frame_unset_flag(frame->frame, FRAME_FLAG_MAXIMIZED);
2177                 }
2178
2179                 frame_resize(frame->frame, width, height);
2180                 frame_interior(frame->frame, &interior.x, &interior.y,
2181                                &interior.width, &interior.height);
2182         }
2183
2184         widget_set_allocation(child, interior.x, interior.y,
2185                               interior.width, interior.height);
2186
2187         if (child->resize_handler) {
2188                 child->resize_handler(child, interior.width, interior.height,
2189                                       child->user_data);
2190
2191                 if (widget->window->type == TYPE_FULLSCREEN) {
2192                         width = child->allocation.width;
2193                         height = child->allocation.height;
2194                 } else {
2195                         frame_resize_inside(frame->frame,
2196                                             child->allocation.width,
2197                                             child->allocation.height);
2198                         width = frame_width(frame->frame);
2199                         height = frame_height(frame->frame);
2200                 }
2201         }
2202
2203         widget_set_allocation(widget, 0, 0, width, height);
2204
2205         widget->surface->input_region =
2206                 wl_compositor_create_region(widget->window->display->compositor);
2207         if (widget->window->type != TYPE_FULLSCREEN) {
2208                 frame_input_rect(frame->frame, &input.x, &input.y,
2209                                  &input.width, &input.height);
2210                 wl_region_add(widget->surface->input_region,
2211                               input.x, input.y, input.width, input.height);
2212         } else {
2213                 wl_region_add(widget->surface->input_region, 0, 0, width, height);
2214         }
2215
2216         widget_set_allocation(widget, 0, 0, width, height);
2217
2218         if (child->opaque) {
2219                 if (widget->window->type != TYPE_FULLSCREEN) {
2220                         frame_opaque_rect(frame->frame, &opaque.x, &opaque.y,
2221                                           &opaque.width, &opaque.height);
2222
2223                         wl_region_add(widget->surface->opaque_region,
2224                                       opaque.x, opaque.y,
2225                                       opaque.width, opaque.height);
2226                 } else {
2227                         wl_region_add(widget->surface->opaque_region,
2228                                       0, 0, width, height);
2229                 }
2230         }
2231
2232
2233         widget_schedule_redraw(widget);
2234 }
2235
2236 static void
2237 frame_redraw_handler(struct widget *widget, void *data)
2238 {
2239         cairo_t *cr;
2240         struct window_frame *frame = data;
2241         struct window *window = widget->window;
2242
2243         if (window->type == TYPE_FULLSCREEN)
2244                 return;
2245
2246         if (window->focus_count) {
2247                 frame_set_flag(frame->frame, FRAME_FLAG_ACTIVE);
2248         } else {
2249                 frame_unset_flag(frame->frame, FRAME_FLAG_ACTIVE);
2250         }
2251
2252         cr = widget_cairo_create(widget);
2253
2254         frame_repaint(frame->frame, cr);
2255
2256         cairo_destroy(cr);
2257 }
2258
2259 static int
2260 frame_get_pointer_image_for_location(struct window_frame *frame,
2261                                      enum theme_location location)
2262 {
2263         struct window *window = frame->widget->window;
2264
2265         if (window->type != TYPE_TOPLEVEL)
2266                 return CURSOR_LEFT_PTR;
2267
2268         switch (location) {
2269         case THEME_LOCATION_RESIZING_TOP:
2270                 return CURSOR_TOP;
2271         case THEME_LOCATION_RESIZING_BOTTOM:
2272                 return CURSOR_BOTTOM;
2273         case THEME_LOCATION_RESIZING_LEFT:
2274                 return CURSOR_LEFT;
2275         case THEME_LOCATION_RESIZING_RIGHT:
2276                 return CURSOR_RIGHT;
2277         case THEME_LOCATION_RESIZING_TOP_LEFT:
2278                 return CURSOR_TOP_LEFT;
2279         case THEME_LOCATION_RESIZING_TOP_RIGHT:
2280                 return CURSOR_TOP_RIGHT;
2281         case THEME_LOCATION_RESIZING_BOTTOM_LEFT:
2282                 return CURSOR_BOTTOM_LEFT;
2283         case THEME_LOCATION_RESIZING_BOTTOM_RIGHT:
2284                 return CURSOR_BOTTOM_RIGHT;
2285         case THEME_LOCATION_EXTERIOR:
2286         case THEME_LOCATION_TITLEBAR:
2287         default:
2288                 return CURSOR_LEFT_PTR;
2289         }
2290 }
2291
2292 static void
2293 frame_menu_func(struct window *window,
2294                 struct input *input, int index, void *data)
2295 {
2296         struct display *display;
2297
2298         switch (index) {
2299         case 0: /* close */
2300                 if (window->close_handler)
2301                         window->close_handler(window->user_data);
2302                 else
2303                         display_exit(window->display);
2304                 break;
2305         case 1: /* move to workspace above */
2306                 display = window->display;
2307                 if (display->workspace > 0)
2308                         workspace_manager_move_surface(
2309                                 display->workspace_manager,
2310                                 window->main_surface->surface,
2311                                 display->workspace - 1);
2312                 break;
2313         case 2: /* move to workspace below */
2314                 display = window->display;
2315                 if (display->workspace < display->workspace_count - 1)
2316                         workspace_manager_move_surface(
2317                                 display->workspace_manager,
2318                                 window->main_surface->surface,
2319                                 display->workspace + 1);
2320                 break;
2321         case 3: /* fullscreen */
2322                 /* we don't have a way to get out of fullscreen for now */
2323                 if (window->fullscreen_handler)
2324                         window->fullscreen_handler(window, window->user_data);
2325                 break;
2326         }
2327 }
2328
2329 void
2330 window_show_frame_menu(struct window *window,
2331                        struct input *input, uint32_t time)
2332 {
2333         int32_t x, y;
2334         int count;
2335
2336         static const char *entries[] = {
2337                 "Close",
2338                 "Move to workspace above", "Move to workspace below",
2339                 "Fullscreen"
2340         };
2341
2342         if (window->fullscreen_handler)
2343                 count = ARRAY_LENGTH(entries);
2344         else
2345                 count = ARRAY_LENGTH(entries) - 1;
2346
2347         input_get_position(input, &x, &y);
2348         window_show_menu(window->display, input, time, window,
2349                          x - 10, y - 10, frame_menu_func, entries, count);
2350 }
2351
2352 static int
2353 frame_enter_handler(struct widget *widget,
2354                     struct input *input, float x, float y, void *data)
2355 {
2356         struct window_frame *frame = data;
2357         enum theme_location location;
2358
2359         location = frame_pointer_enter(frame->frame, input, x, y);
2360         if (frame_status(frame->frame) & FRAME_STATUS_REPAINT)
2361                 widget_schedule_redraw(frame->widget);
2362
2363         return frame_get_pointer_image_for_location(data, location);
2364 }
2365
2366 static int
2367 frame_motion_handler(struct widget *widget,
2368                      struct input *input, uint32_t time,
2369                      float x, float y, void *data)
2370 {
2371         struct window_frame *frame = data;
2372         enum theme_location location;
2373
2374         location = frame_pointer_motion(frame->frame, input, x, y);
2375         if (frame_status(frame->frame) & FRAME_STATUS_REPAINT)
2376                 widget_schedule_redraw(frame->widget);
2377
2378         return frame_get_pointer_image_for_location(data, location);
2379 }
2380
2381 static void
2382 frame_leave_handler(struct widget *widget,
2383                     struct input *input, void *data)
2384 {
2385         struct window_frame *frame = data;
2386
2387         frame_pointer_leave(frame->frame, input);
2388         if (frame_status(frame->frame) & FRAME_STATUS_REPAINT)
2389                 widget_schedule_redraw(frame->widget);
2390 }
2391
2392 static void
2393 frame_handle_status(struct window_frame *frame, struct input *input,
2394                     uint32_t time, enum theme_location location)
2395 {
2396         struct window *window = frame->widget->window;
2397         uint32_t status;
2398
2399         status = frame_status(frame->frame);
2400         if (status & FRAME_STATUS_REPAINT)
2401                 widget_schedule_redraw(frame->widget);
2402
2403         if (status & FRAME_STATUS_MINIMIZE)
2404                 fprintf(stderr,"Minimize stub\n");
2405
2406         if (status & FRAME_STATUS_MENU) {
2407                 window_show_frame_menu(window, input, time);
2408                 frame_status_clear(frame->frame, FRAME_STATUS_MENU);
2409         }
2410
2411         if (status & FRAME_STATUS_MAXIMIZE) {
2412                 window_set_maximized(window, window->type != TYPE_MAXIMIZED);
2413                 frame_status_clear(frame->frame, FRAME_STATUS_MAXIMIZE);
2414         }
2415
2416         if (status & FRAME_STATUS_CLOSE) {
2417                 if (window->close_handler)
2418                         window->close_handler(window->user_data);
2419                 else
2420                         display_exit(window->display);
2421                 return;
2422         }
2423
2424         if ((status & FRAME_STATUS_MOVE) && window->shell_surface) {
2425                 input_ungrab(input);
2426                 wl_shell_surface_move(window->shell_surface,
2427                                       input_get_seat(input),
2428                                       window->display->serial);
2429
2430                 frame_status_clear(frame->frame, FRAME_STATUS_MOVE);
2431         }
2432
2433         if ((status & FRAME_STATUS_RESIZE) && window->shell_surface) {
2434                 input_ungrab(input);
2435
2436                 window->resizing = 1;
2437                 wl_shell_surface_resize(window->shell_surface,
2438                                         input_get_seat(input),
2439                                         window->display->serial,
2440                                         location);
2441
2442                 frame_status_clear(frame->frame, FRAME_STATUS_RESIZE);
2443         }
2444 }
2445
2446 static void
2447 frame_button_handler(struct widget *widget,
2448                      struct input *input, uint32_t time,
2449                      uint32_t button, enum wl_pointer_button_state state,
2450                      void *data)
2451
2452 {
2453         struct window_frame *frame = data;
2454         enum theme_location location;
2455
2456         location = frame_pointer_button(frame->frame, input, button, state);
2457         frame_handle_status(frame, input, time, location);
2458 }
2459
2460 static void
2461 frame_touch_down_handler(struct widget *widget, struct input *input,
2462                          uint32_t serial, uint32_t time, int32_t id,
2463                          float x, float y, void *data)
2464 {
2465         struct window_frame *frame = data;
2466
2467         frame_touch_down(frame->frame, input, id, x, y);
2468         frame_handle_status(frame, input, time, THEME_LOCATION_CLIENT_AREA);
2469 }
2470
2471 static void
2472 frame_touch_up_handler(struct widget *widget,
2473                          struct input *input, uint32_t serial, uint32_t time,
2474                          int32_t id, void *data)
2475 {
2476         struct window_frame *frame = data;
2477
2478         frame_touch_up(frame->frame, input, id);
2479         frame_handle_status(frame, input, time, THEME_LOCATION_CLIENT_AREA);
2480 }
2481
2482 struct widget *
2483 window_frame_create(struct window *window, void *data)
2484 {
2485         struct window_frame *frame;
2486         uint32_t buttons;
2487
2488         if (window->type == TYPE_CUSTOM) {
2489                 buttons = FRAME_BUTTON_NONE;
2490         } else {
2491                 buttons = FRAME_BUTTON_ALL;
2492         }
2493
2494         frame = xzalloc(sizeof *frame);
2495         frame->frame = frame_create(window->display->theme, 0, 0,
2496                                     buttons, window->title);
2497
2498         frame->widget = window_add_widget(window, frame);
2499         frame->child = widget_add_widget(frame->widget, data);
2500
2501         widget_set_redraw_handler(frame->widget, frame_redraw_handler);
2502         widget_set_resize_handler(frame->widget, frame_resize_handler);
2503         widget_set_enter_handler(frame->widget, frame_enter_handler);
2504         widget_set_leave_handler(frame->widget, frame_leave_handler);
2505         widget_set_motion_handler(frame->widget, frame_motion_handler);
2506         widget_set_button_handler(frame->widget, frame_button_handler);
2507         widget_set_touch_down_handler(frame->widget, frame_touch_down_handler);
2508         widget_set_touch_up_handler(frame->widget, frame_touch_up_handler);
2509
2510         window->frame = frame;
2511
2512         return frame->child;
2513 }
2514
2515 void
2516 window_frame_set_child_size(struct widget *widget, int child_width,
2517                             int child_height)
2518 {
2519         struct display *display = widget->window->display;
2520         struct theme *t = display->theme;
2521         int decoration_width, decoration_height;
2522         int width, height;
2523         int margin = widget->window->type == TYPE_MAXIMIZED ? 0 : t->margin;
2524
2525         if (widget->window->type != TYPE_FULLSCREEN) {
2526                 decoration_width = (t->width + margin) * 2;
2527                 decoration_height = t->width +
2528                         t->titlebar_height + margin * 2;
2529
2530                 width = child_width + decoration_width;
2531                 height = child_height + decoration_height;
2532         } else {
2533                 width = child_width;
2534                 height = child_height;
2535         }
2536
2537         window_schedule_resize(widget->window, width, height);
2538 }
2539
2540 static void
2541 window_frame_destroy(struct window_frame *frame)
2542 {
2543         frame_destroy(frame->frame);
2544
2545         /* frame->child must be destroyed by the application */
2546         widget_destroy(frame->widget);
2547         free(frame);
2548 }
2549
2550 static void
2551 input_set_focus_widget(struct input *input, struct widget *focus,
2552                        float x, float y)
2553 {
2554         struct widget *old, *widget;
2555         int cursor;
2556
2557         if (focus == input->focus_widget)
2558                 return;
2559
2560         old = input->focus_widget;
2561         if (old) {
2562                 widget = old;
2563                 if (input->grab)
2564                         widget = input->grab;
2565                 if (widget->leave_handler)
2566                         widget->leave_handler(old, input, widget->user_data);
2567                 input->focus_widget = NULL;
2568         }
2569
2570         if (focus) {
2571                 widget = focus;
2572                 if (input->grab)
2573                         widget = input->grab;
2574                 input->focus_widget = focus;
2575                 if (widget->enter_handler)
2576                         cursor = widget->enter_handler(focus, input, x, y,
2577                                                        widget->user_data);
2578                 else
2579                         cursor = widget->default_cursor;
2580
2581                 input_set_pointer_image(input, cursor);
2582         }
2583 }
2584
2585 void
2586 touch_grab(struct input  *input, int32_t touch_id)
2587 {
2588         input->touch_grab = 1;
2589         input->touch_grab_id = touch_id;
2590 }
2591
2592 void
2593 touch_ungrab(struct input *input)
2594 {
2595         struct touch_point *tp, *tmp;
2596
2597         input->touch_grab = 0;
2598
2599         wl_list_for_each_safe(tp, tmp,
2600                         &input->touch_point_list, link) {
2601                 if (tp->id != input->touch_grab_id)
2602                         continue;
2603                 wl_list_remove(&tp->link);
2604                 free(tp);
2605
2606                 return;
2607         }
2608 }
2609
2610 void
2611 input_grab(struct input *input, struct widget *widget, uint32_t button)
2612 {
2613         input->grab = widget;
2614         input->grab_button = button;
2615 }
2616
2617 void
2618 input_ungrab(struct input *input)
2619 {
2620         struct widget *widget;
2621
2622         input->grab = NULL;
2623         if (input->pointer_focus) {
2624                 widget = window_find_widget(input->pointer_focus,
2625                                             input->sx, input->sy);
2626                 input_set_focus_widget(input, widget, input->sx, input->sy);
2627         }
2628 }
2629
2630 static void
2631 input_remove_pointer_focus(struct input *input)
2632 {
2633         struct window *window = input->pointer_focus;
2634
2635         if (!window)
2636                 return;
2637
2638         input_set_focus_widget(input, NULL, 0, 0);
2639
2640         input->pointer_focus = NULL;
2641         input->current_cursor = CURSOR_UNSET;
2642 }
2643
2644 static void
2645 pointer_handle_enter(void *data, struct wl_pointer *pointer,
2646                      uint32_t serial, struct wl_surface *surface,
2647                      wl_fixed_t sx_w, wl_fixed_t sy_w)
2648 {
2649         struct input *input = data;
2650         struct window *window;
2651         struct widget *widget;
2652         float sx = wl_fixed_to_double(sx_w);
2653         float sy = wl_fixed_to_double(sy_w);
2654
2655         if (!surface) {
2656                 /* enter event for a window we've just destroyed */
2657                 return;
2658         }
2659
2660         input->display->serial = serial;
2661         input->pointer_enter_serial = serial;
2662         input->pointer_focus = wl_surface_get_user_data(surface);
2663         window = input->pointer_focus;
2664
2665         if (window->resizing) {
2666                 window->resizing = 0;
2667                 /* Schedule a redraw to free the pool */
2668                 window_schedule_redraw(window);
2669         }
2670
2671         input->sx = sx;
2672         input->sy = sy;
2673
2674         widget = window_find_widget(window, sx, sy);
2675         input_set_focus_widget(input, widget, sx, sy);
2676 }
2677
2678 static void
2679 pointer_handle_leave(void *data, struct wl_pointer *pointer,
2680                      uint32_t serial, struct wl_surface *surface)
2681 {
2682         struct input *input = data;
2683
2684         input->display->serial = serial;
2685         input_remove_pointer_focus(input);
2686 }
2687
2688 static void
2689 pointer_handle_motion(void *data, struct wl_pointer *pointer,
2690                       uint32_t time, wl_fixed_t sx_w, wl_fixed_t sy_w)
2691 {
2692         struct input *input = data;
2693         struct window *window = input->pointer_focus;
2694         struct widget *widget;
2695         int cursor;
2696         float sx = wl_fixed_to_double(sx_w);
2697         float sy = wl_fixed_to_double(sy_w);
2698
2699         input->sx = sx;
2700         input->sy = sy;
2701
2702         if (!window)
2703                 return;
2704
2705         /* when making the window smaller - e.g. after a unmaximise we might
2706          * still have a pending motion event that the compositor has picked
2707          * based on the old surface dimensions
2708          */
2709         if (sx > window->main_surface->allocation.width ||
2710             sy > window->main_surface->allocation.height)
2711                 return;
2712
2713         if (!(input->grab && input->grab_button)) {
2714                 widget = window_find_widget(window, sx, sy);
2715                 input_set_focus_widget(input, widget, sx, sy);
2716         }
2717
2718         if (input->grab)
2719                 widget = input->grab;
2720         else
2721                 widget = input->focus_widget;
2722         if (widget) {
2723                 if (widget->motion_handler)
2724                         cursor = widget->motion_handler(input->focus_widget,
2725                                                         input, time, sx, sy,
2726                                                         widget->user_data);
2727                 else
2728                         cursor = widget->default_cursor;
2729         } else
2730                 cursor = CURSOR_LEFT_PTR;
2731
2732         input_set_pointer_image(input, cursor);
2733 }
2734
2735 static void
2736 pointer_handle_button(void *data, struct wl_pointer *pointer, uint32_t serial,
2737                       uint32_t time, uint32_t button, uint32_t state_w)
2738 {
2739         struct input *input = data;
2740         struct widget *widget;
2741         enum wl_pointer_button_state state = state_w;
2742
2743         input->display->serial = serial;
2744         if (input->focus_widget && input->grab == NULL &&
2745             state == WL_POINTER_BUTTON_STATE_PRESSED)
2746                 input_grab(input, input->focus_widget, button);
2747
2748         widget = input->grab;
2749         if (widget && widget->button_handler)
2750                 (*widget->button_handler)(widget,
2751                                           input, time,
2752                                           button, state,
2753                                           input->grab->user_data);
2754
2755         if (input->grab && input->grab_button == button &&
2756             state == WL_POINTER_BUTTON_STATE_RELEASED)
2757                 input_ungrab(input);
2758 }
2759
2760 static void
2761 pointer_handle_axis(void *data, struct wl_pointer *pointer,
2762                     uint32_t time, uint32_t axis, wl_fixed_t value)
2763 {
2764         struct input *input = data;
2765         struct widget *widget;
2766
2767         widget = input->focus_widget;
2768         if (input->grab)
2769                 widget = input->grab;
2770         if (widget && widget->axis_handler)
2771                 (*widget->axis_handler)(widget,
2772                                         input, time,
2773                                         axis, value,
2774                                         widget->user_data);
2775 }
2776
2777 static const struct wl_pointer_listener pointer_listener = {
2778         pointer_handle_enter,
2779         pointer_handle_leave,
2780         pointer_handle_motion,
2781         pointer_handle_button,
2782         pointer_handle_axis,
2783 };
2784
2785 static void
2786 input_remove_keyboard_focus(struct input *input)
2787 {
2788         struct window *window = input->keyboard_focus;
2789         struct itimerspec its;
2790
2791         its.it_interval.tv_sec = 0;
2792         its.it_interval.tv_nsec = 0;
2793         its.it_value.tv_sec = 0;
2794         its.it_value.tv_nsec = 0;
2795         timerfd_settime(input->repeat_timer_fd, 0, &its, NULL);
2796
2797         if (!window)
2798                 return;
2799
2800         window->focus_count--;
2801         if (window->keyboard_focus_handler)
2802                 (*window->keyboard_focus_handler)(window, NULL,
2803                                                   window->user_data);
2804
2805         input->keyboard_focus = NULL;
2806 }
2807
2808 static void
2809 keyboard_repeat_func(struct task *task, uint32_t events)
2810 {
2811         struct input *input =
2812                 container_of(task, struct input, repeat_task);
2813         struct window *window = input->keyboard_focus;
2814         uint64_t exp;
2815
2816         if (read(input->repeat_timer_fd, &exp, sizeof exp) != sizeof exp)
2817                 /* If we change the timer between the fd becoming
2818                  * readable and getting here, there'll be nothing to
2819                  * read and we get EAGAIN. */
2820                 return;
2821
2822         if (window && window->key_handler) {
2823                 (*window->key_handler)(window, input, input->repeat_time,
2824                                        input->repeat_key, input->repeat_sym,
2825                                        WL_KEYBOARD_KEY_STATE_PRESSED,
2826                                        window->user_data);
2827         }
2828 }
2829
2830 static void
2831 keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard,
2832                        uint32_t format, int fd, uint32_t size)
2833 {
2834         struct input *input = data;
2835         struct xkb_keymap *keymap;
2836         struct xkb_state *state;
2837         char *map_str;
2838
2839         if (!data) {
2840                 close(fd);
2841                 return;
2842         }
2843
2844         if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) {
2845                 close(fd);
2846                 return;
2847         }
2848
2849         map_str = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
2850         if (map_str == MAP_FAILED) {
2851                 close(fd);
2852                 return;
2853         }
2854
2855         keymap = xkb_map_new_from_string(input->display->xkb_context,
2856                                          map_str,
2857                                          XKB_KEYMAP_FORMAT_TEXT_V1,
2858                                          0);
2859         munmap(map_str, size);
2860         close(fd);
2861
2862         if (!keymap) {
2863                 fprintf(stderr, "failed to compile keymap\n");
2864                 return;
2865         }
2866
2867         state = xkb_state_new(keymap);
2868         if (!state) {
2869                 fprintf(stderr, "failed to create XKB state\n");
2870                 xkb_map_unref(keymap);
2871                 return;
2872         }
2873
2874         xkb_keymap_unref(input->xkb.keymap);
2875         xkb_state_unref(input->xkb.state);
2876         input->xkb.keymap = keymap;
2877         input->xkb.state = state;
2878
2879         input->xkb.control_mask =
2880                 1 << xkb_map_mod_get_index(input->xkb.keymap, "Control");
2881         input->xkb.alt_mask =
2882                 1 << xkb_map_mod_get_index(input->xkb.keymap, "Mod1");
2883         input->xkb.shift_mask =
2884                 1 << xkb_map_mod_get_index(input->xkb.keymap, "Shift");
2885 }
2886
2887 static void
2888 keyboard_handle_enter(void *data, struct wl_keyboard *keyboard,
2889                       uint32_t serial, struct wl_surface *surface,
2890                       struct wl_array *keys)
2891 {
2892         struct input *input = data;
2893         struct window *window;
2894
2895         input->display->serial = serial;
2896         input->keyboard_focus = wl_surface_get_user_data(surface);
2897
2898         window = input->keyboard_focus;
2899         window->focus_count++;
2900         if (window->keyboard_focus_handler)
2901                 (*window->keyboard_focus_handler)(window,
2902                                                   input, window->user_data);
2903 }
2904
2905 static void
2906 keyboard_handle_leave(void *data, struct wl_keyboard *keyboard,
2907                       uint32_t serial, struct wl_surface *surface)
2908 {
2909         struct input *input = data;
2910
2911         input->display->serial = serial;
2912         input_remove_keyboard_focus(input);
2913 }
2914
2915 static void
2916 keyboard_handle_key(void *data, struct wl_keyboard *keyboard,
2917                     uint32_t serial, uint32_t time, uint32_t key,
2918                     uint32_t state_w)
2919 {
2920         struct input *input = data;
2921         struct window *window = input->keyboard_focus;
2922         uint32_t code, num_syms;
2923         enum wl_keyboard_key_state state = state_w;
2924         const xkb_keysym_t *syms;
2925         xkb_keysym_t sym;
2926         struct itimerspec its;
2927
2928         input->display->serial = serial;
2929         code = key + 8;
2930         if (!window || !input->xkb.state)
2931                 return;
2932
2933         num_syms = xkb_key_get_syms(input->xkb.state, code, &syms);
2934
2935         sym = XKB_KEY_NoSymbol;
2936         if (num_syms == 1)
2937                 sym = syms[0];
2938
2939         if (sym == XKB_KEY_F5 && input->modifiers == MOD_ALT_MASK) {
2940                 if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
2941                         window_set_maximized(window,
2942                                              window->type != TYPE_MAXIMIZED);
2943         } else if (sym == XKB_KEY_F11 &&
2944                    window->fullscreen_handler &&
2945                    state == WL_KEYBOARD_KEY_STATE_PRESSED) {
2946                 window->fullscreen_handler(window, window->user_data);
2947         } else if (sym == XKB_KEY_F4 &&
2948                    input->modifiers == MOD_ALT_MASK &&
2949                    state == WL_KEYBOARD_KEY_STATE_PRESSED) {
2950                 if (window->close_handler)
2951                         window->close_handler(window->user_data);
2952                 else
2953                         display_exit(window->display);
2954         } else if (window->key_handler) {
2955                 (*window->key_handler)(window, input, time, key,
2956                                        sym, state, window->user_data);
2957         }
2958
2959         if (state == WL_KEYBOARD_KEY_STATE_RELEASED &&
2960             key == input->repeat_key) {
2961                 its.it_interval.tv_sec = 0;
2962                 its.it_interval.tv_nsec = 0;
2963                 its.it_value.tv_sec = 0;
2964                 its.it_value.tv_nsec = 0;
2965                 timerfd_settime(input->repeat_timer_fd, 0, &its, NULL);
2966         } else if (state == WL_KEYBOARD_KEY_STATE_PRESSED) {
2967                 input->repeat_sym = sym;
2968                 input->repeat_key = key;
2969                 input->repeat_time = time;
2970                 its.it_interval.tv_sec = 0;
2971                 its.it_interval.tv_nsec = 25 * 1000 * 1000;
2972                 its.it_value.tv_sec = 0;
2973                 its.it_value.tv_nsec = 400 * 1000 * 1000;
2974                 timerfd_settime(input->repeat_timer_fd, 0, &its, NULL);
2975         }
2976 }
2977
2978 static void
2979 keyboard_handle_modifiers(void *data, struct wl_keyboard *keyboard,
2980                           uint32_t serial, uint32_t mods_depressed,
2981                           uint32_t mods_latched, uint32_t mods_locked,
2982                           uint32_t group)
2983 {
2984         struct input *input = data;
2985         xkb_mod_mask_t mask;
2986
2987         /* If we're not using a keymap, then we don't handle PC-style modifiers */
2988         if (!input->xkb.keymap)
2989                 return;
2990
2991         xkb_state_update_mask(input->xkb.state, mods_depressed, mods_latched,
2992                               mods_locked, 0, 0, group);
2993         mask = xkb_state_serialize_mods(input->xkb.state,
2994                                         XKB_STATE_DEPRESSED |
2995                                         XKB_STATE_LATCHED);
2996         input->modifiers = 0;
2997         if (mask & input->xkb.control_mask)
2998                 input->modifiers |= MOD_CONTROL_MASK;
2999         if (mask & input->xkb.alt_mask)
3000                 input->modifiers |= MOD_ALT_MASK;
3001         if (mask & input->xkb.shift_mask)
3002                 input->modifiers |= MOD_SHIFT_MASK;
3003 }
3004
3005 static const struct wl_keyboard_listener keyboard_listener = {
3006         keyboard_handle_keymap,
3007         keyboard_handle_enter,
3008         keyboard_handle_leave,
3009         keyboard_handle_key,
3010         keyboard_handle_modifiers,
3011 };
3012
3013 static void
3014 touch_handle_down(void *data, struct wl_touch *wl_touch,
3015                   uint32_t serial, uint32_t time, struct wl_surface *surface,
3016                   int32_t id, wl_fixed_t x_w, wl_fixed_t y_w)
3017 {
3018         struct input *input = data;
3019         struct widget *widget;
3020         float sx = wl_fixed_to_double(x_w);
3021         float sy = wl_fixed_to_double(y_w);
3022
3023         input->display->serial = serial;
3024         input->touch_focus = wl_surface_get_user_data(surface);
3025         if (!input->touch_focus) {
3026                 DBG("Failed to find to touch focus for surface %p\n", surface);
3027                 return;
3028         }
3029
3030         widget = window_find_widget(input->touch_focus,
3031                                     wl_fixed_to_double(x_w),
3032                                     wl_fixed_to_double(y_w));
3033         if (widget) {
3034                 struct touch_point *tp = xmalloc(sizeof *tp);
3035                 if (tp) {
3036                         tp->id = id;
3037                         tp->widget = widget;
3038                         tp->x = sx;
3039                         tp->y = sy;
3040                         wl_list_insert(&input->touch_point_list, &tp->link);
3041
3042                         if (widget->touch_down_handler)
3043                                 (*widget->touch_down_handler)(widget, input, 
3044                                                               serial, time, id,
3045                                                               sx, sy,
3046                                                               widget->user_data);
3047                 }
3048         }
3049 }
3050
3051 static void
3052 touch_handle_up(void *data, struct wl_touch *wl_touch,
3053                 uint32_t serial, uint32_t time, int32_t id)
3054 {
3055         struct input *input = data;
3056         struct touch_point *tp, *tmp;
3057
3058         if (!input->touch_focus) {
3059                 DBG("No touch focus found for touch up event!\n");
3060                 return;
3061         }
3062
3063         wl_list_for_each_safe(tp, tmp, &input->touch_point_list, link) {
3064                 if (tp->id != id)
3065                         continue;
3066
3067                 if (tp->widget->touch_up_handler)
3068                         (*tp->widget->touch_up_handler)(tp->widget, input, serial,
3069                                                         time, id,
3070                                                         tp->widget->user_data);
3071
3072                 wl_list_remove(&tp->link);
3073                 free(tp);
3074
3075                 return;
3076         }
3077 }
3078
3079 static void
3080 touch_handle_motion(void *data, struct wl_touch *wl_touch,
3081                     uint32_t time, int32_t id, wl_fixed_t x_w, wl_fixed_t y_w)
3082 {
3083         struct input *input = data;
3084         struct touch_point *tp;
3085         float sx = wl_fixed_to_double(x_w);
3086         float sy = wl_fixed_to_double(y_w);
3087
3088         DBG("touch_handle_motion: %i %i\n", id, wl_list_length(&input->touch_point_list));
3089
3090         if (!input->touch_focus) {
3091                 DBG("No touch focus found for touch motion event!\n");
3092                 return;
3093         }
3094
3095         wl_list_for_each(tp, &input->touch_point_list, link) {
3096                 if (tp->id != id)
3097                         continue;
3098
3099                 tp->x = sx;
3100                 tp->y = sy;
3101                 if (tp->widget->touch_motion_handler)
3102                         (*tp->widget->touch_motion_handler)(tp->widget, input, time,
3103                                                             id, sx, sy,
3104                                                             tp->widget->user_data);
3105                 return;
3106         }
3107 }
3108
3109 static void
3110 touch_handle_frame(void *data, struct wl_touch *wl_touch)
3111 {
3112         struct input *input = data;
3113         struct touch_point *tp, *tmp;
3114
3115         DBG("touch_handle_frame\n");
3116
3117         if (!input->touch_focus) {
3118                 DBG("No touch focus found for touch frame event!\n");
3119                 return;
3120         }
3121
3122         wl_list_for_each_safe(tp, tmp, &input->touch_point_list, link) {
3123                 if (tp->widget->touch_frame_handler)
3124                         (*tp->widget->touch_frame_handler)(tp->widget, input, 
3125                                                            tp->widget->user_data);
3126
3127                 wl_list_remove(&tp->link);
3128                 free(tp);
3129         }
3130 }
3131
3132 static void
3133 touch_handle_cancel(void *data, struct wl_touch *wl_touch)
3134 {
3135         struct input *input = data;
3136         struct touch_point *tp, *tmp;
3137
3138         DBG("touch_handle_cancel\n");
3139
3140         if (!input->touch_focus) {
3141                 DBG("No touch focus found for touch cancel event!\n");
3142                 return;
3143         }
3144
3145         wl_list_for_each_safe(tp, tmp, &input->touch_point_list, link) {
3146                 if (tp->widget->touch_cancel_handler)
3147                         (*tp->widget->touch_cancel_handler)(tp->widget, input,
3148                                                             tp->widget->user_data);
3149
3150                 wl_list_remove(&tp->link);
3151                 free(tp);
3152         }
3153 }
3154
3155 static const struct wl_touch_listener touch_listener = {
3156         touch_handle_down,
3157         touch_handle_up,
3158         touch_handle_motion,
3159         touch_handle_frame,
3160         touch_handle_cancel,
3161 };
3162
3163 static void
3164 seat_handle_capabilities(void *data, struct wl_seat *seat,
3165                          enum wl_seat_capability caps)
3166 {
3167         struct input *input = data;
3168
3169         if ((caps & WL_SEAT_CAPABILITY_POINTER) && !input->pointer) {
3170                 input->pointer = wl_seat_get_pointer(seat);
3171                 wl_pointer_set_user_data(input->pointer, input);
3172                 wl_pointer_add_listener(input->pointer, &pointer_listener,
3173                                         input);
3174         } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && input->pointer) {
3175                 wl_pointer_destroy(input->pointer);
3176                 input->pointer = NULL;
3177         }
3178
3179         if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !input->keyboard) {
3180                 input->keyboard = wl_seat_get_keyboard(seat);
3181                 wl_keyboard_set_user_data(input->keyboard, input);
3182                 wl_keyboard_add_listener(input->keyboard, &keyboard_listener,
3183                                          input);
3184         } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && input->keyboard) {
3185                 wl_keyboard_destroy(input->keyboard);
3186                 input->keyboard = NULL;
3187         }
3188
3189         if ((caps & WL_SEAT_CAPABILITY_TOUCH) && !input->touch) {
3190                 input->touch = wl_seat_get_touch(seat);
3191                 wl_touch_set_user_data(input->touch, input);
3192                 wl_touch_add_listener(input->touch, &touch_listener, input);
3193         } else if (!(caps & WL_SEAT_CAPABILITY_TOUCH) && input->touch) {
3194                 wl_touch_destroy(input->touch);
3195                 input->touch = NULL;
3196         }
3197 }
3198
3199 static void
3200 seat_handle_name(void *data, struct wl_seat *seat,
3201                  const char *name)
3202 {
3203
3204 }
3205
3206 static const struct wl_seat_listener seat_listener = {
3207         seat_handle_capabilities,
3208         seat_handle_name
3209 };
3210
3211 void
3212 input_get_position(struct input *input, int32_t *x, int32_t *y)
3213 {
3214         *x = input->sx;
3215         *y = input->sy;
3216 }
3217
3218 int
3219 input_get_touch(struct input *input, int32_t id, float *x, float *y)
3220 {
3221         struct touch_point *tp;
3222
3223         wl_list_for_each(tp, &input->touch_point_list, link) {
3224                 if (tp->id != id)
3225                         continue;
3226
3227                 *x = tp->x;
3228                 *y = tp->y;
3229                 return 0;
3230         }
3231
3232         return -1;
3233 }
3234
3235 struct display *
3236 input_get_display(struct input *input)
3237 {
3238         return input->display;
3239 }
3240
3241 struct wl_seat *
3242 input_get_seat(struct input *input)
3243 {
3244         return input->seat;
3245 }
3246
3247 uint32_t
3248 input_get_modifiers(struct input *input)
3249 {
3250         return input->modifiers;
3251 }
3252
3253 struct widget *
3254 input_get_focus_widget(struct input *input)
3255 {
3256         return input->focus_widget;
3257 }
3258
3259 struct data_offer {
3260         struct wl_data_offer *offer;
3261         struct input *input;
3262         struct wl_array types;
3263         int refcount;
3264
3265         struct task io_task;
3266         int fd;
3267         data_func_t func;
3268         int32_t x, y;
3269         void *user_data;
3270 };
3271
3272 static void
3273 data_offer_offer(void *data, struct wl_data_offer *wl_data_offer, const char *type)
3274 {
3275         struct data_offer *offer = data;
3276         char **p;
3277
3278         p = wl_array_add(&offer->types, sizeof *p);
3279         *p = strdup(type);
3280 }
3281
3282 static const struct wl_data_offer_listener data_offer_listener = {
3283         data_offer_offer,
3284 };
3285
3286 static void
3287 data_offer_destroy(struct data_offer *offer)
3288 {
3289         char **p;
3290
3291         offer->refcount--;
3292         if (offer->refcount == 0) {
3293                 wl_data_offer_destroy(offer->offer);
3294                 for (p = offer->types.data; *p; p++)
3295                         free(*p);
3296                 wl_array_release(&offer->types);
3297                 free(offer);
3298         }
3299 }
3300
3301 static void
3302 data_device_data_offer(void *data,
3303                        struct wl_data_device *data_device,
3304                        struct wl_data_offer *_offer)
3305 {
3306         struct data_offer *offer;
3307
3308         offer = xmalloc(sizeof *offer);
3309
3310         wl_array_init(&offer->types);
3311         offer->refcount = 1;
3312         offer->input = data;
3313         offer->offer = _offer;
3314         wl_data_offer_add_listener(offer->offer,
3315                                    &data_offer_listener, offer);
3316 }
3317
3318 static void
3319 data_device_enter(void *data, struct wl_data_device *data_device,
3320                   uint32_t serial, struct wl_surface *surface,
3321                   wl_fixed_t x_w, wl_fixed_t y_w,
3322                   struct wl_data_offer *offer)
3323 {
3324         struct input *input = data;
3325         struct window *window;
3326         void *types_data;
3327         float x = wl_fixed_to_double(x_w);
3328         float y = wl_fixed_to_double(y_w);
3329         char **p;
3330
3331         window = wl_surface_get_user_data(surface);
3332         input->drag_enter_serial = serial;
3333         input->drag_focus = window,
3334         input->drag_x = x;
3335         input->drag_y = y;
3336
3337         if (!input->touch_grab)
3338                 input->pointer_enter_serial = serial;
3339
3340         if (offer) {
3341                 input->drag_offer = wl_data_offer_get_user_data(offer);
3342
3343                 p = wl_array_add(&input->drag_offer->types, sizeof *p);
3344                 *p = NULL;
3345
3346                 types_data = input->drag_offer->types.data;
3347         } else {
3348                 input->drag_offer = NULL;
3349                 types_data = NULL;
3350         }
3351
3352         if (window->data_handler)
3353                 window->data_handler(window, input, x, y, types_data,
3354                                      window->user_data);
3355 }
3356
3357 static void
3358 data_device_leave(void *data, struct wl_data_device *data_device)
3359 {
3360         struct input *input = data;
3361
3362         if (input->drag_offer) {
3363                 data_offer_destroy(input->drag_offer);
3364                 input->drag_offer = NULL;
3365         }
3366 }
3367
3368 static void
3369 data_device_motion(void *data, struct wl_data_device *data_device,
3370                    uint32_t time, wl_fixed_t x_w, wl_fixed_t y_w)
3371 {
3372         struct input *input = data;
3373         struct window *window = input->drag_focus;
3374         float x = wl_fixed_to_double(x_w);
3375         float y = wl_fixed_to_double(y_w);
3376         void *types_data;
3377
3378         input->drag_x = x;
3379         input->drag_y = y;
3380
3381         if (input->drag_offer)
3382                 types_data = input->drag_offer->types.data;
3383         else
3384                 types_data = NULL;
3385
3386         if (window->data_handler)
3387                 window->data_handler(window, input, x, y, types_data,
3388                                      window->user_data);
3389 }
3390
3391 static void
3392 data_device_drop(void *data, struct wl_data_device *data_device)
3393 {
3394         struct input *input = data;
3395         struct window *window = input->drag_focus;
3396         float x, y;
3397
3398         x = input->drag_x;
3399         y = input->drag_y;
3400
3401         if (window->drop_handler)
3402                 window->drop_handler(window, input,
3403                                      x, y, window->user_data);
3404
3405         if (input->touch_grab)
3406                 touch_ungrab(input);
3407 }
3408
3409 static void
3410 data_device_selection(void *data,
3411                       struct wl_data_device *wl_data_device,
3412                       struct wl_data_offer *offer)
3413 {
3414         struct input *input = data;
3415         char **p;
3416
3417         if (input->selection_offer)
3418                 data_offer_destroy(input->selection_offer);
3419
3420         if (offer) {
3421                 input->selection_offer = wl_data_offer_get_user_data(offer);
3422                 p = wl_array_add(&input->selection_offer->types, sizeof *p);
3423                 *p = NULL;
3424         } else {
3425                 input->selection_offer = NULL;
3426         }
3427 }
3428
3429 static const struct wl_data_device_listener data_device_listener = {
3430         data_device_data_offer,
3431         data_device_enter,
3432         data_device_leave,
3433         data_device_motion,
3434         data_device_drop,
3435         data_device_selection
3436 };
3437
3438 static void
3439 input_set_pointer_image_index(struct input *input, int index)
3440 {
3441         struct wl_buffer *buffer;
3442         struct wl_cursor *cursor;
3443         struct wl_cursor_image *image;
3444
3445         if (!input->pointer)
3446                 return;
3447
3448         cursor = input->display->cursors[input->current_cursor];
3449         if (!cursor)
3450                 return;
3451
3452         if (index >= (int) cursor->image_count) {
3453                 fprintf(stderr, "cursor index out of range\n");
3454                 return;
3455         }
3456
3457         image = cursor->images[index];
3458         buffer = wl_cursor_image_get_buffer(image);
3459         if (!buffer)
3460                 return;
3461
3462         wl_pointer_set_cursor(input->pointer, input->pointer_enter_serial,
3463                               input->pointer_surface,
3464                               image->hotspot_x, image->hotspot_y);
3465         wl_surface_attach(input->pointer_surface, buffer, 0, 0);
3466         wl_surface_damage(input->pointer_surface, 0, 0,
3467                           image->width, image->height);
3468         wl_surface_commit(input->pointer_surface);
3469 }
3470
3471 static const struct wl_callback_listener pointer_surface_listener;
3472
3473 static void
3474 pointer_surface_frame_callback(void *data, struct wl_callback *callback,
3475                                uint32_t time)
3476 {
3477         struct input *input = data;
3478         struct wl_cursor *cursor;
3479         int i;
3480
3481         if (callback) {
3482                 assert(callback == input->cursor_frame_cb);
3483                 wl_callback_destroy(callback);
3484                 input->cursor_frame_cb = NULL;
3485         }
3486
3487         if (!input->pointer)
3488                 return;
3489
3490         if (input->current_cursor == CURSOR_BLANK) {
3491                 wl_pointer_set_cursor(input->pointer,
3492                                       input->pointer_enter_serial,
3493                                       NULL, 0, 0);
3494                 return;
3495         }
3496
3497         if (input->current_cursor == CURSOR_UNSET)
3498                 return;
3499         cursor = input->display->cursors[input->current_cursor];
3500         if (!cursor)
3501                 return;
3502
3503         /* FIXME We don't have the current time on the first call so we set
3504          * the animation start to the time of the first frame callback. */
3505         if (time == 0)
3506                 input->cursor_anim_start = 0;
3507         else if (input->cursor_anim_start == 0)
3508                 input->cursor_anim_start = time;
3509
3510         if (time == 0 || input->cursor_anim_start == 0)
3511                 i = 0;
3512         else
3513                 i = wl_cursor_frame(cursor, time - input->cursor_anim_start);
3514
3515         if (cursor->image_count > 1) {
3516                 input->cursor_frame_cb =
3517                         wl_surface_frame(input->pointer_surface);
3518                 wl_callback_add_listener(input->cursor_frame_cb,
3519                                          &pointer_surface_listener, input);
3520         }
3521
3522         input_set_pointer_image_index(input, i);
3523 }
3524
3525 static const struct wl_callback_listener pointer_surface_listener = {
3526         pointer_surface_frame_callback
3527 };
3528
3529 void
3530 input_set_pointer_image(struct input *input, int pointer)
3531 {
3532         int force = 0;
3533
3534         if (!input->pointer)
3535                 return;
3536
3537         if (input->pointer_enter_serial > input->cursor_serial)
3538                 force = 1;
3539
3540         if (!force && pointer == input->current_cursor)
3541                 return;
3542
3543         input->current_cursor = pointer;
3544         input->cursor_serial = input->pointer_enter_serial;
3545         if (!input->cursor_frame_cb)
3546                 pointer_surface_frame_callback(input, NULL, 0);
3547         else if (force) {
3548                 /* The current frame callback may be stuck if, for instance,
3549                  * the set cursor request was processed by the server after
3550                  * this client lost the focus. In this case the cursor surface
3551                  * might not be mapped and the frame callback wouldn't ever
3552                  * complete. Send a set_cursor and attach to try to map the
3553                  * cursor surface again so that the callback will finish */
3554                 input_set_pointer_image_index(input, 0);
3555         }
3556 }
3557
3558 struct wl_data_device *
3559 input_get_data_device(struct input *input)
3560 {
3561         return input->data_device;
3562 }
3563
3564 void
3565 input_set_selection(struct input *input,
3566                     struct wl_data_source *source, uint32_t time)
3567 {
3568         wl_data_device_set_selection(input->data_device, source, time);
3569 }
3570
3571 void
3572 input_accept(struct input *input, const char *type)
3573 {
3574         wl_data_offer_accept(input->drag_offer->offer,
3575                              input->drag_enter_serial, type);
3576 }
3577
3578 static void
3579 offer_io_func(struct task *task, uint32_t events)
3580 {
3581         struct data_offer *offer =
3582                 container_of(task, struct data_offer, io_task);
3583         unsigned int len;
3584         char buffer[4096];
3585
3586         len = read(offer->fd, buffer, sizeof buffer);
3587         offer->func(buffer, len,
3588                     offer->x, offer->y, offer->user_data);
3589
3590         if (len == 0) {
3591                 close(offer->fd);
3592                 data_offer_destroy(offer);
3593         }
3594 }
3595
3596 static void
3597 data_offer_receive_data(struct data_offer *offer, const char *mime_type,
3598                         data_func_t func, void *user_data)
3599 {
3600         int p[2];
3601
3602         if (pipe2(p, O_CLOEXEC) == -1)
3603                 return;
3604
3605         wl_data_offer_receive(offer->offer, mime_type, p[1]);
3606         close(p[1]);
3607
3608         offer->io_task.run = offer_io_func;
3609         offer->fd = p[0];
3610         offer->func = func;
3611         offer->refcount++;
3612         offer->user_data = user_data;
3613
3614         display_watch_fd(offer->input->display,
3615                          offer->fd, EPOLLIN, &offer->io_task);
3616 }
3617
3618 void
3619 input_receive_drag_data(struct input *input, const char *mime_type,
3620                         data_func_t func, void *data)
3621 {
3622         data_offer_receive_data(input->drag_offer, mime_type, func, data);
3623         input->drag_offer->x = input->drag_x;
3624         input->drag_offer->y = input->drag_y;
3625 }
3626
3627 int
3628 input_receive_drag_data_to_fd(struct input *input,
3629                               const char *mime_type, int fd)
3630 {
3631         if (input->drag_offer)
3632                 wl_data_offer_receive(input->drag_offer->offer, mime_type, fd);
3633
3634         return 0;
3635 }
3636
3637 int
3638 input_receive_selection_data(struct input *input, const char *mime_type,
3639                              data_func_t func, void *data)
3640 {
3641         char **p;
3642
3643         if (input->selection_offer == NULL)
3644                 return -1;
3645
3646         for (p = input->selection_offer->types.data; *p; p++)
3647                 if (strcmp(mime_type, *p) == 0)
3648                         break;
3649
3650         if (*p == NULL)
3651                 return -1;
3652
3653         data_offer_receive_data(input->selection_offer,
3654                                 mime_type, func, data);
3655         return 0;
3656 }
3657
3658 int
3659 input_receive_selection_data_to_fd(struct input *input,
3660                                    const char *mime_type, int fd)
3661 {
3662         if (input->selection_offer)
3663                 wl_data_offer_receive(input->selection_offer->offer,
3664                                       mime_type, fd);
3665
3666         return 0;
3667 }
3668
3669 void
3670 window_move(struct window *window, struct input *input, uint32_t serial)
3671 {
3672         if (!window->shell_surface)
3673                 return;
3674
3675         wl_shell_surface_move(window->shell_surface, input->seat, serial);
3676 }
3677
3678 static void
3679 surface_set_synchronized(struct surface *surface)
3680 {
3681         if (!surface->subsurface)
3682                 return;
3683
3684         if (surface->synchronized)
3685                 return;
3686
3687         wl_subsurface_set_sync(surface->subsurface);
3688         surface->synchronized = 1;
3689 }
3690
3691 static void
3692 surface_set_synchronized_default(struct surface *surface)
3693 {
3694         if (!surface->subsurface)
3695                 return;
3696
3697         if (surface->synchronized == surface->synchronized_default)
3698                 return;
3699
3700         if (surface->synchronized_default)
3701                 wl_subsurface_set_sync(surface->subsurface);
3702         else
3703                 wl_subsurface_set_desync(surface->subsurface);
3704
3705         surface->synchronized = surface->synchronized_default;
3706 }
3707
3708 static void
3709 surface_resize(struct surface *surface)
3710 {
3711         struct widget *widget = surface->widget;
3712         struct wl_compositor *compositor = widget->window->display->compositor;
3713
3714         if (surface->input_region) {
3715                 wl_region_destroy(surface->input_region);
3716                 surface->input_region = NULL;
3717         }
3718
3719         if (surface->opaque_region)
3720                 wl_region_destroy(surface->opaque_region);
3721
3722         surface->opaque_region = wl_compositor_create_region(compositor);
3723
3724         if (widget->resize_handler)
3725                 widget->resize_handler(widget,
3726                                        widget->allocation.width,
3727                                        widget->allocation.height,
3728                                        widget->user_data);
3729
3730         if (surface->subsurface &&
3731             (surface->allocation.x != widget->allocation.x ||
3732              surface->allocation.y != widget->allocation.y)) {
3733                 wl_subsurface_set_position(surface->subsurface,
3734                                            widget->allocation.x,
3735                                            widget->allocation.y);
3736         }
3737         if (surface->allocation.width != widget->allocation.width ||
3738             surface->allocation.height != widget->allocation.height) {
3739                 window_schedule_redraw(widget->window);
3740         }
3741         surface->allocation = widget->allocation;
3742
3743         if (widget->opaque)
3744                 wl_region_add(surface->opaque_region, 0, 0,
3745                               widget->allocation.width,
3746                               widget->allocation.height);
3747 }
3748
3749 static void
3750 hack_prevent_EGL_sub_surface_deadlock(struct window *window)
3751 {
3752         /*
3753          * This hack should be removed, when EGL respects
3754          * eglSwapInterval(0).
3755          *
3756          * If this window has sub-surfaces, especially a free-running
3757          * EGL-widget, we need to post the parent surface once with
3758          * all the old state to guarantee, that the EGL-widget will
3759          * receive its frame callback soon. Otherwise, a forced call
3760          * to eglSwapBuffers may end up blocking, waiting for a frame
3761          * event that will never come, because we will commit the parent
3762          * surface with all new state only after eglSwapBuffers returns.
3763          *
3764          * This assumes, that:
3765          * 1. When the EGL widget's resize hook is called, it pauses.
3766          * 2. When the EGL widget's redraw hook is called, it forces a
3767          *    repaint and a call to eglSwapBuffers(), and maybe resumes.
3768          * In a single threaded application condition 1 is a no-op.
3769          *
3770          * XXX: This should actually be after the surface_resize() calls,
3771          * but cannot, because then it would commit the incomplete state
3772          * accumulated from the widget resize hooks.
3773          */
3774         if (window->subsurface_list.next != &window->main_surface->link ||
3775             window->subsurface_list.prev != &window->main_surface->link)
3776                 wl_surface_commit(window->main_surface->surface);
3777 }
3778
3779 static void
3780 window_do_resize(struct window *window)
3781 {
3782         struct surface *surface;
3783
3784         widget_set_allocation(window->main_surface->widget,
3785                               window->pending_allocation.x,
3786                               window->pending_allocation.y,
3787                               window->pending_allocation.width,
3788                               window->pending_allocation.height);
3789
3790         surface_resize(window->main_surface);
3791
3792         /* The main surface is in the list, too. Main surface's
3793          * resize_handler is responsible for calling widget_set_allocation()
3794          * on all sub-surface root widgets, so they will be resized
3795          * properly.
3796          */
3797         wl_list_for_each(surface, &window->subsurface_list, link) {
3798                 if (surface == window->main_surface)
3799                         continue;
3800
3801                 surface_set_synchronized(surface);
3802                 surface_resize(surface);
3803         }
3804 }
3805
3806 static void
3807 idle_resize(struct window *window)
3808 {
3809         window->resize_needed = 0;
3810         window->redraw_needed = 1;
3811
3812         DBG("from %dx%d to %dx%d\n",
3813             window->main_surface->server_allocation.width,
3814             window->main_surface->server_allocation.height,
3815             window->pending_allocation.width,
3816             window->pending_allocation.height);
3817
3818         hack_prevent_EGL_sub_surface_deadlock(window);
3819
3820         window_do_resize(window);
3821 }
3822
3823 static void
3824 undo_resize(struct window *window)
3825 {
3826         window->pending_allocation.width =
3827                 window->main_surface->server_allocation.width;
3828         window->pending_allocation.height =
3829                 window->main_surface->server_allocation.height;
3830
3831         DBG("back to %dx%d\n",
3832             window->main_surface->server_allocation.width,
3833             window->main_surface->server_allocation.height);
3834
3835         window_do_resize(window);
3836
3837         if (window->pending_allocation.width == 0 &&
3838             window->pending_allocation.height == 0) {
3839                 fprintf(stderr, "Error: Could not draw a surface, "
3840                         "most likely due to insufficient disk space in "
3841                         "%s (XDG_RUNTIME_DIR).\n", getenv("XDG_RUNTIME_DIR"));
3842                 exit(EXIT_FAILURE);
3843         }
3844 }
3845
3846 void
3847 window_schedule_resize(struct window *window, int width, int height)
3848 {
3849         /* We should probably get these numbers from the theme. */
3850         const int min_width = 200, min_height = 200;
3851
3852         window->pending_allocation.x = 0;
3853         window->pending_allocation.y = 0;
3854         window->pending_allocation.width = width;
3855         window->pending_allocation.height = height;
3856
3857         if (window->min_allocation.width == 0) {
3858                 if (width < min_width && window->frame)
3859                         window->min_allocation.width = min_width;
3860                 else
3861                         window->min_allocation.width = width;
3862                 if (height < min_height && window->frame)
3863                         window->min_allocation.height = min_height;
3864                 else
3865                         window->min_allocation.height = height;
3866         }
3867
3868         if (window->pending_allocation.width < window->min_allocation.width)
3869                 window->pending_allocation.width = window->min_allocation.width;
3870         if (window->pending_allocation.height < window->min_allocation.height)
3871                 window->pending_allocation.height = window->min_allocation.height;
3872
3873         window->resize_needed = 1;
3874         window_schedule_redraw(window);
3875 }
3876
3877 void
3878 widget_schedule_resize(struct widget *widget, int32_t width, int32_t height)
3879 {
3880         window_schedule_resize(widget->window, width, height);
3881 }
3882
3883 static void
3884 handle_ping(void *data, struct wl_shell_surface *shell_surface,
3885                                                         uint32_t serial)
3886 {
3887         wl_shell_surface_pong(shell_surface, serial);
3888 }
3889
3890 static void
3891 handle_configure(void *data, struct wl_shell_surface *shell_surface,
3892                  uint32_t edges, int32_t width, int32_t height)
3893 {
3894         struct window *window = data;
3895
3896         window->resize_edges = edges;
3897         window_schedule_resize(window, width, height);
3898 }
3899
3900 static void
3901 menu_destroy(struct menu *menu)
3902 {
3903         widget_destroy(menu->widget);
3904         window_destroy(menu->window);
3905         frame_destroy(menu->frame);
3906         free(menu);
3907 }
3908
3909 static void
3910 handle_popup_done(void *data, struct wl_shell_surface *shell_surface)
3911 {
3912         struct window *window = data;
3913         struct menu *menu = window->main_surface->widget->user_data;
3914
3915         /* FIXME: Need more context in this event, at least the input
3916          * device.  Or just use wl_callback.  And this really needs to
3917          * be a window vfunc that the menu can set.  And we need the
3918          * time. */
3919
3920         input_ungrab(menu->input);
3921         menu_destroy(menu);
3922 }
3923
3924 static const struct wl_shell_surface_listener shell_surface_listener = {
3925         handle_ping,
3926         handle_configure,
3927         handle_popup_done
3928 };
3929
3930 void
3931 window_get_allocation(struct window *window,
3932                       struct rectangle *allocation)
3933 {
3934         *allocation = window->main_surface->allocation;
3935 }
3936
3937 static void
3938 widget_redraw(struct widget *widget)
3939 {
3940         struct widget *child;
3941
3942         if (widget->redraw_handler)
3943                 widget->redraw_handler(widget, widget->user_data);
3944         wl_list_for_each(child, &widget->child_list, link)
3945                 widget_redraw(child);
3946 }
3947
3948 static void
3949 frame_callback(void *data, struct wl_callback *callback, uint32_t time)
3950 {
3951         struct surface *surface = data;
3952
3953         assert(callback == surface->frame_cb);
3954         DBG_OBJ(callback, "done\n");
3955         wl_callback_destroy(callback);
3956         surface->frame_cb = NULL;
3957
3958         surface->last_time = time;
3959
3960         if (surface->redraw_needed || surface->window->redraw_needed) {
3961                 DBG_OBJ(surface->surface, "window_schedule_redraw_task\n");
3962                 window_schedule_redraw_task(surface->window);
3963         }
3964 }
3965
3966 static const struct wl_callback_listener listener = {
3967         frame_callback
3968 };
3969
3970 static int
3971 surface_redraw(struct surface *surface)
3972 {
3973         DBG_OBJ(surface->surface, "begin\n");
3974
3975         if (!surface->window->redraw_needed && !surface->redraw_needed)
3976                 return 0;
3977
3978         /* Whole-window redraw forces a redraw even if the previous has
3979          * not yet hit the screen.
3980          */
3981         if (surface->frame_cb) {
3982                 if (!surface->window->redraw_needed)
3983                         return 0;
3984
3985                 DBG_OBJ(surface->frame_cb, "cancelled\n");
3986                 wl_callback_destroy(surface->frame_cb);
3987         }
3988
3989         if (surface->widget->use_cairo &&
3990             !widget_get_cairo_surface(surface->widget)) {
3991                 DBG_OBJ(surface->surface, "cancelled due buffer failure\n");
3992                 return -1;
3993         }
3994
3995         surface->frame_cb = wl_surface_frame(surface->surface);
3996         wl_callback_add_listener(surface->frame_cb, &listener, surface);
3997         DBG_OBJ(surface->frame_cb, "new\n");
3998
3999         surface->redraw_needed = 0;
4000         DBG_OBJ(surface->surface, "-> widget_redraw\n");
4001         widget_redraw(surface->widget);
4002         DBG_OBJ(surface->surface, "done\n");
4003         return 0;
4004 }
4005
4006 static void
4007 idle_redraw(struct task *task, uint32_t events)
4008 {
4009         struct window *window = container_of(task, struct window, redraw_task);
4010         struct surface *surface;
4011         int failed = 0;
4012         int resized = 0;
4013
4014         DBG(" --------- \n");
4015
4016         wl_list_init(&window->redraw_task.link);
4017         window->redraw_task_scheduled = 0;
4018
4019         if (window->resize_needed) {
4020                 /* throttle resizing to the main surface display */
4021                 if (window->main_surface->frame_cb) {
4022                         DBG_OBJ(window->main_surface->frame_cb, "pending\n");
4023                         return;
4024                 }
4025
4026                 idle_resize(window);
4027                 resized = 1;
4028         }
4029
4030         if (surface_redraw(window->main_surface) < 0) {
4031                 /*
4032                  * Only main_surface failure will cause us to undo the resize.
4033                  * If sub-surfaces fail, they will just be broken with old
4034                  * content.
4035                  */
4036                 failed = 1;
4037         } else {
4038                 wl_list_for_each(surface, &window->subsurface_list, link) {
4039                         if (surface == window->main_surface)
4040                                 continue;
4041
4042                         surface_redraw(surface);
4043                 }
4044         }
4045
4046         window->redraw_needed = 0;
4047         window_flush(window);
4048
4049         wl_list_for_each(surface, &window->subsurface_list, link)
4050                 surface_set_synchronized_default(surface);
4051
4052         if (resized && failed) {
4053                 /* Restore widget tree to correspond to what is on screen. */
4054                 undo_resize(window);
4055         }
4056 }
4057
4058 static void
4059 window_schedule_redraw_task(struct window *window)
4060 {
4061         if (window->configure_requests)
4062                 return;
4063         if (!window->redraw_task_scheduled) {
4064                 window->redraw_task.run = idle_redraw;
4065                 display_defer(window->display, &window->redraw_task);
4066                 window->redraw_task_scheduled = 1;
4067         }
4068 }
4069
4070 void
4071 window_schedule_redraw(struct window *window)
4072 {
4073         struct surface *surface;
4074
4075         DBG_OBJ(window->main_surface->surface, "window %p\n", window);
4076
4077         wl_list_for_each(surface, &window->subsurface_list, link)
4078                 surface->redraw_needed = 1;
4079
4080         window_schedule_redraw_task(window);
4081 }
4082
4083 int
4084 window_is_fullscreen(struct window *window)
4085 {
4086         return window->type == TYPE_FULLSCREEN;
4087 }
4088
4089 int
4090 window_is_transient(struct window *window)
4091 {
4092         return window->type == TYPE_TRANSIENT;
4093 }
4094
4095 static void
4096 configure_request_completed(void *data, struct wl_callback *callback, uint32_t  time)
4097 {
4098         struct window *window = data;
4099
4100         wl_callback_destroy(callback);
4101         window->configure_requests--;
4102
4103         if (!window->configure_requests)
4104                 window_schedule_redraw(window);
4105 }
4106
4107 static struct wl_callback_listener configure_request_listener = {
4108         configure_request_completed,
4109 };
4110
4111 static void
4112 window_defer_redraw_until_configure(struct window* window)
4113 {
4114         struct wl_callback *callback;
4115
4116         if (window->redraw_task_scheduled) {
4117                 wl_list_remove(&window->redraw_task.link);
4118                 window->redraw_task_scheduled = 0;
4119         }
4120
4121         callback = wl_display_sync(window->display->display);
4122         wl_callback_add_listener(callback, &configure_request_listener, window);
4123         window->configure_requests++;
4124 }
4125
4126 void
4127 window_set_fullscreen(struct window *window, int fullscreen)
4128 {
4129         if (!window->display->shell)
4130                 return;
4131
4132         if ((window->type == TYPE_FULLSCREEN) == fullscreen)
4133                 return;
4134
4135         if (fullscreen) {
4136                 window->saved_type = window->type;
4137                 if (window->type == TYPE_TOPLEVEL) {
4138                         window->saved_allocation = window->main_surface->allocation;
4139                 }
4140                 window->type = TYPE_FULLSCREEN;
4141                 wl_shell_surface_set_fullscreen(window->shell_surface,
4142                                                 window->fullscreen_method,
4143                                                 0, NULL);
4144                 window_defer_redraw_until_configure (window);
4145         } else {
4146                 if (window->saved_type == TYPE_MAXIMIZED) {
4147                         window_set_maximized(window, 1);
4148                 } else {
4149                         window->type = TYPE_TOPLEVEL;
4150                         wl_shell_surface_set_toplevel(window->shell_surface);
4151                         window_schedule_resize(window,
4152                                                    window->saved_allocation.width,
4153                                                    window->saved_allocation.height);
4154                 }
4155
4156         }
4157 }
4158
4159 void
4160 window_set_fullscreen_method(struct window *window,
4161                              enum wl_shell_surface_fullscreen_method method)
4162 {
4163         window->fullscreen_method = method;
4164 }
4165
4166 int
4167 window_is_maximized(struct window *window)
4168 {
4169         return window->type == TYPE_MAXIMIZED;
4170 }
4171
4172 void
4173 window_set_maximized(struct window *window, int maximized)
4174 {
4175         if (!window->display->shell)
4176                 return;
4177
4178         if ((window->type == TYPE_MAXIMIZED) == maximized)
4179                 return;
4180
4181         if (window->type == TYPE_TOPLEVEL) {
4182                 window->saved_allocation = window->main_surface->allocation;
4183                 wl_shell_surface_set_maximized(window->shell_surface, NULL);
4184                 window->type = TYPE_MAXIMIZED;
4185                 window_defer_redraw_until_configure(window);
4186         } else if (window->type == TYPE_FULLSCREEN) {
4187                 wl_shell_surface_set_maximized(window->shell_surface, NULL);
4188                 window->type = TYPE_MAXIMIZED;
4189                 window_defer_redraw_until_configure(window);
4190         } else {
4191                 wl_shell_surface_set_toplevel(window->shell_surface);
4192                 window->type = TYPE_TOPLEVEL;
4193                 window_schedule_resize(window,
4194                                        window->saved_allocation.width,
4195                                        window->saved_allocation.height);
4196         }
4197 }
4198
4199 void
4200 window_set_user_data(struct window *window, void *data)
4201 {
4202         window->user_data = data;
4203 }
4204
4205 void *
4206 window_get_user_data(struct window *window)
4207 {
4208         return window->user_data;
4209 }
4210
4211 void
4212 window_set_key_handler(struct window *window,
4213                        window_key_handler_t handler)
4214 {
4215         window->key_handler = handler;
4216 }
4217
4218 void
4219 window_set_keyboard_focus_handler(struct window *window,
4220                                   window_keyboard_focus_handler_t handler)
4221 {
4222         window->keyboard_focus_handler = handler;
4223 }
4224
4225 void
4226 window_set_data_handler(struct window *window, window_data_handler_t handler)
4227 {
4228         window->data_handler = handler;
4229 }
4230
4231 void
4232 window_set_drop_handler(struct window *window, window_drop_handler_t handler)
4233 {
4234         window->drop_handler = handler;
4235 }
4236
4237 void
4238 window_set_close_handler(struct window *window,
4239                          window_close_handler_t handler)
4240 {
4241         window->close_handler = handler;
4242 }
4243
4244 void
4245 window_set_fullscreen_handler(struct window *window,
4246                               window_fullscreen_handler_t handler)
4247 {
4248         window->fullscreen_handler = handler;
4249 }
4250
4251 void
4252 window_set_output_handler(struct window *window,
4253                           window_output_handler_t handler)
4254 {
4255         window->output_handler = handler;
4256 }
4257
4258 void
4259 window_set_title(struct window *window, const char *title)
4260 {
4261         free(window->title);
4262         window->title = strdup(title);
4263         if (window->frame) {
4264                 frame_set_title(window->frame->frame, title);
4265                 widget_schedule_redraw(window->frame->widget);
4266         }
4267         if (window->shell_surface)
4268                 wl_shell_surface_set_title(window->shell_surface, title);
4269 }
4270
4271 const char *
4272 window_get_title(struct window *window)
4273 {
4274         return window->title;
4275 }
4276
4277 void
4278 window_set_text_cursor_position(struct window *window, int32_t x, int32_t y)
4279 {
4280         struct text_cursor_position *text_cursor_position =
4281                                         window->display->text_cursor_position;
4282
4283         if (!text_cursor_position)
4284                 return;
4285
4286         text_cursor_position_notify(text_cursor_position,
4287                                     window->main_surface->surface,
4288                                     wl_fixed_from_int(x),
4289                                     wl_fixed_from_int(y));
4290 }
4291
4292 void
4293 window_damage(struct window *window, int32_t x, int32_t y,
4294               int32_t width, int32_t height)
4295 {
4296         wl_surface_damage(window->main_surface->surface, x, y, width, height);
4297 }
4298
4299 static void
4300 surface_enter(void *data,
4301               struct wl_surface *wl_surface, struct wl_output *wl_output)
4302 {
4303         struct window *window = data;
4304         struct output *output;
4305         struct output *output_found = NULL;
4306         struct window_output *window_output;
4307
4308         wl_list_for_each(output, &window->display->output_list, link) {
4309                 if (output->output == wl_output) {
4310                         output_found = output;
4311                         break;
4312                 }
4313         }
4314
4315         if (!output_found)
4316                 return;
4317
4318         window_output = xmalloc(sizeof *window_output);
4319         window_output->output = output_found;
4320
4321         wl_list_insert (&window->window_output_list, &window_output->link);
4322
4323         if (window->output_handler)
4324                 window->output_handler(window, output_found, 1,
4325                                        window->user_data);
4326 }
4327
4328 static void
4329 surface_leave(void *data,
4330               struct wl_surface *wl_surface, struct wl_output *output)
4331 {
4332         struct window *window = data;
4333         struct window_output *window_output;
4334         struct window_output *window_output_found = NULL;
4335
4336         wl_list_for_each(window_output, &window->window_output_list, link) {
4337                 if (window_output->output->output == output) {
4338                         window_output_found = window_output;
4339                         break;
4340                 }
4341         }
4342
4343         if (window_output_found) {
4344                 wl_list_remove(&window_output_found->link);
4345
4346                 if (window->output_handler)
4347                         window->output_handler(window, window_output->output,
4348                                                0, window->user_data);
4349
4350                 free(window_output_found);
4351         }
4352 }
4353
4354 static const struct wl_surface_listener surface_listener = {
4355         surface_enter,
4356         surface_leave
4357 };
4358
4359 static struct surface *
4360 surface_create(struct window *window)
4361 {
4362         struct display *display = window->display;
4363         struct surface *surface;
4364
4365         surface = xmalloc(sizeof *surface);
4366         memset(surface, 0, sizeof *surface);
4367         if (!surface)
4368                 return NULL;
4369
4370         surface->window = window;
4371         surface->surface = wl_compositor_create_surface(display->compositor);
4372         surface->buffer_scale = 1;
4373         wl_surface_add_listener(surface->surface, &surface_listener, window);
4374
4375         wl_list_insert(&window->subsurface_list, &surface->link);
4376
4377         return surface;
4378 }
4379
4380 static struct window *
4381 window_create_internal(struct display *display, int type)
4382 {
4383         struct window *window;
4384         struct surface *surface;
4385
4386         window = xzalloc(sizeof *window);
4387         wl_list_init(&window->subsurface_list);
4388         window->display = display;
4389
4390         surface = surface_create(window);
4391         window->main_surface = surface;
4392
4393         if (type != TYPE_CUSTOM && display->shell) {
4394                 window->shell_surface =
4395                         wl_shell_get_shell_surface(display->shell,
4396                                                    surface->surface);
4397                 fail_on_null(window->shell_surface);
4398         }
4399
4400         window->type = type;
4401         window->fullscreen_method = WL_SHELL_SURFACE_FULLSCREEN_METHOD_DEFAULT;
4402         window->configure_requests = 0;
4403         window->preferred_format = WINDOW_PREFERRED_FORMAT_NONE;
4404
4405         if (display->argb_device)
4406 #ifdef HAVE_CAIRO_EGL
4407                 surface->buffer_type = WINDOW_BUFFER_TYPE_EGL_WINDOW;
4408 #else
4409                 surface->buffer_type = WINDOW_BUFFER_TYPE_SHM;
4410 #endif
4411         else
4412                 surface->buffer_type = WINDOW_BUFFER_TYPE_SHM;
4413
4414         wl_surface_set_user_data(surface->surface, window);
4415         wl_list_insert(display->window_list.prev, &window->link);
4416         wl_list_init(&window->redraw_task.link);
4417
4418         if (window->shell_surface) {
4419                 wl_shell_surface_set_user_data(window->shell_surface, window);
4420                 wl_shell_surface_add_listener(window->shell_surface,
4421                                               &shell_surface_listener, window);
4422         }
4423
4424         wl_list_init (&window->window_output_list);
4425
4426         return window;
4427 }
4428
4429 struct window *
4430 window_create(struct display *display)
4431 {
4432         return window_create_internal(display, TYPE_NONE);
4433 }
4434
4435 struct window *
4436 window_create_custom(struct display *display)
4437 {
4438         return window_create_internal(display, TYPE_CUSTOM);
4439 }
4440
4441 struct window *
4442 window_create_transient(struct display *display, struct window *parent,
4443                         int32_t x, int32_t y, uint32_t flags)
4444 {
4445         struct window *window;
4446
4447         window = window_create_internal(parent->display, TYPE_TRANSIENT);
4448
4449         window->x = x;
4450         window->y = y;
4451
4452         if (display->shell)
4453                 wl_shell_surface_set_transient(
4454                         window->shell_surface,
4455                         parent->main_surface->surface,
4456                         window->x, window->y, flags);
4457
4458         return window;
4459 }
4460
4461 static void
4462 menu_set_item(struct menu *menu, int sy)
4463 {
4464         int32_t x, y, width, height;
4465         int next;
4466
4467         frame_interior(menu->frame, &x, &y, &width, &height);
4468         next = (sy - y) / 20;
4469         if (menu->current != next) {
4470                 menu->current = next;
4471                 widget_schedule_redraw(menu->widget);
4472         }
4473 }
4474
4475 static int
4476 menu_motion_handler(struct widget *widget,
4477                     struct input *input, uint32_t time,
4478                     float x, float y, void *data)
4479 {
4480         struct menu *menu = data;
4481
4482         if (widget == menu->widget)
4483                 menu_set_item(data, y);
4484
4485         return CURSOR_LEFT_PTR;
4486 }
4487
4488 static int
4489 menu_enter_handler(struct widget *widget,
4490                    struct input *input, float x, float y, void *data)
4491 {
4492         struct menu *menu = data;
4493
4494         if (widget == menu->widget)
4495                 menu_set_item(data, y);
4496
4497         return CURSOR_LEFT_PTR;
4498 }
4499
4500 static void
4501 menu_leave_handler(struct widget *widget, struct input *input, void *data)
4502 {
4503         struct menu *menu = data;
4504
4505         if (widget == menu->widget)
4506                 menu_set_item(data, -200);
4507 }
4508
4509 static void
4510 menu_button_handler(struct widget *widget,
4511                     struct input *input, uint32_t time,
4512                     uint32_t button, enum wl_pointer_button_state state,
4513                     void *data)
4514
4515 {
4516         struct menu *menu = data;
4517
4518         if (state == WL_POINTER_BUTTON_STATE_RELEASED &&
4519             (menu->release_count > 0 || time - menu->time > 500)) {
4520                 /* Either relase after press-drag-release or
4521                  * click-motion-click. */
4522                 menu->func(menu->parent, input,
4523                            menu->current, menu->parent->user_data);
4524                 input_ungrab(input);
4525                 menu_destroy(menu);
4526         } else if (state == WL_POINTER_BUTTON_STATE_RELEASED) {
4527                 menu->release_count++;
4528         }
4529 }
4530
4531 static void
4532 menu_redraw_handler(struct widget *widget, void *data)
4533 {
4534         cairo_t *cr;
4535         struct menu *menu = data;
4536         int32_t x, y, width, height, i;
4537
4538         cr = widget_cairo_create(widget);
4539
4540         frame_repaint(menu->frame, cr);
4541         frame_interior(menu->frame, &x, &y, &width, &height);
4542
4543         theme_set_background_source(menu->window->display->theme,
4544                                     cr, THEME_FRAME_ACTIVE);
4545         cairo_rectangle(cr, x, y, width, height);
4546         cairo_fill(cr);
4547
4548         cairo_select_font_face(cr, "sans",
4549                                CAIRO_FONT_SLANT_NORMAL,
4550                                CAIRO_FONT_WEIGHT_NORMAL);
4551         cairo_set_font_size(cr, 12);
4552
4553         for (i = 0; i < menu->count; i++) {
4554                 if (i == menu->current) {
4555                         cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
4556                         cairo_rectangle(cr, x, y + i * 20, width, 20);
4557                         cairo_fill(cr);
4558                         cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
4559                         cairo_move_to(cr, x + 10, y + i * 20 + 16);
4560                         cairo_show_text(cr, menu->entries[i]);
4561                 } else {
4562                         cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
4563                         cairo_move_to(cr, x + 10, y + i * 20 + 16);
4564                         cairo_show_text(cr, menu->entries[i]);
4565                 }
4566         }
4567
4568         cairo_destroy(cr);
4569 }
4570
4571 void
4572 window_show_menu(struct display *display,
4573                  struct input *input, uint32_t time, struct window *parent,
4574                  int32_t x, int32_t y,
4575                  menu_func_t func, const char **entries, int count)
4576 {
4577         struct window *window;
4578         struct menu *menu;
4579         int32_t ix, iy;
4580
4581         menu = malloc(sizeof *menu);
4582         if (!menu)
4583                 return;
4584
4585         window = window_create_internal(parent->display, TYPE_MENU);
4586         if (!window) {
4587                 free(menu);
4588                 return;
4589         }
4590
4591         menu->window = window;
4592         menu->parent = parent;
4593         menu->widget = window_add_widget(menu->window, menu);
4594         window_set_buffer_scale (menu->window, window_get_buffer_scale (parent));
4595         window_set_buffer_transform (menu->window, window_get_buffer_transform (parent));
4596         menu->frame = frame_create(window->display->theme, 0, 0,
4597                                    FRAME_BUTTON_NONE, NULL);
4598         menu->entries = entries;
4599         menu->count = count;
4600         menu->release_count = 0;
4601         menu->current = -1;
4602         menu->time = time;
4603         menu->func = func;
4604         menu->input = input;
4605         window->type = TYPE_MENU;
4606         window->x = x;
4607         window->y = y;
4608
4609         input_ungrab(input);
4610
4611         widget_set_redraw_handler(menu->widget, menu_redraw_handler);
4612         widget_set_enter_handler(menu->widget, menu_enter_handler);
4613         widget_set_leave_handler(menu->widget, menu_leave_handler);
4614         widget_set_motion_handler(menu->widget, menu_motion_handler);
4615         widget_set_button_handler(menu->widget, menu_button_handler);
4616
4617         input_grab(input, menu->widget, 0);
4618         frame_resize_inside(menu->frame, 200, count * 20);
4619         frame_set_flag(menu->frame, FRAME_FLAG_ACTIVE);
4620         window_schedule_resize(window, frame_width(menu->frame),
4621                                frame_height(menu->frame));
4622
4623         frame_interior(menu->frame, &ix, &iy, NULL, NULL);
4624         wl_shell_surface_set_popup(window->shell_surface, input->seat,
4625                                    display_get_serial(window->display),
4626                                    parent->main_surface->surface,
4627                                    window->x - ix, window->y - iy, 0);
4628 }
4629
4630 void
4631 window_set_buffer_type(struct window *window, enum window_buffer_type type)
4632 {
4633         window->main_surface->buffer_type = type;
4634 }
4635
4636 void
4637 window_set_preferred_format(struct window *window,
4638                             enum preferred_format format)
4639 {
4640         window->preferred_format = format;
4641 }
4642
4643 struct widget *
4644 window_add_subsurface(struct window *window, void *data,
4645                       enum subsurface_mode default_mode)
4646 {
4647         struct widget *widget;
4648         struct surface *surface;
4649         struct wl_surface *parent;
4650         struct wl_subcompositor *subcompo = window->display->subcompositor;
4651
4652         surface = surface_create(window);
4653         widget = widget_create(window, surface, data);
4654         wl_list_init(&widget->link);
4655         surface->widget = widget;
4656
4657         parent = window->main_surface->surface;
4658         surface->subsurface = wl_subcompositor_get_subsurface(subcompo,
4659                                                               surface->surface,
4660                                                               parent);
4661         surface->synchronized = 1;
4662
4663         switch (default_mode) {
4664         case SUBSURFACE_SYNCHRONIZED:
4665                 surface->synchronized_default = 1;
4666                 break;
4667         case SUBSURFACE_DESYNCHRONIZED:
4668                 surface->synchronized_default = 0;
4669                 break;
4670         default:
4671                 assert(!"bad enum subsurface_mode");
4672         }
4673
4674         return widget;
4675 }
4676
4677 static void
4678 display_handle_geometry(void *data,
4679                         struct wl_output *wl_output,
4680                         int x, int y,
4681                         int physical_width,
4682                         int physical_height,
4683                         int subpixel,
4684                         const char *make,
4685                         const char *model,
4686                         int transform)
4687 {
4688         struct output *output = data;
4689
4690         output->allocation.x = x;
4691         output->allocation.y = y;
4692         output->transform = transform;
4693 }
4694
4695 static void
4696 display_handle_done(void *data,
4697                      struct wl_output *wl_output)
4698 {
4699 }
4700
4701 static void
4702 display_handle_scale(void *data,
4703                      struct wl_output *wl_output,
4704                      int32_t scale)
4705 {
4706         struct output *output = data;
4707
4708         output->scale = scale;
4709 }
4710
4711 static void
4712 display_handle_mode(void *data,
4713                     struct wl_output *wl_output,
4714                     uint32_t flags,
4715                     int width,
4716                     int height,
4717                     int refresh)
4718 {
4719         struct output *output = data;
4720         struct display *display = output->display;
4721
4722         if (flags & WL_OUTPUT_MODE_CURRENT) {
4723                 output->allocation.width = width;
4724                 output->allocation.height = height;
4725                 if (display->output_configure_handler)
4726                         (*display->output_configure_handler)(
4727                                                 output, display->user_data);
4728         }
4729 }
4730
4731 static const struct wl_output_listener output_listener = {
4732         display_handle_geometry,
4733         display_handle_mode,
4734         display_handle_done,
4735         display_handle_scale
4736 };
4737
4738 static void
4739 display_add_output(struct display *d, uint32_t id)
4740 {
4741         struct output *output;
4742
4743         output = xzalloc(sizeof *output);
4744         output->display = d;
4745         output->scale = 1;
4746         output->output =
4747                 wl_registry_bind(d->registry, id, &wl_output_interface, 2);
4748         output->server_output_id = id;
4749         wl_list_insert(d->output_list.prev, &output->link);
4750
4751         wl_output_add_listener(output->output, &output_listener, output);
4752 }
4753
4754 static void
4755 output_destroy(struct output *output)
4756 {
4757         if (output->destroy_handler)
4758                 (*output->destroy_handler)(output, output->user_data);
4759
4760         wl_output_destroy(output->output);
4761         wl_list_remove(&output->link);
4762         free(output);
4763 }
4764
4765 static void
4766 display_destroy_output(struct display *d, uint32_t id)
4767 {
4768         struct output *output;
4769
4770         wl_list_for_each(output, &d->output_list, link) {
4771                 if (output->server_output_id == id) {
4772                         output_destroy(output);
4773                         break;
4774                 }
4775         }
4776 }
4777
4778 void
4779 display_set_global_handler(struct display *display,
4780                            display_global_handler_t handler)
4781 {
4782         struct global *global;
4783
4784         display->global_handler = handler;
4785         if (!handler)
4786                 return;
4787
4788         wl_list_for_each(global, &display->global_list, link)
4789                 display->global_handler(display,
4790                                         global->name, global->interface,
4791                                         global->version, display->user_data);
4792 }
4793
4794 void
4795 display_set_global_handler_remove(struct display *display,
4796                            display_global_handler_t remove_handler)
4797 {
4798         display->global_handler_remove = remove_handler;
4799         if (!remove_handler)
4800                 return;
4801 }
4802
4803 void
4804 display_set_output_configure_handler(struct display *display,
4805                                      display_output_handler_t handler)
4806 {
4807         struct output *output;
4808
4809         display->output_configure_handler = handler;
4810         if (!handler)
4811                 return;
4812
4813         wl_list_for_each(output, &display->output_list, link) {
4814                 if (output->allocation.width == 0 &&
4815                     output->allocation.height == 0)
4816                         continue;
4817
4818                 (*display->output_configure_handler)(output,
4819                                                      display->user_data);
4820         }
4821 }
4822
4823 void
4824 output_set_user_data(struct output *output, void *data)
4825 {
4826         output->user_data = data;
4827 }
4828
4829 void *
4830 output_get_user_data(struct output *output)
4831 {
4832         return output->user_data;
4833 }
4834
4835 void
4836 output_set_destroy_handler(struct output *output,
4837                            display_output_handler_t handler)
4838 {
4839         output->destroy_handler = handler;
4840         /* FIXME: implement this, once we have way to remove outputs */
4841 }
4842
4843 void
4844 output_get_allocation(struct output *output, struct rectangle *base)
4845 {
4846         struct rectangle allocation = output->allocation;
4847
4848         switch (output->transform) {
4849         case WL_OUTPUT_TRANSFORM_90:
4850         case WL_OUTPUT_TRANSFORM_270:
4851         case WL_OUTPUT_TRANSFORM_FLIPPED_90:
4852         case WL_OUTPUT_TRANSFORM_FLIPPED_270:
4853                 /* Swap width and height */
4854                 allocation.width = output->allocation.height;
4855                 allocation.height = output->allocation.width;
4856                 break;
4857         }
4858
4859         *base = allocation;
4860 }
4861
4862 struct wl_output *
4863 output_get_wl_output(struct output *output)
4864 {
4865         return output->output;
4866 }
4867
4868 enum wl_output_transform
4869 output_get_transform(struct output *output)
4870 {
4871         return output->transform;
4872 }
4873
4874 uint32_t
4875 output_get_scale(struct output *output)
4876 {
4877         return output->scale;
4878 }
4879
4880 static void
4881 fini_xkb(struct input *input)
4882 {
4883         xkb_state_unref(input->xkb.state);
4884         xkb_map_unref(input->xkb.keymap);
4885 }
4886
4887 #define MIN(a,b) ((a) < (b) ? a : b)
4888
4889 static void
4890 display_add_input(struct display *d, uint32_t id)
4891 {
4892         struct input *input;
4893
4894         input = xzalloc(sizeof *input);
4895         input->display = d;
4896         input->seat = wl_registry_bind(d->registry, id, &wl_seat_interface,
4897                                        MIN(d->seat_version, 3));
4898         input->touch_focus = NULL;
4899         input->pointer_focus = NULL;
4900         input->keyboard_focus = NULL;
4901         wl_list_init(&input->touch_point_list);
4902         wl_list_insert(d->input_list.prev, &input->link);
4903
4904         wl_seat_add_listener(input->seat, &seat_listener, input);
4905         wl_seat_set_user_data(input->seat, input);
4906
4907         input->data_device =
4908                 wl_data_device_manager_get_data_device(d->data_device_manager,
4909                                                        input->seat);
4910         wl_data_device_add_listener(input->data_device, &data_device_listener,
4911                                     input);
4912
4913         input->pointer_surface = wl_compositor_create_surface(d->compositor);
4914
4915         input->repeat_timer_fd = timerfd_create(CLOCK_MONOTONIC,
4916                                                 TFD_CLOEXEC | TFD_NONBLOCK);
4917         input->repeat_task.run = keyboard_repeat_func;
4918         display_watch_fd(d, input->repeat_timer_fd,
4919                          EPOLLIN, &input->repeat_task);
4920 }
4921
4922 static void
4923 input_destroy(struct input *input)
4924 {
4925         input_remove_keyboard_focus(input);
4926         input_remove_pointer_focus(input);
4927
4928         if (input->drag_offer)
4929                 data_offer_destroy(input->drag_offer);
4930
4931         if (input->selection_offer)
4932                 data_offer_destroy(input->selection_offer);
4933
4934         wl_data_device_destroy(input->data_device);
4935
4936         if (input->display->seat_version >= 3) {
4937                 if (input->pointer)
4938                         wl_pointer_release(input->pointer);
4939                 if (input->keyboard)
4940                         wl_keyboard_release(input->keyboard);
4941         }
4942
4943         fini_xkb(input);
4944
4945         wl_surface_destroy(input->pointer_surface);
4946
4947         wl_list_remove(&input->link);
4948         wl_seat_destroy(input->seat);
4949         close(input->repeat_timer_fd);
4950         free(input);
4951 }
4952
4953 static void
4954 init_workspace_manager(struct display *d, uint32_t id)
4955 {
4956         d->workspace_manager =
4957                 wl_registry_bind(d->registry, id,
4958                                  &workspace_manager_interface, 1);
4959         if (d->workspace_manager != NULL)
4960                 workspace_manager_add_listener(d->workspace_manager,
4961                                                &workspace_manager_listener,
4962                                                d);
4963 }
4964
4965 static void
4966 shm_format(void *data, struct wl_shm *wl_shm, uint32_t format)
4967 {
4968         struct display *d = data;
4969
4970         if (format == WL_SHM_FORMAT_RGB565)
4971                 d->has_rgb565 = 1;
4972 }
4973
4974 struct wl_shm_listener shm_listener = {
4975         shm_format
4976 };
4977
4978 static void
4979 registry_handle_global(void *data, struct wl_registry *registry, uint32_t id,
4980                        const char *interface, uint32_t version)
4981 {
4982         struct display *d = data;
4983         struct global *global;
4984
4985         global = xmalloc(sizeof *global);
4986         global->name = id;
4987         global->interface = strdup(interface);
4988         global->version = version;
4989         wl_list_insert(d->global_list.prev, &global->link);
4990
4991         if (strcmp(interface, "wl_compositor") == 0) {
4992                 d->compositor = wl_registry_bind(registry, id,
4993                                                  &wl_compositor_interface, 3);
4994         } else if (strcmp(interface, "wl_output") == 0) {
4995                 display_add_output(d, id);
4996         } else if (strcmp(interface, "wl_seat") == 0) {
4997                 d->seat_version = version;
4998                 display_add_input(d, id);
4999         } else if (strcmp(interface, "wl_shell") == 0) {
5000                 d->shell = wl_registry_bind(registry,
5001                                             id, &wl_shell_interface, 1);
5002         } else if (strcmp(interface, "wl_shm") == 0) {
5003                 d->shm = wl_registry_bind(registry, id, &wl_shm_interface, 1);
5004                 wl_shm_add_listener(d->shm, &shm_listener, d);
5005         } else if (strcmp(interface, "wl_data_device_manager") == 0) {
5006                 d->data_device_manager =
5007                         wl_registry_bind(registry, id,
5008                                          &wl_data_device_manager_interface, 1);
5009         } else if (strcmp(interface, "text_cursor_position") == 0) {
5010                 d->text_cursor_position =
5011                         wl_registry_bind(registry, id,
5012                                          &text_cursor_position_interface, 1);
5013         } else if (strcmp(interface, "workspace_manager") == 0) {
5014                 init_workspace_manager(d, id);
5015         } else if (strcmp(interface, "wl_subcompositor") == 0) {
5016                 d->subcompositor =
5017                         wl_registry_bind(registry, id,
5018                                          &wl_subcompositor_interface, 1);
5019         }
5020
5021         if (d->global_handler)
5022                 d->global_handler(d, id, interface, version, d->user_data);
5023 }
5024
5025 static void
5026 registry_handle_global_remove(void *data, struct wl_registry *registry,
5027                               uint32_t name)
5028 {
5029         struct display *d = data;
5030         struct global *global;
5031         struct global *tmp;
5032
5033         wl_list_for_each_safe(global, tmp, &d->global_list, link) {
5034                 if (global->name != name)
5035                         continue;
5036
5037                 if (strcmp(global->interface, "wl_output") == 0)
5038                         display_destroy_output(d, name);
5039
5040                 /* XXX: Should destroy remaining bound globals */
5041
5042                 if (d->global_handler_remove)
5043                         d->global_handler_remove(d, name, global->interface,
5044                                         global->version, d->user_data);
5045
5046                 wl_list_remove(&global->link);
5047                 free(global->interface);
5048                 free(global);
5049         }
5050 }
5051
5052 void *
5053 display_bind(struct display *display, uint32_t name,
5054              const struct wl_interface *interface, uint32_t version)
5055 {
5056         return wl_registry_bind(display->registry, name, interface, version);
5057 }
5058
5059 static const struct wl_registry_listener registry_listener = {
5060         registry_handle_global,
5061         registry_handle_global_remove
5062 };
5063
5064 #ifdef HAVE_CAIRO_EGL
5065 static int
5066 init_egl(struct display *d)
5067 {
5068         EGLint major, minor;
5069         EGLint n;
5070
5071 #ifdef USE_CAIRO_GLESV2
5072 #  define GL_BIT EGL_OPENGL_ES2_BIT
5073 #else
5074 #  define GL_BIT EGL_OPENGL_BIT
5075 #endif
5076
5077         static const EGLint argb_cfg_attribs[] = {
5078                 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
5079                 EGL_RED_SIZE, 1,
5080                 EGL_GREEN_SIZE, 1,
5081                 EGL_BLUE_SIZE, 1,
5082                 EGL_ALPHA_SIZE, 1,
5083                 EGL_DEPTH_SIZE, 1,
5084                 EGL_RENDERABLE_TYPE, GL_BIT,
5085                 EGL_NONE
5086         };
5087
5088 #ifdef USE_CAIRO_GLESV2
5089         static const EGLint context_attribs[] = {
5090                 EGL_CONTEXT_CLIENT_VERSION, 2,
5091                 EGL_NONE
5092         };
5093         EGLint api = EGL_OPENGL_ES_API;
5094 #else
5095         EGLint *context_attribs = NULL;
5096         EGLint api = EGL_OPENGL_API;
5097 #endif
5098
5099         d->dpy = eglGetDisplay(d->display);
5100         if (!eglInitialize(d->dpy, &major, &minor)) {
5101                 fprintf(stderr, "failed to initialize EGL\n");
5102                 return -1;
5103         }
5104
5105         if (!eglBindAPI(api)) {
5106                 fprintf(stderr, "failed to bind EGL client API\n");
5107                 return -1;
5108         }
5109
5110         if (!eglChooseConfig(d->dpy, argb_cfg_attribs,
5111                              &d->argb_config, 1, &n) || n != 1) {
5112                 fprintf(stderr, "failed to choose argb EGL config\n");
5113                 return -1;
5114         }
5115
5116         d->argb_ctx = eglCreateContext(d->dpy, d->argb_config,
5117                                        EGL_NO_CONTEXT, context_attribs);
5118         if (d->argb_ctx == NULL) {
5119                 fprintf(stderr, "failed to create EGL context\n");
5120                 return -1;
5121         }
5122
5123         d->argb_device = cairo_egl_device_create(d->dpy, d->argb_ctx);
5124         if (cairo_device_status(d->argb_device) != CAIRO_STATUS_SUCCESS) {
5125                 fprintf(stderr, "failed to get cairo EGL argb device\n");
5126                 return -1;
5127         }
5128
5129         return 0;
5130 }
5131
5132 static void
5133 fini_egl(struct display *display)
5134 {
5135         cairo_device_destroy(display->argb_device);
5136
5137         eglMakeCurrent(display->dpy, EGL_NO_SURFACE, EGL_NO_SURFACE,
5138                        EGL_NO_CONTEXT);
5139
5140         eglTerminate(display->dpy);
5141         eglReleaseThread();
5142 }
5143 #endif
5144
5145 static void
5146 init_dummy_surface(struct display *display)
5147 {
5148         int len;
5149         void *data;
5150
5151         len = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, 1);
5152         data = malloc(len);
5153         display->dummy_surface =
5154                 cairo_image_surface_create_for_data(data, CAIRO_FORMAT_ARGB32,
5155                                                     1, 1, len);
5156         display->dummy_surface_data = data;
5157 }
5158
5159 static void
5160 handle_display_data(struct task *task, uint32_t events)
5161 {
5162         struct display *display =
5163                 container_of(task, struct display, display_task);
5164         struct epoll_event ep;
5165         int ret;
5166
5167         display->display_fd_events = events;
5168
5169         if (events & EPOLLERR || events & EPOLLHUP) {
5170                 display_exit(display);
5171                 return;
5172         }
5173
5174         if (events & EPOLLIN) {
5175                 ret = wl_display_dispatch(display->display);
5176                 if (ret == -1) {
5177                         display_exit(display);
5178                         return;
5179                 }
5180         }
5181
5182         if (events & EPOLLOUT) {
5183                 ret = wl_display_flush(display->display);
5184                 if (ret == 0) {
5185                         ep.events = EPOLLIN | EPOLLERR | EPOLLHUP;
5186                         ep.data.ptr = &display->display_task;
5187                         epoll_ctl(display->epoll_fd, EPOLL_CTL_MOD,
5188                                   display->display_fd, &ep);
5189                 } else if (ret == -1 && errno != EAGAIN) {
5190                         display_exit(display);
5191                         return;
5192                 }
5193         }
5194 }
5195
5196 static void
5197 log_handler(const char *format, va_list args)
5198 {
5199         vfprintf(stderr, format, args);
5200 }
5201
5202 struct display *
5203 display_create(int *argc, char *argv[])
5204 {
5205         struct display *d;
5206
5207         wl_log_set_handler_client(log_handler);
5208
5209         d = zalloc(sizeof *d);
5210         if (d == NULL)
5211                 return NULL;
5212
5213         d->display = wl_display_connect(NULL);
5214         if (d->display == NULL) {
5215                 fprintf(stderr, "failed to connect to Wayland display: %m\n");
5216                 free(d);
5217                 return NULL;
5218         }
5219
5220         d->xkb_context = xkb_context_new(0);
5221         if (d->xkb_context == NULL) {
5222                 fprintf(stderr, "Failed to create XKB context\n");
5223                 free(d);
5224                 return NULL;
5225         }
5226
5227         d->epoll_fd = os_epoll_create_cloexec();
5228         d->display_fd = wl_display_get_fd(d->display);
5229         d->display_task.run = handle_display_data;
5230         display_watch_fd(d, d->display_fd, EPOLLIN | EPOLLERR | EPOLLHUP,
5231                          &d->display_task);
5232
5233         wl_list_init(&d->deferred_list);
5234         wl_list_init(&d->input_list);
5235         wl_list_init(&d->output_list);
5236         wl_list_init(&d->global_list);
5237
5238         d->workspace = 0;
5239         d->workspace_count = 1;
5240
5241         d->registry = wl_display_get_registry(d->display);
5242         wl_registry_add_listener(d->registry, &registry_listener, d);
5243
5244         if (wl_display_dispatch(d->display) < 0) {
5245                 fprintf(stderr, "Failed to process Wayland connection: %m\n");
5246                 return NULL;
5247         }
5248
5249 #ifdef HAVE_CAIRO_EGL
5250         if (init_egl(d) < 0)
5251                 fprintf(stderr, "EGL does not seem to work, "
5252                         "falling back to software rendering and wl_shm.\n");
5253 #endif
5254
5255         create_cursors(d);
5256
5257         d->theme = theme_create();
5258
5259         wl_list_init(&d->window_list);
5260
5261         init_dummy_surface(d);
5262
5263         return d;
5264 }
5265
5266 static void
5267 display_destroy_outputs(struct display *display)
5268 {
5269         struct output *tmp;
5270         struct output *output;
5271
5272         wl_list_for_each_safe(output, tmp, &display->output_list, link)
5273                 output_destroy(output);
5274 }
5275
5276 static void
5277 display_destroy_inputs(struct display *display)
5278 {
5279         struct input *tmp;
5280         struct input *input;
5281
5282         wl_list_for_each_safe(input, tmp, &display->input_list, link)
5283                 input_destroy(input);
5284 }
5285
5286 void
5287 display_destroy(struct display *display)
5288 {
5289         if (!wl_list_empty(&display->window_list))
5290                 fprintf(stderr, "toytoolkit warning: %d windows exist.\n",
5291                         wl_list_length(&display->window_list));
5292
5293         if (!wl_list_empty(&display->deferred_list))
5294                 fprintf(stderr, "toytoolkit warning: deferred tasks exist.\n");
5295
5296         cairo_surface_destroy(display->dummy_surface);
5297         free(display->dummy_surface_data);
5298
5299         display_destroy_outputs(display);
5300         display_destroy_inputs(display);
5301
5302         xkb_context_unref(display->xkb_context);
5303
5304         theme_destroy(display->theme);
5305         destroy_cursors(display);
5306
5307 #ifdef HAVE_CAIRO_EGL
5308         if (display->argb_device)
5309                 fini_egl(display);
5310 #endif
5311
5312         if (display->subcompositor)
5313                 wl_subcompositor_destroy(display->subcompositor);
5314
5315         if (display->shell)
5316                 wl_shell_destroy(display->shell);
5317
5318         if (display->shm)
5319                 wl_shm_destroy(display->shm);
5320
5321         if (display->data_device_manager)
5322                 wl_data_device_manager_destroy(display->data_device_manager);
5323
5324         wl_compositor_destroy(display->compositor);
5325         wl_registry_destroy(display->registry);
5326
5327         close(display->epoll_fd);
5328
5329         if (!(display->display_fd_events & EPOLLERR) &&
5330             !(display->display_fd_events & EPOLLHUP))
5331                 wl_display_flush(display->display);
5332
5333         wl_display_disconnect(display->display);
5334         free(display);
5335 }
5336
5337 void
5338 display_set_user_data(struct display *display, void *data)
5339 {
5340         display->user_data = data;
5341 }
5342
5343 void *
5344 display_get_user_data(struct display *display)
5345 {
5346         return display->user_data;
5347 }
5348
5349 struct wl_display *
5350 display_get_display(struct display *display)
5351 {
5352         return display->display;
5353 }
5354
5355 int
5356 display_has_subcompositor(struct display *display)
5357 {
5358         if (display->subcompositor)
5359                 return 1;
5360
5361         wl_display_roundtrip(display->display);
5362
5363         return display->subcompositor != NULL;
5364 }
5365
5366 cairo_device_t *
5367 display_get_cairo_device(struct display *display)
5368 {
5369         return display->argb_device;
5370 }
5371
5372 struct output *
5373 display_get_output(struct display *display)
5374 {
5375         return container_of(display->output_list.next, struct output, link);
5376 }
5377
5378 struct wl_compositor *
5379 display_get_compositor(struct display *display)
5380 {
5381         return display->compositor;
5382 }
5383
5384 uint32_t
5385 display_get_serial(struct display *display)
5386 {
5387         return display->serial;
5388 }
5389
5390 EGLDisplay
5391 display_get_egl_display(struct display *d)
5392 {
5393         return d->dpy;
5394 }
5395
5396 struct wl_data_source *
5397 display_create_data_source(struct display *display)
5398 {
5399         return wl_data_device_manager_create_data_source(display->data_device_manager);
5400 }
5401
5402 EGLConfig
5403 display_get_argb_egl_config(struct display *d)
5404 {
5405         return d->argb_config;
5406 }
5407
5408 int
5409 display_acquire_window_surface(struct display *display,
5410                                struct window *window,
5411                                EGLContext ctx)
5412 {
5413         struct surface *surface = window->main_surface;
5414
5415         if (surface->buffer_type != WINDOW_BUFFER_TYPE_EGL_WINDOW)
5416                 return -1;
5417
5418         widget_get_cairo_surface(window->main_surface->widget);
5419         return surface->toysurface->acquire(surface->toysurface, ctx);
5420 }
5421
5422 void
5423 display_release_window_surface(struct display *display,
5424                                struct window *window)
5425 {
5426         struct surface *surface = window->main_surface;
5427
5428         if (surface->buffer_type != WINDOW_BUFFER_TYPE_EGL_WINDOW)
5429                 return;
5430
5431         surface->toysurface->release(surface->toysurface);
5432 }
5433
5434 void
5435 display_defer(struct display *display, struct task *task)
5436 {
5437         wl_list_insert(&display->deferred_list, &task->link);
5438 }
5439
5440 void
5441 display_watch_fd(struct display *display,
5442                  int fd, uint32_t events, struct task *task)
5443 {
5444         struct epoll_event ep;
5445
5446         ep.events = events;
5447         ep.data.ptr = task;
5448         epoll_ctl(display->epoll_fd, EPOLL_CTL_ADD, fd, &ep);
5449 }
5450
5451 void
5452 display_unwatch_fd(struct display *display, int fd)
5453 {
5454         epoll_ctl(display->epoll_fd, EPOLL_CTL_DEL, fd, NULL);
5455 }
5456
5457 void
5458 display_run(struct display *display)
5459 {
5460         struct task *task;
5461         struct epoll_event ep[16];
5462         int i, count, ret;
5463
5464         display->running = 1;
5465         while (1) {
5466                 while (!wl_list_empty(&display->deferred_list)) {
5467                         task = container_of(display->deferred_list.prev,
5468                                             struct task, link);
5469                         wl_list_remove(&task->link);
5470                         task->run(task, 0);
5471                 }
5472
5473                 wl_display_dispatch_pending(display->display);
5474
5475                 if (!display->running)
5476                         break;
5477
5478                 ret = wl_display_flush(display->display);
5479                 if (ret < 0 && errno == EAGAIN) {
5480                         ep[0].events =
5481                                 EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLHUP;
5482                         ep[0].data.ptr = &display->display_task;
5483
5484                         epoll_ctl(display->epoll_fd, EPOLL_CTL_MOD,
5485                                   display->display_fd, &ep[0]);
5486                 } else if (ret < 0) {
5487                         break;
5488                 }
5489
5490                 count = epoll_wait(display->epoll_fd,
5491                                    ep, ARRAY_LENGTH(ep), -1);
5492                 for (i = 0; i < count; i++) {
5493                         task = ep[i].data.ptr;
5494                         task->run(task, ep[i].events);
5495                 }
5496         }
5497 }
5498
5499 void
5500 display_exit(struct display *display)
5501 {
5502         display->running = 0;
5503 }
5504
5505 void
5506 keysym_modifiers_add(struct wl_array *modifiers_map,
5507                      const char *name)
5508 {
5509         size_t len = strlen(name) + 1;
5510         char *p;
5511
5512         p = wl_array_add(modifiers_map, len);
5513
5514         if (p == NULL)
5515                 return;
5516
5517         strncpy(p, name, len);
5518 }
5519
5520 static xkb_mod_index_t
5521 keysym_modifiers_get_index(struct wl_array *modifiers_map,
5522                            const char *name)
5523 {
5524         xkb_mod_index_t index = 0;
5525         char *p = modifiers_map->data;
5526
5527         while ((const char *)p < (const char *)(modifiers_map->data + modifiers_map->size)) {
5528                 if (strcmp(p, name) == 0)
5529                         return index;
5530
5531                 index++;
5532                 p += strlen(p) + 1;
5533         }
5534
5535         return XKB_MOD_INVALID;
5536 }
5537
5538 xkb_mod_mask_t
5539 keysym_modifiers_get_mask(struct wl_array *modifiers_map,
5540                           const char *name)
5541 {
5542         xkb_mod_index_t index = keysym_modifiers_get_index(modifiers_map, name);
5543
5544         if (index == XKB_MOD_INVALID)
5545                 return XKB_MOD_INVALID;
5546
5547         return 1 << index;
5548 }
5549
5550 void *
5551 fail_on_null(void *p)
5552 {
5553         if (p == NULL) {
5554                 fprintf(stderr, "%s: out of memory\n", program_invocation_short_name);
5555                 exit(EXIT_FAILURE);
5556         }
5557
5558         return p;
5559 }
5560
5561 void *
5562 xmalloc(size_t s)
5563 {
5564         return fail_on_null(malloc(s));
5565 }
5566
5567 void *
5568 xzalloc(size_t s)
5569 {
5570         return fail_on_null(zalloc(s));
5571 }
5572
5573 char *
5574 xstrdup(const char *s)
5575 {
5576         return fail_on_null(strdup(s));
5577 }