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