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