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