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