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