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