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