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