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