#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <gio/gio.h>
#include <glib-unix.h>
#include <math.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <time.h>
#include <unistd.h>
#include <wayland-client.h>
#include <xkbcommon/xkbcommon.h>
#include "c8ui-private.h"
#include "c8ui-wayland.h"
#include "wayland-private.h"
#include "cursor-shape-v1-client-protocol.h"
#include "fractional-scale-v1-client-protocol.h"
#include "keyboard-shortcuts-inhibit-unstable-v1-client-protocol.h"
#include "pointer-gestures-unstable-v1-client-protocol.h"
#include "viewporter-client-protocol.h"
#include "xdg-activation-v1-client-protocol.h"
#include "xdg-foreign-unstable-v2-client-protocol.h"
#include "xdg-shell-client-protocol.h"

#define WHEEL_STEP 48 // pixels per wheel click

struct global {
	uint32_t name;
	char *interface;
	uint32_t version;
};

struct buffer {
	struct wl_buffer *wl_buffer;
	void *data;
	size_t len;
	int width, height;
	bool busy;
	bool drop; // not wanted any more: goes when the compositor lets go
	/* What it shows is older than the window: nothing drawn yet (blank),
	 * or these buffer pixels changed in frames drawn into the other one */
	bool blank;
	cairo_region_t *stale;
};

struct c8ui_window {
	struct wl_list link; // c8ui_app.windows
	struct c8ui_app *app;
	struct c8ui_root *root;
	struct wl_surface *surface;
	struct xdg_surface *xdg_surface;
	struct xdg_toplevel *toplevel;
	struct wp_fractional_scale_v1 *fractional;
	struct wp_viewport *viewport;
	struct zwp_keyboard_shortcuts_inhibitor_v1 *inhibitor;
	struct buffer buffers[2];
	bool suspended; // c8ui_window_suspend: nothing is drawn
	int64_t drawn_at; // the last frame, monotonic us
	guint rest; // lets the buffers go once it has sat still
	const struct c8ui_drop_impl *drop; // takes drops, if set
	void *drop_data;
	int width, height; // logical
	double scale; // fractional, or the integer buffer scale
	struct wl_callback *frame_cb;
	c8ui_window_fn leave_fn;
	void *leave_data;
	c8ui_modifiers_fn modifiers_fn;
	void *modifiers_data;
	bool fullscreen; // as the compositor last said
	c8ui_window_fn fullscreen_fn;
	void *fullscreen_data;
	c8ui_window_close_fn close_fn;
	void *close_data;
	c8ui_window_fn scale_fn;
	void *scale_data;
	uint32_t background; // painted under the widgets
	double background_alpha;
	cairo_region_t *opaque; // set by the caller, or NULL
	struct zxdg_exported_v2 *exported; // for portal dialogs, once asked
	struct zxdg_imported_v2 *imported; // another client's parent window
	char *export_handle;
	char *activate_token; // presented before it was mapped
	bool present_waiting; // for a token from another of our windows
	bool configured, dirty, animating, frame_pending;
	bool damage_all; // the next frame draws everything, whatever the root says
	guint idle;
};

struct timer {
	struct c8ui_app *app;
	guint id;
	int interval;
	c8ui_timer_fn fn;
	void *data;
};

struct c8ui_app {
	char *app_id;
	struct wl_display *display;
	struct wl_registry *registry;
	struct global *globals;
	int global_count;
	struct wl_compositor *compositor;
	uint32_t compositor_version;
	struct wl_shm *shm;
	struct xdg_wm_base *wm_base;
	struct wl_seat *seat;
	struct wl_pointer *pointer;
	struct wl_keyboard *keyboard;
	struct wl_touch *touch;
	struct wp_cursor_shape_manager_v1 *cursor_shape_manager;
	struct wp_cursor_shape_device_v1 *cursor_shape;
	struct wp_fractional_scale_manager_v1 *fractional_manager;
	struct wp_viewporter *viewporter;
	struct zwp_keyboard_shortcuts_inhibit_manager_v1 *inhibit_manager;
	struct wl_data_device_manager *data_manager;
	struct wl_data_device *data_device;
	struct zwp_pointer_gestures_v1 *gestures;
	struct zwp_pointer_gesture_swipe_v1 *swipe;
	struct zwp_pointer_gesture_pinch_v1 *pinch;
	struct xdg_activation_v1 *activation;
	struct zxdg_exporter_v2 *exporter;
	struct zxdg_importer_v2 *importer;

	struct wl_list windows;
	GMainLoop *loop;
	GSource *flush_source;
	guint fd_source;
	guint icon_source; // the background icon loader finished something
	int status;

	/* Pointer */
	struct c8ui_window *pointer_window;
	uint32_t enter_serial;
	enum c8ui_cursor cursor;
	struct {
		double dx, dy;
		int discrete_x, discrete_y; // in 120ths of a click
		bool precise, have, stop;
	} axis;

	/* Touch: the window each finger landed on */
	struct {
		int32_t id;
		struct c8ui_window *window; // NULL: a free slot
	} fingers[10];

	/* Keyboard */
	struct xkb_context *xkb;
	struct xkb_keymap *keymap;
	struct xkb_state *state;
	struct c8ui_window *keyboard_window;
	uint32_t last_serial;
	int repeat_rate, repeat_delay;
	uint32_t repeat_key;
	guint repeat_source;

	/* Clipboard */
	struct wl_data_offer *selection;
	struct wl_data_source *source;
	GPtrArray *source_items; // struct clip_item
	c8ui_app_fn clip_fn; // the selection changed
	void *clip_data;

	/* Drag and drop: ours being dragged, and another's (or ours) over us */
	uint32_t press_serial; // the button or finger a drag starts from
	struct {
		struct wl_data_source *source;
		GPtrArray *items; // struct clip_item
		struct wl_surface *icon;
		uint32_t action; // as last chosen by the target
		void (*done)(uint32_t action, void *data);
		void *data;
	} drag;
	struct {
		struct wl_data_offer *offer;
		struct c8ui_window *window;
		uint32_t serial;
		double x, y;
	} dnd;

	/* The one copy (c8ui_app_main) */
	GDBusConnection *unique_bus;
	int hold;
	char *launch_token;

	/* Theme */
	struct c8ui_theme theme;
	char *config_dir;
	GFileMonitor *monitors[2];
};

/* Theme from the cont8nuum configuration */

static char *ini_get(const char *path, const char *section, const char *key) {
	char *text = NULL;
	if (!g_file_get_contents(path, &text, NULL, NULL)) {
		return NULL;
	}
	char *result = NULL;
	char current[256] = "";
	char **lines = g_strsplit(text, "\n", -1);
	for (char **l = lines; *l; l++) {
		char *s = g_strstrip(*l);
		if (s[0] == '[') {
			char *end = strchr(s, ']');
			if (end) {
				*end = '\0';
				snprintf(current, sizeof(current), "%s", g_strstrip(s + 1));
			}
			continue;
		}
		char *eq = strchr(s, '=');
		if (s[0] == '#' || eq == NULL || strcmp(current, section) != 0) {
			continue;
		}
		*eq = '\0';
		if (strcmp(g_strstrip(s), key) == 0) {
			g_free(result);
			result = g_strdup(g_strstrip(eq + 1));
		}
	}
	g_strfreev(lines);
	g_free(text);
	return result;
}

static void load_theme(struct c8ui_app *app) {
	char *start = g_build_filename(app->config_dir, "start.ini", NULL);
	char *config = g_build_filename(app->config_dir, "config.ini", NULL);
	/* [appearance] lives in config.ini; start.ini had it before */
	char *accent = ini_get(config, "appearance", "accent");
	char *background = ini_get(config, "appearance", "background");
	if (accent == NULL) {
		accent = ini_get(start, "appearance", "accent");
	}
	if (background == NULL) {
		background = ini_get(start, "appearance", "background");
	}
	char *font = ini_get(config, "general", "font");
	app->theme.accent = C8UI_DEFAULT_ACCENT;
	app->theme.background = C8UI_DEFAULT_BACKGROUND;
	c8ui_parse_color(accent, &app->theme.accent);
	c8ui_parse_color(background, &app->theme.background);
	free(app->theme.font);
	app->theme.font = strdup(font && font[0] ? font : C8UI_DEFAULT_FONT);
	g_free(accent);
	g_free(background);
	g_free(font);
	g_free(start);
	g_free(config);
}

static void theme_changed(GFileMonitor *monitor, GFile *file, GFile *other,
		GFileMonitorEvent event, gpointer data) {
	struct c8ui_app *app = data;
	if (event != G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT &&
			event != G_FILE_MONITOR_EVENT_CREATED &&
			event != G_FILE_MONITOR_EVENT_RENAMED &&
			event != G_FILE_MONITOR_EVENT_MOVED_IN) {
		return;
	}
	uint32_t accent = app->theme.accent, background = app->theme.background;
	char *font = strdup(app->theme.font);
	load_theme(app);
	bool same = accent == app->theme.accent &&
		background == app->theme.background && strcmp(font, app->theme.font) == 0;
	free(font);
	if (same) {
		return;
	}
	struct c8ui_window *win;
	wl_list_for_each(win, &app->windows, link) {
		c8ui_root_set_theme(win->root, &app->theme);
	}
}

static void watch_theme(struct c8ui_app *app) {
	/* Files are replaced by rename, so watch the directory */
	GFile *dir = g_file_new_for_path(app->config_dir);
	app->monitors[0] = g_file_monitor_directory(dir, G_FILE_MONITOR_WATCH_MOVES,
		NULL, NULL);
	if (app->monitors[0]) {
		g_signal_connect(app->monitors[0], "changed", G_CALLBACK(theme_changed),
			app);
	}
	g_object_unref(dir);
}

const struct c8ui_theme *c8ui_app_theme(struct c8ui_app *app) {
	return &app->theme;
}

/* Timers */

static gboolean timer_fire(gpointer data) {
	struct timer *t = data;
	int next = t->fn(t->data);
	if (next <= 0) {
		free(t);
		return G_SOURCE_REMOVE;
	}
	if (next == t->interval) {
		return G_SOURCE_CONTINUE;
	}
	t->interval = next;
	t->id = g_timeout_add(next, timer_fire, t);
	return G_SOURCE_REMOVE;
}

static void *host_timer_add(void *host, int ms, c8ui_timer_fn fn, void *data) {
	struct c8ui_window *win = host;
	struct timer *t = calloc(1, sizeof(*t));
	t->app = win->app;
	t->interval = ms;
	t->fn = fn;
	t->data = data;
	t->id = g_timeout_add(ms, timer_fire, t);
	return t;
}

static void host_timer_remove(void *host, void *timer) {
	struct timer *t = timer;
	g_source_remove(t->id);
	free(t);
}

/* Buffers */

static void buffer_finish(struct buffer *buf);

static void buffer_release(void *data, struct wl_buffer *wl_buffer) {
	struct buffer *buf = data;
	buf->busy = false;
	if (buf->drop) {
		buffer_finish(buf);
	}
}

static const struct wl_buffer_listener buffer_listener = {
	.release = buffer_release,
};

static void buffer_finish(struct buffer *buf) {
	if (buf->wl_buffer) {
		wl_buffer_destroy(buf->wl_buffer);
	}
	if (buf->data) {
		munmap(buf->data, buf->len);
	}
	if (buf->stale) {
		cairo_region_destroy(buf->stale);
	}
	*buf = (struct buffer){ 0 };
}

/* A shared-memory ARGB buffer and where its pixels are mapped (the
 * caller's to munmap, *len bytes); NULL when there's no memory for it */
static struct wl_buffer *shm_buffer(struct wl_shm *shm, int width, int height,
		void **pixels, size_t *len) {
	int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width);
	*len = (size_t)stride * height;
	int fd = memfd_create("c8ui", MFD_CLOEXEC);
	if (fd < 0 || ftruncate(fd, *len) < 0) {
		if (fd >= 0) {
			close(fd);
		}
		return NULL;
	}
	*pixels = mmap(NULL, *len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (*pixels == MAP_FAILED) {
		close(fd);
		return NULL;
	}
	struct wl_shm_pool *pool = wl_shm_create_pool(shm, fd, *len);
	struct wl_buffer *buffer = wl_shm_pool_create_buffer(pool, 0, width,
		height, stride, WL_SHM_FORMAT_ARGB8888);
	wl_shm_pool_destroy(pool);
	close(fd);
	return buffer;
}

/* A window nobody sees needn't keep its pixels: a full screen's two
 * buffers are 16 MB. The one the compositor holds goes when it's let go. */
static void drop_buffers(struct c8ui_window *win) {
	for (int i = 0; i < 2; i++) {
		struct buffer *buf = &win->buffers[i];
		if (buf->wl_buffer == NULL) {
			continue;
		}
		if (buf->busy) {
			buf->drop = true;
		} else {
			buffer_finish(buf);
		}
	}
}

static struct buffer *get_buffer(struct c8ui_window *win, int width, int height) {
	for (int i = 0; i < 2; i++) {
		win->buffers[i].drop = false; // drawing again: both are wanted
	}
	for (int i = 0; i < 2; i++) {
		struct buffer *buf = &win->buffers[i];
		if (buf->busy) {
			continue;
		}
		if (buf->wl_buffer && (buf->width != width || buf->height != height)) {
			buffer_finish(buf);
		}
		if (buf->wl_buffer) {
			return buf;
		}
		void *data;
		size_t len;
		buf->wl_buffer = shm_buffer(win->app->shm, width, height, &data,
			&len);
		if (buf->wl_buffer == NULL) {
			return NULL;
		}
		wl_buffer_add_listener(buf->wl_buffer, &buffer_listener, buf);
		buf->data = data;
		buf->len = len;
		buf->width = width;
		buf->height = height;
		buf->blank = true;
		return buf;
	}
	return NULL;
}

/* Drawing */

static void schedule(struct c8ui_window *win);

static void frame_done(void *data, struct wl_callback *cb, uint32_t time) {
	struct c8ui_window *win = data;
	wl_callback_destroy(cb);
	win->frame_cb = NULL;
	win->frame_pending = false;
	if (win->dirty || win->animating) {
		schedule(win);
	}
}

static const struct wl_callback_listener frame_listener = {
	.done = frame_done,
};

/* A window that hasn't drawn for a while lets its buffers go: most
 * windows sit still most of the time, each holding two copies of all its
 * pixels (16 MB full screen) that take a couple of ms to have again. The
 * compositor keeps what it shows. */
#define REST_S 5

static gboolean rest(gpointer data) {
	struct c8ui_window *win = data;
	int64_t quiet = g_get_monotonic_time() - win->drawn_at;
	if (win->frame_pending || win->dirty || win->animating ||
			quiet < (REST_S - 1) * G_USEC_PER_SEC) {
		/* Still at it, or waiting to be shown a frame: look again */
		if (win->frame_pending && quiet > 2 * REST_S * G_USEC_PER_SEC) {
			drop_buffers(win); // hidden: no frame is coming
			win->rest = 0;
			return G_SOURCE_REMOVE;
		}
		return G_SOURCE_CONTINUE;
	}
	drop_buffers(win);
	win->rest = 0;
	return G_SOURCE_REMOVE;
}

/* Damage. A frame draws only what changed: the root says what, in
 * logical pixels (c8ui_root_take_damage), and it is drawn clipped to
 * that. The two buffers take turns, so the one a frame gets missed what
 * went into the other meanwhile: each keeps what it has yet to catch up
 * on (stale), drawn again with the frame's own. A new buffer, another
 * size or scale, or anything the window itself changes draws it all.
 * C8UI_FULL_REDRAW=1 always does, to compare against;
 * C8UI_FRAME_LOG=1 says on stderr what each frame drew and how long it
 * took. */

/* More than this much of the window: all of it is as quick */
#define DAMAGE_FULL_SHARE 0.7

static bool env_on(const char *name) {
	const char *v = g_getenv(name);
	return v && v[0] && strcmp(v, "0") != 0;
}

/* The root's logical rects as buffer pixels, rounded outwards (a pixel
 * a rect only touches is drawn again whole) */
static cairo_region_t *to_pixels(cairo_region_t *logical, double scale, int pw,
		int ph) {
	cairo_region_t *px = cairo_region_create();
	int n = cairo_region_num_rectangles(logical);
	for (int i = 0; i < n; i++) {
		cairo_rectangle_int_t r;
		cairo_region_get_rectangle(logical, i, &r);
		int x1 = (int)floor(r.x * scale), y1 = (int)floor(r.y * scale);
		int x2 = (int)ceil((r.x + r.width) * scale);
		int y2 = (int)ceil((r.y + r.height) * scale);
		x1 = x1 < 0 ? 0 : x1;
		y1 = y1 < 0 ? 0 : y1;
		x2 = x2 > pw ? pw : x2;
		y2 = y2 > ph ? ph : y2;
		if (x2 > x1 && y2 > y1) {
			cairo_rectangle_int_t p = { x1, y1, x2 - x1, y2 - y1 };
			cairo_region_union_rectangle(px, &p);
		}
	}
	return px;
}

static double region_area(cairo_region_t *region) {
	double area = 0;
	int n = cairo_region_num_rectangles(region);
	for (int i = 0; i < n; i++) {
		cairo_rectangle_int_t r;
		cairo_region_get_rectangle(region, i, &r);
		area += (double)r.width * r.height;
	}
	return area;
}

static void render(struct c8ui_window *win) {
	if (!win->configured || win->frame_pending || win->suspended) {
		return;
	}
	if (win->animating) {
		win->animating = c8ui_root_tick(win->root, c8ui_now_ms());
	}
	if (!win->dirty) {
		return;
	}
	static int full_redraw = -1, frame_log;
	if (full_redraw < 0) {
		full_redraw = env_on("C8UI_FULL_REDRAW");
		frame_log = env_on("C8UI_FRAME_LOG");
	}
	bool fractional = win->viewport != NULL;
	double scale = win->scale > 0 ? win->scale : 1;
	int pw = (int)ceil(win->width * scale);
	int ph = (int)ceil(win->height * scale);
	struct buffer *buf = get_buffer(win, pw, ph);
	if (buf == NULL) {
		return; /* both busy: drawn at the next frame */
	}
	win->dirty = false;
	int64_t started = frame_log ? g_get_monotonic_time() : 0;

	/* What changed since the last frame (NULL: everything)... */
	cairo_region_t *logical = c8ui_root_take_damage(win->root);
	cairo_region_t *changed = NULL;
	if (logical && !win->damage_all && !full_redraw) {
		changed = to_pixels(logical, scale, pw, ph);
	}
	if (logical) {
		cairo_region_destroy(logical);
	}
	win->damage_all = false;
	/* ...which the other buffer now lacks... */
	for (int i = 0; i < 2; i++) {
		struct buffer *other = &win->buffers[i];
		if (other == buf || other->wl_buffer == NULL || other->blank) {
			continue;
		}
		if (changed == NULL) {
			other->blank = true;
			g_clear_pointer(&other->stale, cairo_region_destroy);
		} else if (other->stale) {
			cairo_region_union(other->stale, changed);
		} else {
			other->stale = cairo_region_copy(changed);
		}
	}
	/* ...and what this one has to draw: that and what it missed */
	cairo_region_t *paint = NULL;
	if (changed && !buf->blank) {
		paint = cairo_region_copy(changed);
		if (buf->stale) {
			cairo_region_union(paint, buf->stale);
		}
		if (region_area(paint) > DAMAGE_FULL_SHARE * pw * ph) {
			g_clear_pointer(&paint, cairo_region_destroy);
		}
	}
	bool was_blank = buf->blank;
	buf->blank = false;
	g_clear_pointer(&buf->stale, cairo_region_destroy);

	bool opaque = win->background_alpha >= 1;
	if (paint == NULL || !cairo_region_is_empty(paint)) {
		cairo_surface_t *surface = cairo_image_surface_create_for_data(
			buf->data, CAIRO_FORMAT_ARGB32, pw, ph,
			cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, pw));
		cairo_t *cr = cairo_create(surface);
		if (paint) {
			int n = cairo_region_num_rectangles(paint);
			for (int i = 0; i < n; i++) {
				cairo_rectangle_int_t r;
				cairo_region_get_rectangle(paint, i, &r);
				cairo_rectangle(cr, r.x, r.y, r.width, r.height);
			}
			cairo_clip(cr);
		}
		/* SOURCE, so a see-through window's old pixels are cleared,
		 * not painted over */
		cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
		c8ui_set_source(cr, win->background, win->background_alpha);
		cairo_paint(cr);
		cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
		cairo_scale(cr, scale, scale);
		c8ui_root_draw(win->root, cr);
		cairo_destroy(cr);
		cairo_surface_flush(surface);
		cairo_surface_destroy(surface);
	}

	if (fractional) {
		wl_surface_set_buffer_scale(win->surface, 1);
		wp_viewport_set_destination(win->viewport, win->width, win->height);
	} else {
		wl_surface_set_buffer_scale(win->surface, (int)scale);
	}
	if (win->opaque || opaque) {
		struct wl_region *region =
			wl_compositor_create_region(win->app->compositor);
		if (opaque) {
			wl_region_add(region, 0, 0, win->width, win->height);
		} else {
			int n = cairo_region_num_rectangles(win->opaque);
			for (int i = 0; i < n; i++) {
				cairo_rectangle_int_t r;
				cairo_region_get_rectangle(win->opaque, i, &r);
				wl_region_add(region, r.x, r.y, r.width, r.height);
			}
		}
		wl_surface_set_opaque_region(win->surface, region);
		wl_region_destroy(region);
	} else {
		wl_surface_set_opaque_region(win->surface, NULL);
	}
	wl_surface_attach(win->surface, buf->wl_buffer, 0, 0);
	/* The compositor is told what differs from the frame before: only
	 * what changed, however much more this buffer had to catch up on.
	 * A buffer made anew says all of it, to be safe. */
	if (changed == NULL || was_blank) {
		wl_surface_damage_buffer(win->surface, 0, 0, pw, ph);
	} else {
		int n = cairo_region_num_rectangles(changed);
		for (int i = 0; i < n; i++) {
			cairo_rectangle_int_t r;
			cairo_region_get_rectangle(changed, i, &r);
			wl_surface_damage_buffer(win->surface, r.x, r.y, r.width,
				r.height);
		}
	}
	if (frame_log) {
		double share = paint ? region_area(paint) / ((double)pw * ph) : 1;
		fprintf(stderr, "c8ui frame %s %dx%d drew %.1f%% in %d rects, "
			"%.2f ms\n", win->app->app_id ? win->app->app_id : "?", pw, ph,
			share * 100, paint ? cairo_region_num_rectangles(paint) : 1,
			(g_get_monotonic_time() - started) / 1000.0);
	}
	if (paint) {
		cairo_region_destroy(paint);
	}
	if (changed) {
		cairo_region_destroy(changed);
	}
	struct wl_callback *cb = wl_surface_frame(win->surface);
	wl_callback_add_listener(cb, &frame_listener, win);
	win->frame_cb = cb;
	win->frame_pending = true;
	wl_surface_commit(win->surface);
	buf->busy = true;
	win->drawn_at = g_get_monotonic_time();
	if (win->rest == 0) {
		win->rest = g_timeout_add_seconds(REST_S, rest, win);
	}
}

static gboolean render_idle(gpointer data) {
	struct c8ui_window *win = data;
	win->idle = 0;
	render(win);
	return G_SOURCE_REMOVE;
}

static void schedule(struct c8ui_window *win) {
	if (win->idle == 0 && !win->frame_pending) {
		win->idle = g_idle_add(render_idle, win);
	}
}

static void host_queue_redraw(void *host) {
	struct c8ui_window *win = host;
	win->dirty = true;
	schedule(win);
}

/* Something of the window's own changed (its scale, its background):
 * all of it is drawn again */
static void redraw_all(struct c8ui_window *win) {
	win->damage_all = true;
	host_queue_redraw(win);
}

static void host_request_frame(void *host) {
	struct c8ui_window *win = host;
	win->animating = true;
	schedule(win);
}

static void apply_cursor(struct c8ui_app *app) {
	if (app->pointer_window == NULL) {
		return;
	}
	if (app->cursor == C8UI_CURSOR_NONE) {
		if (app->pointer) {
			wl_pointer_set_cursor(app->pointer, app->enter_serial, NULL,
				0, 0);
		}
		return;
	}
	if (app->cursor_shape == NULL) {
		return;
	}
	static const uint32_t shapes[] = {
		[C8UI_CURSOR_DEFAULT] = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT,
		[C8UI_CURSOR_POINTER] = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_POINTER,
		[C8UI_CURSOR_TEXT] = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_TEXT,
		[C8UI_CURSOR_MOVE] = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_MOVE,
		[C8UI_CURSOR_RESIZE_H] = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_COL_RESIZE,
		[C8UI_CURSOR_RESIZE_V] = WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ROW_RESIZE,
	};
	wp_cursor_shape_device_v1_set_shape(app->cursor_shape, app->enter_serial,
		shapes[app->cursor]);
}

static void host_set_cursor(void *host, enum c8ui_cursor cursor) {
	struct c8ui_window *win = host;
	win->app->cursor = cursor;
	if (win->app->pointer_window == win) {
		apply_cursor(win->app);
	}
}

static void host_inhibit_shortcuts(void *host, bool inhibit) {
	struct c8ui_window *win = host;
	struct c8ui_app *app = win->app;
	if (inhibit && win->inhibitor == NULL && app->inhibit_manager && app->seat) {
		win->inhibitor = zwp_keyboard_shortcuts_inhibit_manager_v1_inhibit_shortcuts(
			app->inhibit_manager, win->surface, app->seat);
	} else if (!inhibit && win->inhibitor) {
		zwp_keyboard_shortcuts_inhibitor_v1_destroy(win->inhibitor);
		win->inhibitor = NULL;
	}
}


/* Clipboard: ours offers each item's type (text in its usual names);
 * another app's offer is read by type, synchronously */

static const char *const text_types[] = {
	"text/plain;charset=utf-8", "text/plain", "UTF8_STRING", "TEXT", "STRING",
};

struct clip_item {
	char *mime;
	GBytes *bytes;
};

static bool offer_has(struct wl_data_offer *offer, const char *mime);
static struct c8ui_window *window_for(struct c8ui_app *app,
	struct wl_surface *surface);
static void drag_end(struct c8ui_app *app, uint32_t action);

static void clip_item_free(gpointer data) {
	struct clip_item *c = data;
	g_free(c->mime);
	g_bytes_unref(c->bytes);
	free(c);
}

static bool is_text_type(const char *mime) {
	for (size_t i = 0; i < G_N_ELEMENTS(text_types); i++) {
		if (strcmp(mime, text_types[i]) == 0) {
			return true;
		}
	}
	return false;
}

/* Our item for a type asked for: text for any of text's names */
static struct clip_item *find_item(GPtrArray *items, const char *mime) {
	if (items == NULL) {
		return NULL;
	}
	bool text = is_text_type(mime);
	for (guint i = 0; i < items->len; i++) {
		struct clip_item *c = items->pdata[i];
		if (strcmp(c->mime, mime) == 0 ||
				(text && strcmp(c->mime, "text/plain") == 0)) {
			return c;
		}
	}
	return NULL;
}

static struct clip_item *own_item(struct c8ui_app *app, const char *mime) {
	return find_item(app->source_items, mime);
}

/* Copies items and offers each on source */
static GPtrArray *take_items(struct wl_data_source *source,
		const struct c8ui_clip_item *items, int count) {
	GPtrArray *own = g_ptr_array_new_with_free_func(clip_item_free);
	for (int i = 0; i < count; i++) {
		struct clip_item *c = calloc(1, sizeof(*c));
		c->mime = g_strdup(items[i].mime);
		c->bytes = g_bytes_new(items[i].data, items[i].len);
		g_ptr_array_add(own, c);
		if (strcmp(c->mime, "text/plain") == 0) {
			for (size_t t = 0; t < G_N_ELEMENTS(text_types); t++) {
				wl_data_source_offer(source, text_types[t]);
			}
		} else {
			wl_data_source_offer(source, c->mime);
		}
	}
	return own;
}

/* Written as the pipe takes it, so an app that stops reading can't
 * hang ours */
struct clip_write {
	int fd;
	GBytes *bytes;
	size_t done;
};

static gboolean clip_write_ready(gint fd, GIOCondition cond, gpointer data) {
	struct clip_write *w = data;
	gsize len;
	const char *bytes = g_bytes_get_data(w->bytes, &len);
	if (!(cond & (G_IO_ERR | G_IO_HUP))) {
		ssize_t n = write(fd, bytes + w->done, len - w->done);
		if (n > 0) {
			w->done += n;
		}
		if ((n > 0 || errno == EAGAIN || errno == EINTR) && w->done < len) {
			return G_SOURCE_CONTINUE;
		}
	}
	close(fd);
	g_bytes_unref(w->bytes);
	free(w);
	return G_SOURCE_REMOVE;
}

/* Sends c (or nothing, if NULL) down fd, then closes it */
static void send_item(struct clip_item *c, int fd) {
	if (c == NULL || g_bytes_get_size(c->bytes) == 0) {
		close(fd);
		return;
	}
	struct clip_write *w = calloc(1, sizeof(*w));
	w->fd = fd;
	w->bytes = g_bytes_ref(c->bytes);
	fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
	g_unix_fd_add(fd, G_IO_OUT | G_IO_ERR | G_IO_HUP, clip_write_ready, w);
}

static void source_send(void *data, struct wl_data_source *source,
		const char *mime, int32_t fd) {
	struct c8ui_app *app = data;
	send_item(app->source == source ? own_item(app, mime) : NULL, fd);
}

static void notify_clipboard(struct c8ui_app *app) {
	if (app->clip_fn) {
		app->clip_fn(app, app->clip_data);
	}
}

static void source_cancelled(void *data, struct wl_data_source *source) {
	struct c8ui_app *app = data;
	if (app->source == source) {
		app->source = NULL;
		g_clear_pointer(&app->source_items, g_ptr_array_unref);
	}
	wl_data_source_destroy(source);
}

static void source_target(void *data, struct wl_data_source *source,
		const char *mime) {
}

static const struct wl_data_source_listener source_listener = {
	.target = source_target,
	.send = source_send,
	.cancelled = source_cancelled,
};

void c8ui_window_set_clipboard(struct c8ui_window *win,
		const struct c8ui_clip_item *items, int count) {
	struct c8ui_app *app = win->app;
	if (app->data_device == NULL) {
		return;
	}
	if (count == 0) {
		if (app->source) {
			wl_data_device_set_selection(app->data_device, NULL,
				app->last_serial);
			wl_data_source_destroy(app->source);
			app->source = NULL;
			g_clear_pointer(&app->source_items, g_ptr_array_unref);
			notify_clipboard(app);
		}
		return;
	}
	struct wl_data_source *source =
		wl_data_device_manager_create_data_source(app->data_manager);
	GPtrArray *own = take_items(source, items, count);
	wl_data_source_add_listener(source, &source_listener, app);
	wl_data_device_set_selection(app->data_device, source, app->last_serial);
	if (app->source) {
		wl_data_source_destroy(app->source);
	}
	app->source = source;
	if (app->source_items) {
		g_ptr_array_unref(app->source_items);
	}
	app->source_items = own;
	notify_clipboard(app);
}

void c8ui_window_set_clipboard_files(struct c8ui_window *win, char **uris,
		bool cut, const struct c8ui_clip_item *extra, int n_extra) {
	GString *gnome = g_string_new(cut ? "cut" : "copy");
	GString *list = g_string_new(NULL);
	GString *paths = g_string_new(NULL);
	for (int i = 0; uris[i]; i++) {
		g_string_append_printf(gnome, "\n%s", uris[i]);
		g_string_append_printf(list, "%s\r\n", uris[i]);
		char *path = g_filename_from_uri(uris[i], NULL, NULL);
		g_string_append_printf(paths, "%s%s", i ? "\n" : "",
			path ? path : uris[i]);
		g_free(path);
	}
	int n = 0;
	struct c8ui_clip_item *items = g_new(struct c8ui_clip_item, n_extra + 4);
	for (int i = 0; i < n_extra; i++) {
		items[n++] = extra[i];
	}
	items[n++] = (struct c8ui_clip_item){ "x-special/gnome-copied-files",
		gnome->str, gnome->len };
	items[n++] = (struct c8ui_clip_item){ "text/uri-list", list->str,
		list->len };
	items[n++] = (struct c8ui_clip_item){ "application/x-kde-cutselection",
		cut ? "1" : "0", 1 };
	items[n++] = (struct c8ui_clip_item){ "text/plain", paths->str,
		paths->len };
	c8ui_window_set_clipboard(win, items, n);
	g_free(items);
	g_string_free(gnome, TRUE);
	g_string_free(list, TRUE);
	g_string_free(paths, TRUE);
}

static void host_set_clipboard(void *host, const char *text) {
	struct c8ui_clip_item item = { "text/plain", text, strlen(text) };
	c8ui_window_set_clipboard(host, &item, 1);
}

bool c8ui_app_clipboard_offers(struct c8ui_app *app, const char *mime) {
	if (app->source) {
		return own_item(app, mime) != NULL;
	}
	return offer_has(app->selection, mime);
}

bool c8ui_app_clipboard_owned(struct c8ui_app *app) {
	return app->source != NULL;
}

void c8ui_app_on_clipboard(struct c8ui_app *app, c8ui_app_fn fn, void *data) {
	app->clip_fn = fn;
	app->clip_data = data;
}

/* Reads mime from the offer now, so whoever asked is surely still there;
 * gives up on a source that stalls */
static GBytes *receive(struct c8ui_app *app, struct wl_data_offer *offer,
		const char *mime) {
	int fds[2];
	if (pipe2(fds, O_CLOEXEC) != 0) {
		return NULL;
	}
	wl_data_offer_receive(offer, mime, fds[1]);
	close(fds[1]);
	wl_display_flush(app->display);
	GByteArray *buf = g_byte_array_new();
	struct pollfd pfd = { .fd = fds[0], .events = POLLIN };
	guint8 chunk[4096];
	while (poll(&pfd, 1, 1000) > 0) {
		ssize_t n = read(fds[0], chunk, sizeof(chunk));
		if (n <= 0) {
			break;
		}
		g_byte_array_append(buf, chunk, n);
		if (buf->len > 16 << 20) {
			break;
		}
	}
	close(fds[0]);
	return g_byte_array_free_to_bytes(buf);
}

/* Hands got to fn, NUL-terminated as well (for text), and drops it */
static void give(const char *mime, GBytes *got, c8ui_clip_fn fn, void *data) {
	gsize len;
	const char *bytes = g_bytes_get_data(got, &len);
	char *copy = g_malloc(len + 1);
	memcpy(copy, bytes, len);
	copy[len] = '\0';
	fn(mime, copy, len, data);
	g_free(copy);
	g_bytes_unref(got);
}

void c8ui_window_paste(struct c8ui_window *win, const char *const *mimes,
		int count, c8ui_clip_fn fn, void *data) {
	struct c8ui_app *app = win->app;
	for (int i = 0; i < count; i++) {
		if (!c8ui_app_clipboard_offers(app, mimes[i])) {
			continue;
		}
		/* Our own copy: the compositor would ask us, and we'd be waiting
		 * on ourselves */
		GBytes *got = app->source ?
			g_bytes_ref(own_item(app, mimes[i])->bytes) :
			receive(app, app->selection, mimes[i]);
		if (got) {
			give(mimes[i], got, fn, data);
			return;
		}
	}
	fn(NULL, NULL, 0, data);
}

struct text_paste {
	c8ui_paste_fn fn;
	void *data;
};

static void text_pasted(const char *mime, const char *bytes, size_t len,
		void *data) {
	struct text_paste *t = data;
	if (mime && g_utf8_validate(bytes, len, NULL)) {
		char *text = g_strndup(bytes, len);
		t->fn(t->data, text);
		g_free(text);
	}
}

static void host_request_paste(void *host, c8ui_paste_fn fn, void *data) {
	struct text_paste t = { fn, data };
	c8ui_window_paste(host, text_types, G_N_ELEMENTS(text_types), text_pasted,
		&t);
}

/* What an offer (the selection's, or a drag's) has */
struct offer_info {
	GPtrArray *types; // char *
	uint32_t source_actions, action; // drags: allowed, and chosen
};

static void offer_offer(void *data, struct wl_data_offer *offer,
		const char *mime) {
	struct offer_info *info = wl_data_offer_get_user_data(offer);
	g_ptr_array_add(info->types, g_strdup(mime));
}

static void offer_source_actions(void *data, struct wl_data_offer *offer,
		uint32_t actions) {
	struct offer_info *info = wl_data_offer_get_user_data(offer);
	info->source_actions = actions;
}

static void offer_action(void *data, struct wl_data_offer *offer,
		uint32_t action) {
	struct offer_info *info = wl_data_offer_get_user_data(offer);
	info->action = action;
}

static const struct wl_data_offer_listener offer_listener = {
	.offer = offer_offer,
	.source_actions = offer_source_actions,
	.action = offer_action,
};

static struct offer_info *offer_info(struct wl_data_offer *offer) {
	return offer ? wl_data_offer_get_user_data(offer) : NULL;
}

static void offer_destroy(struct wl_data_offer *offer) {
	struct offer_info *info = offer_info(offer);
	g_ptr_array_unref(info->types);
	free(info);
	wl_data_offer_destroy(offer);
}

static bool offer_has(struct wl_data_offer *offer, const char *mime) {
	struct offer_info *info = offer_info(offer);
	for (guint i = 0; info && i < info->types->len; i++) {
		if (strcmp(info->types->pdata[i], mime) == 0) {
			return true;
		}
	}
	return false;
}

static void device_data_offer(void *data, struct wl_data_device *device,
		struct wl_data_offer *offer) {
	struct offer_info *info = calloc(1, sizeof(*info));
	info->types = g_ptr_array_new_with_free_func(g_free);
	wl_data_offer_add_listener(offer, &offer_listener, info);
}

static void device_selection(void *data, struct wl_data_device *device,
		struct wl_data_offer *offer) {
	struct c8ui_app *app = data;
	if (app->selection) {
		offer_destroy(app->selection);
	}
	app->selection = offer;
	notify_clipboard(app);
}

/* Drops: the window under a drag says what it would do there */

static void dnd_forget(struct c8ui_app *app) {
	struct c8ui_window *win = app->dnd.window;
	app->dnd.window = NULL;
	if (win && win->drop && win->drop->leave) {
		win->drop->leave(win, win->drop_data);
	}
	if (app->dnd.offer) {
		offer_destroy(app->dnd.offer);
		app->dnd.offer = NULL;
	}
}

static void dnd_update(struct c8ui_app *app) {
	struct c8ui_window *win = app->dnd.window;
	struct wl_data_offer *offer = app->dnd.offer;
	if (offer == NULL) {
		return;
	}
	struct offer_info *info = offer_info(offer);
	uint32_t allowed = info->source_actions;
	if (wl_data_offer_get_version(offer) < 3) {
		allowed = WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY;
	}
	uint32_t action = 0;
	if (win && win->drop && info->types->len > 0) {
		action = win->drop->motion(win, app->dnd.x, app->dnd.y, allowed,
			win->drop_data) & allowed;
	}
	wl_data_offer_accept(offer, app->dnd.serial,
		action ? info->types->pdata[0] : NULL);
	if (wl_data_offer_get_version(offer) >= 3) {
		wl_data_offer_set_actions(offer, action, action);
	}
}

static void device_enter(void *data, struct wl_data_device *device,
		uint32_t serial, struct wl_surface *surface, wl_fixed_t x, wl_fixed_t y,
		struct wl_data_offer *offer) {
	struct c8ui_app *app = data;
	dnd_forget(app);
	app->dnd.offer = offer;
	app->dnd.window = window_for(app, surface);
	app->dnd.serial = serial;
	app->dnd.x = wl_fixed_to_double(x);
	app->dnd.y = wl_fixed_to_double(y);
	dnd_update(app);
}

static void device_leave(void *data, struct wl_data_device *device) {
	dnd_forget(data);
}

static void device_motion(void *data, struct wl_data_device *device,
		uint32_t time, wl_fixed_t x, wl_fixed_t y) {
	struct c8ui_app *app = data;
	app->dnd.x = wl_fixed_to_double(x);
	app->dnd.y = wl_fixed_to_double(y);
	dnd_update(app);
}

static void device_drop(void *data, struct wl_data_device *device) {
	struct c8ui_app *app = data;
	struct c8ui_window *win = app->dnd.window;
	struct wl_data_offer *offer = app->dnd.offer;
	if (offer == NULL) {
		return;
	}
	struct offer_info *info = offer_info(offer);
	uint32_t action = wl_data_offer_get_version(offer) >= 3 ? info->action :
		WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY;
	if (win && win->drop && action) {
		win->drop->drop(win, app->dnd.x, app->dnd.y, action, win->drop_data);
		if (wl_data_offer_get_version(offer) >= 3) {
			wl_data_offer_finish(offer);
		}
	}
	/* A leave may follow; this drag is over either way */
	dnd_forget(app);
}

void c8ui_window_set_drop(struct c8ui_window *win,
		const struct c8ui_drop_impl *impl, void *data) {
	win->drop = impl;
	win->drop_data = data;
}

bool c8ui_drop_offers(struct c8ui_window *win, const char *mime) {
	return offer_has(win->app->dnd.offer, mime);
}

void c8ui_drop_read(struct c8ui_window *win, const char *const *mimes,
		int count, c8ui_clip_fn fn, void *data) {
	struct c8ui_app *app = win->app;
	for (int i = 0; app->dnd.offer && i < count; i++) {
		if (!offer_has(app->dnd.offer, mimes[i])) {
			continue;
		}
		/* Our own drag: the compositor would ask us to send it, and we'd
		 * be waiting on ourselves */
		struct clip_item *own = app->drag.source ?
			find_item(app->drag.items, mimes[i]) : NULL;
		GBytes *got = own ? g_bytes_ref(own->bytes) :
			receive(app, app->dnd.offer, mimes[i]);
		if (got) {
			give(mimes[i], got, fn, data);
			return;
		}
	}
	fn(NULL, NULL, 0, data);
}

/* Dragging: ours, from a press in one of our windows */

static void drag_end(struct c8ui_app *app, uint32_t action) {
	if (app->drag.source == NULL) {
		return;
	}
	wl_data_source_destroy(app->drag.source);
	app->drag.source = NULL;
	if (app->drag.icon) {
		wl_surface_destroy(app->drag.icon);
		app->drag.icon = NULL;
	}
	g_clear_pointer(&app->drag.items, g_ptr_array_unref);
	if (app->drag.done) {
		app->drag.done(action, app->drag.data);
	}
}

static void drag_send(void *data, struct wl_data_source *source,
		const char *mime, int32_t fd) {
	struct c8ui_app *app = data;
	struct clip_item *c = app->drag.source == source ?
		find_item(app->drag.items, mime) : NULL;
	send_item(c, fd);
}

static void drag_target(void *data, struct wl_data_source *source,
		const char *mime) {
}

static void drag_cancelled(void *data, struct wl_data_source *source) {
	drag_end(data, 0);
}

static void drag_dropped(void *data, struct wl_data_source *source) {
	/* Waits for dnd_finished (or cancelled, if the target gives up) */
}

static void drag_finished(void *data, struct wl_data_source *source) {
	struct c8ui_app *app = data;
	drag_end(app, app->drag.action);
}

static void drag_action(void *data, struct wl_data_source *source,
		uint32_t action) {
	struct c8ui_app *app = data;
	app->drag.action = action;
}

static const struct wl_data_source_listener drag_listener = {
	.target = drag_target,
	.send = drag_send,
	.cancelled = drag_cancelled,
	.dnd_drop_performed = drag_dropped,
	.dnd_finished = drag_finished,
	.action = drag_action,
};

static void icon_buffer_release(void *data, struct wl_buffer *buffer) {
	wl_buffer_destroy(buffer);
}

static const struct wl_buffer_listener icon_buffer_listener = {
	.release = icon_buffer_release,
};

/* The picture under the pointer while dragging */
static struct wl_surface *drag_icon(struct c8ui_window *win,
		const struct c8ui_drag_options *o) {
	struct c8ui_app *app = win->app;
	if (o->draw_icon == NULL || o->icon_width <= 0 || o->icon_height <= 0) {
		return NULL;
	}
	int scale = (int)ceil(win->scale > 0 ? win->scale : 1);
	int w = o->icon_width * scale, h = o->icon_height * scale;
	void *pixels;
	size_t len;
	struct wl_buffer *buffer = shm_buffer(app->shm, w, h, &pixels, &len);
	if (buffer == NULL) {
		return NULL;
	}
	cairo_surface_t *cs = cairo_image_surface_create_for_data(pixels,
		CAIRO_FORMAT_ARGB32, w, h,
		cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, w));
	cairo_t *cr = cairo_create(cs);
	cairo_scale(cr, scale, scale);
	o->draw_icon(cr, o->data);
	cairo_destroy(cr);
	cairo_surface_flush(cs);
	cairo_surface_destroy(cs);
	munmap(pixels, len);
	wl_buffer_add_listener(buffer, &icon_buffer_listener, NULL);
	struct wl_surface *icon = wl_compositor_create_surface(app->compositor);
	wl_surface_set_buffer_scale(icon, scale);
	wl_surface_attach(icon, buffer, 0, 0);
	wl_surface_damage_buffer(icon, 0, 0, w, h);
	return icon;
}

bool c8ui_window_start_drag(struct c8ui_window *win,
		const struct c8ui_drag_options *o) {
	struct c8ui_app *app = win->app;
	if (app->data_device == NULL || o->count == 0 || app->press_serial == 0) {
		return false;
	}
	drag_end(app, 0); // one at a time
	struct wl_data_source *source =
		wl_data_device_manager_create_data_source(app->data_manager);
	app->drag.items = take_items(source, o->items, o->count);
	if (wl_data_source_get_version(source) >= 3) {
		wl_data_source_set_actions(source, o->actions ? o->actions :
			WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY);
	}
	wl_data_source_add_listener(source, &drag_listener, app);
	app->drag.source = source;
	app->drag.action = 0;
	app->drag.done = o->done;
	app->drag.data = o->data;
	app->drag.icon = drag_icon(win, o);
	wl_data_device_start_drag(app->data_device, source, win->surface,
		app->drag.icon, app->press_serial);
	if (app->drag.icon) {
		/* Its top left starts at the pointer: put the hot spot there */
		if (wl_surface_get_version(app->drag.icon) >= 5) {
			wl_surface_offset(app->drag.icon, -o->hot_x, -o->hot_y);
		}
		wl_surface_commit(app->drag.icon);
	}
	/* The press is the drag's now: no click comes of it */
	c8ui_root_cancel_press(win->root);
	return true;
}

static const struct wl_data_device_listener device_listener = {
	.data_offer = device_data_offer,
	.enter = device_enter,
	.leave = device_leave,
	.motion = device_motion,
	.drop = device_drop,
	.selection = device_selection,
};

static const struct c8ui_host_impl window_host = {
	.queue_redraw = host_queue_redraw,
	.request_frame = host_request_frame,
	.timer_add = host_timer_add,
	.timer_remove = host_timer_remove,
	.set_cursor = host_set_cursor,
	.inhibit_shortcuts = host_inhibit_shortcuts,
	.set_clipboard = host_set_clipboard,
	.request_paste = host_request_paste,
};

/* Pointer */

static struct c8ui_window *window_for(struct c8ui_app *app,
		struct wl_surface *surface) {
	struct c8ui_window *win;
	wl_list_for_each(win, &app->windows, link) {
		if (win->surface == surface) {
			return win;
		}
	}
	return NULL;
}

static void pointer_enter(void *data, struct wl_pointer *pointer,
		uint32_t serial, struct wl_surface *surface, wl_fixed_t x, wl_fixed_t y) {
	struct c8ui_app *app = data;
	app->enter_serial = serial;
	app->pointer_window = window_for(app, surface);
	if (app->pointer_window) {
		app->cursor = app->pointer_window->root->cursor;
		apply_cursor(app);
		c8ui_root_pointer_motion(app->pointer_window->root,
			wl_fixed_to_double(x), wl_fixed_to_double(y));
	}
}

static void pointer_leave(void *data, struct wl_pointer *pointer,
		uint32_t serial, struct wl_surface *surface) {
	struct c8ui_app *app = data;
	struct c8ui_window *win = app->pointer_window;
	app->pointer_window = NULL;
	if (win) {
		c8ui_root_swipe_end(win->root, true);
		c8ui_root_pinch_end(win->root, true);
		/* Left with a button down (the compositor took the pointer
		 * away): the release goes elsewhere, so the press is over. Kept,
		 * it would count every later click as a second button. */
		c8ui_root_cancel_press(win->root);
		c8ui_root_pointer_leave(win->root);
		if (win->leave_fn) {
			win->leave_fn(win, win->leave_data);
		}
	}
}

static void pointer_motion(void *data, struct wl_pointer *pointer,
		uint32_t time, wl_fixed_t x, wl_fixed_t y) {
	struct c8ui_app *app = data;
	if (app->pointer_window) {
		c8ui_root_pointer_motion(app->pointer_window->root,
			wl_fixed_to_double(x), wl_fixed_to_double(y));
	}
}

static uint32_t current_mods(struct c8ui_app *app);

static void pointer_button(void *data, struct wl_pointer *pointer,
		uint32_t serial, uint32_t time, uint32_t button, uint32_t state) {
	struct c8ui_app *app = data;
	app->last_serial = serial;
	if (state == WL_POINTER_BUTTON_STATE_PRESSED) {
		app->press_serial = serial;
	}
	if (app->pointer_window) {
		c8ui_root_set_mods(app->pointer_window->root, current_mods(app));
		c8ui_root_pointer_button(app->pointer_window->root, button,
			state == WL_POINTER_BUTTON_STATE_PRESSED);
	}
}

static void pointer_axis(void *data, struct wl_pointer *pointer, uint32_t time,
		uint32_t axis, wl_fixed_t value) {
	struct c8ui_app *app = data;
	double v = wl_fixed_to_double(value);
	if (axis == WL_POINTER_AXIS_VERTICAL_SCROLL) {
		app->axis.dy += v;
	} else {
		app->axis.dx += v;
	}
	app->axis.have = true;
}

static void pointer_axis_source(void *data, struct wl_pointer *pointer,
		uint32_t source) {
	struct c8ui_app *app = data;
	app->axis.precise = source == WL_POINTER_AXIS_SOURCE_FINGER ||
		source == WL_POINTER_AXIS_SOURCE_CONTINUOUS;
}

static void pointer_axis_stop(void *data, struct wl_pointer *pointer,
		uint32_t time, uint32_t axis) {
	struct c8ui_app *app = data;
	app->axis.stop = true;
}

static void pointer_axis_value120(void *data, struct wl_pointer *pointer,
		uint32_t axis, int32_t value120) {
	struct c8ui_app *app = data;
	if (axis == WL_POINTER_AXIS_VERTICAL_SCROLL) {
		app->axis.discrete_y += value120;
	} else {
		app->axis.discrete_x += value120;
	}
}

/* The older event for the same thing: a notch is 120 */
static void pointer_axis_discrete(void *data, struct wl_pointer *pointer,
		uint32_t axis, int32_t discrete) {
	pointer_axis_value120(data, pointer, axis, discrete * 120);
}

static void pointer_axis_relative_direction(void *data,
		struct wl_pointer *pointer, uint32_t axis, uint32_t direction) {
}

static uint32_t current_mods(struct c8ui_app *app);

static void pointer_frame(void *data, struct wl_pointer *pointer) {
	struct c8ui_app *app = data;
	if (app->axis.have && app->pointer_window) {
		double dx = app->axis.dx, dy = app->axis.dy;
		if (!app->axis.precise) {
			/* Wheels scroll a fixed distance per click */
			if (app->axis.discrete_y || app->axis.discrete_x) {
				dy = app->axis.discrete_y * WHEEL_STEP / 120.0;
				dx = app->axis.discrete_x * WHEEL_STEP / 120.0;
			} else {
				dy *= WHEEL_STEP / 15.0;
				dx *= WHEEL_STEP / 15.0;
			}
		}
		c8ui_root_pointer_scroll(app->pointer_window->root, dx, dy,
			app->axis.precise, current_mods(app));
	}
	/* Both axes stop in one frame when the fingers lift: once is enough */
	if (app->axis.stop && app->pointer_window) {
		c8ui_root_pointer_scroll_stop(app->pointer_window->root);
	}
	memset(&app->axis, 0, sizeof(app->axis));
}

/* Touchpad swipes of three or more fingers, to the window under the
 * pointer */

static void swipe_begin(void *data, struct zwp_pointer_gesture_swipe_v1 *swipe,
		uint32_t serial, uint32_t time, struct wl_surface *surface,
		uint32_t fingers) {
	struct c8ui_app *app = data;
	if (app->pointer_window) {
		c8ui_root_swipe_begin(app->pointer_window->root, (int)fingers);
	}
}

static void swipe_update(void *data, struct zwp_pointer_gesture_swipe_v1 *swipe,
		uint32_t time, wl_fixed_t dx, wl_fixed_t dy) {
	struct c8ui_app *app = data;
	if (app->pointer_window) {
		c8ui_root_swipe_update(app->pointer_window->root,
			wl_fixed_to_double(dx), wl_fixed_to_double(dy));
	}
}

static void swipe_end(void *data, struct zwp_pointer_gesture_swipe_v1 *swipe,
		uint32_t serial, uint32_t time, int32_t cancelled) {
	struct c8ui_app *app = data;
	if (app->pointer_window) {
		c8ui_root_swipe_end(app->pointer_window->root, cancelled != 0);
	}
}

static const struct zwp_pointer_gesture_swipe_v1_listener swipe_listener = {
	.begin = swipe_begin,
	.update = swipe_update,
	.end = swipe_end,
};

/* Pinches, for zooming */

static void pinch_begin(void *data, struct zwp_pointer_gesture_pinch_v1 *pinch,
		uint32_t serial, uint32_t time, struct wl_surface *surface,
		uint32_t fingers) {
	struct c8ui_app *app = data;
	if (app->pointer_window) {
		c8ui_root_pinch_begin(app->pointer_window->root, (int)fingers);
	}
}

static void pinch_update(void *data, struct zwp_pointer_gesture_pinch_v1 *pinch,
		uint32_t time, wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t scale,
		wl_fixed_t rotation) {
	struct c8ui_app *app = data;
	if (app->pointer_window) {
		c8ui_root_pinch_update(app->pointer_window->root,
			wl_fixed_to_double(dx), wl_fixed_to_double(dy),
			wl_fixed_to_double(scale));
	}
}

static void pinch_end(void *data, struct zwp_pointer_gesture_pinch_v1 *pinch,
		uint32_t serial, uint32_t time, int32_t cancelled) {
	struct c8ui_app *app = data;
	if (app->pointer_window) {
		c8ui_root_pinch_end(app->pointer_window->root, cancelled != 0);
	}
}

static const struct zwp_pointer_gesture_pinch_v1_listener pinch_listener = {
	.begin = pinch_begin,
	.update = pinch_update,
	.end = pinch_end,
};

static const struct wl_pointer_listener pointer_listener = {
	.enter = pointer_enter,
	.leave = pointer_leave,
	.motion = pointer_motion,
	.button = pointer_button,
	.axis = pointer_axis,
	.frame = pointer_frame,
	.axis_source = pointer_axis_source,
	.axis_stop = pointer_axis_stop,
	.axis_discrete = pointer_axis_discrete,
	.axis_value120 = pointer_axis_value120,
	.axis_relative_direction = pointer_axis_relative_direction,
};

/* Touch */

#define FINGERS (int)(sizeof(((struct c8ui_app *)0)->fingers) / \
	sizeof(((struct c8ui_app *)0)->fingers[0]))

static int finger_slot(struct c8ui_app *app, int32_t id) {
	for (int i = 0; i < FINGERS; i++) {
		if (app->fingers[i].window && app->fingers[i].id == id) {
			return i;
		}
	}
	return -1;
}

static void touch_down(void *data, struct wl_touch *touch, uint32_t serial,
		uint32_t time, struct wl_surface *surface, int32_t id, wl_fixed_t x,
		wl_fixed_t y) {
	struct c8ui_app *app = data;
	app->last_serial = serial;
	app->press_serial = serial;
	struct c8ui_window *win = window_for(app, surface);
	int i = 0;
	while (i < FINGERS && app->fingers[i].window) {
		i++;
	}
	if (win == NULL || i == FINGERS) {
		return;
	}
	app->fingers[i].id = id;
	app->fingers[i].window = win;
	c8ui_root_touch_down(win->root, id, time, wl_fixed_to_double(x),
		wl_fixed_to_double(y));
}

static void touch_up(void *data, struct wl_touch *touch, uint32_t serial,
		uint32_t time, int32_t id) {
	struct c8ui_app *app = data;
	app->last_serial = serial;
	int i = finger_slot(app, id);
	if (i >= 0) {
		struct c8ui_window *win = app->fingers[i].window;
		app->fingers[i].window = NULL;
		c8ui_root_touch_up(win->root, id, time);
	}
}

static void touch_motion(void *data, struct wl_touch *touch, uint32_t time,
		int32_t id, wl_fixed_t x, wl_fixed_t y) {
	struct c8ui_app *app = data;
	int i = finger_slot(app, id);
	if (i >= 0) {
		c8ui_root_touch_motion(app->fingers[i].window->root, id, time,
			wl_fixed_to_double(x), wl_fixed_to_double(y));
	}
}

static void touch_frame(void *data, struct wl_touch *touch) {
}

static void touch_cancel(void *data, struct wl_touch *touch) {
	struct c8ui_app *app = data;
	for (int i = 0; i < FINGERS; i++) {
		struct c8ui_window *win = app->fingers[i].window;
		if (win == NULL) {
			continue;
		}
		/* Once per window */
		for (int j = i; j < FINGERS; j++) {
			if (app->fingers[j].window == win) {
				app->fingers[j].window = NULL;
			}
		}
		c8ui_root_touch_cancel(win->root);
	}
}

static void touch_shape(void *data, struct wl_touch *touch, int32_t id,
		wl_fixed_t major, wl_fixed_t minor) {
}

static void touch_orientation(void *data, struct wl_touch *touch, int32_t id,
		wl_fixed_t orientation) {
}

static const struct wl_touch_listener touch_listener = {
	.down = touch_down,
	.up = touch_up,
	.motion = touch_motion,
	.frame = touch_frame,
	.cancel = touch_cancel,
	.shape = touch_shape,
	.orientation = touch_orientation,
};

/* Keyboard */

static uint32_t current_mods(struct c8ui_app *app) {
	static const struct {
		const char *name;
		uint32_t mod;
	} known[] = {
		{ XKB_MOD_NAME_SHIFT, C8UI_MOD_SHIFT },
		{ XKB_MOD_NAME_CTRL, C8UI_MOD_CTRL },
		{ XKB_MOD_NAME_ALT, C8UI_MOD_ALT },
		{ XKB_MOD_NAME_LOGO, C8UI_MOD_SUPER },
	};
	uint32_t mods = 0;
	for (size_t i = 0; app->state && i < G_N_ELEMENTS(known); i++) {
		if (xkb_state_mod_name_is_active(app->state, known[i].name,
				XKB_STATE_MODS_EFFECTIVE) > 0) {
			mods |= known[i].mod;
		}
	}
	return mods;
}

bool c8ui_app_caps_lock(struct c8ui_app *app) {
	return app->state && xkb_state_mod_name_is_active(app->state,
		XKB_MOD_NAME_CAPS, XKB_STATE_MODS_LOCKED) > 0;
}

static void send_key(struct c8ui_app *app, uint32_t key) {
	if (app->keyboard_window == NULL || app->state == NULL) {
		return;
	}
	xkb_keycode_t code = key + 8;
	xkb_keysym_t sym = xkb_state_key_get_one_sym(app->state, code);
	const xkb_keysym_t *raw;
	xkb_layout_index_t layout = xkb_state_key_get_layout(app->state, code);
	int n = xkb_keymap_key_get_syms_by_level(app->keymap, code, layout, 0, &raw);
	char text[64] = "";
	xkb_state_key_get_utf8(app->state, code, text, sizeof(text));
	c8ui_root_key(app->keyboard_window->root, sym, n > 0 ? raw[0] : sym,
		current_mods(app), text);
}

static void stop_repeat(struct c8ui_app *app) {
	if (app->repeat_source) {
		g_source_remove(app->repeat_source);
		app->repeat_source = 0;
	}
}

static gboolean repeat_tick(gpointer data) {
	struct c8ui_app *app = data;
	send_key(app, app->repeat_key);
	return G_SOURCE_CONTINUE;
}

static gboolean repeat_start(gpointer data) {
	struct c8ui_app *app = data;
	send_key(app, app->repeat_key);
	app->repeat_source = g_timeout_add(1000 / app->repeat_rate, repeat_tick, app);
	return G_SOURCE_REMOVE;
}

static void keyboard_keymap(void *data, struct wl_keyboard *keyboard,
		uint32_t format, int32_t fd, uint32_t size) {
	struct c8ui_app *app = data;
	if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) {
		close(fd);
		return;
	}
	char *map = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
	close(fd);
	if (map == MAP_FAILED) {
		return;
	}
	struct xkb_keymap *keymap = xkb_keymap_new_from_string(app->xkb, map,
		XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS);
	munmap(map, size);
	if (keymap == NULL) {
		return;
	}
	xkb_state_unref(app->state);
	xkb_keymap_unref(app->keymap);
	app->keymap = keymap;
	app->state = xkb_state_new(keymap);
}

static void keyboard_enter(void *data, struct wl_keyboard *keyboard,
		uint32_t serial, struct wl_surface *surface, struct wl_array *keys) {
	struct c8ui_app *app = data;
	app->last_serial = serial;
	app->keyboard_window = window_for(app, surface);
	if (app->keyboard_window) {
		c8ui_root_keyboard_focus(app->keyboard_window->root, true);
	}
}

static void keyboard_leave(void *data, struct wl_keyboard *keyboard,
		uint32_t serial, struct wl_surface *surface) {
	struct c8ui_app *app = data;
	stop_repeat(app);
	if (app->keyboard_window) {
		c8ui_root_keyboard_focus(app->keyboard_window->root, false);
	}
	app->keyboard_window = NULL;
}

static void keyboard_key(void *data, struct wl_keyboard *keyboard,
		uint32_t serial, uint32_t time, uint32_t key, uint32_t state) {
	struct c8ui_app *app = data;
	app->last_serial = serial;
	if (state == WL_KEYBOARD_KEY_STATE_RELEASED) {
		if (key == app->repeat_key) {
			stop_repeat(app);
		}
		return;
	}
	stop_repeat(app);
	send_key(app, key);
	if (app->keymap && app->repeat_rate > 0 &&
			xkb_keymap_key_repeats(app->keymap, key + 8)) {
		app->repeat_key = key;
		app->repeat_source = g_timeout_add(app->repeat_delay, repeat_start, app);
	}
}

static void keyboard_modifiers(void *data, struct wl_keyboard *keyboard,
		uint32_t serial, uint32_t depressed, uint32_t latched, uint32_t locked,
		uint32_t group) {
	struct c8ui_app *app = data;
	if (app->state) {
		xkb_state_update_mask(app->state, depressed, latched, locked, 0, 0,
			group);
	}
	struct c8ui_window *win = app->keyboard_window;
	if (win && win->modifiers_fn) {
		win->modifiers_fn(win, current_mods(app), win->modifiers_data);
	}
}

static void keyboard_repeat_info(void *data, struct wl_keyboard *keyboard,
		int32_t rate, int32_t delay) {
	struct c8ui_app *app = data;
	app->repeat_rate = rate;
	app->repeat_delay = delay;
}

static const struct wl_keyboard_listener keyboard_listener = {
	.keymap = keyboard_keymap,
	.enter = keyboard_enter,
	.leave = keyboard_leave,
	.key = keyboard_key,
	.modifiers = keyboard_modifiers,
	.repeat_info = keyboard_repeat_info,
};

static void seat_capabilities(void *data, struct wl_seat *seat, uint32_t caps) {
	struct c8ui_app *app = data;
	bool want_pointer = caps & WL_SEAT_CAPABILITY_POINTER;
	bool want_keyboard = caps & WL_SEAT_CAPABILITY_KEYBOARD;
	bool want_touch = caps & WL_SEAT_CAPABILITY_TOUCH;
	if (want_touch && app->touch == NULL) {
		app->touch = wl_seat_get_touch(seat);
		wl_touch_add_listener(app->touch, &touch_listener, app);
	} else if (!want_touch && app->touch) {
		wl_touch_release(app->touch);
		app->touch = NULL;
		memset(app->fingers, 0, sizeof(app->fingers));
	}
	if (want_pointer && app->pointer == NULL) {
		app->pointer = wl_seat_get_pointer(seat);
		wl_pointer_add_listener(app->pointer, &pointer_listener, app);
		if (app->cursor_shape_manager) {
			app->cursor_shape = wp_cursor_shape_manager_v1_get_pointer(
				app->cursor_shape_manager, app->pointer);
		}
		if (app->gestures) {
			app->swipe = zwp_pointer_gestures_v1_get_swipe_gesture(
				app->gestures, app->pointer);
			zwp_pointer_gesture_swipe_v1_add_listener(app->swipe,
				&swipe_listener, app);
			app->pinch = zwp_pointer_gestures_v1_get_pinch_gesture(
				app->gestures, app->pointer);
			zwp_pointer_gesture_pinch_v1_add_listener(app->pinch,
				&pinch_listener, app);
		}
	} else if (!want_pointer && app->pointer) {
		if (app->swipe) {
			zwp_pointer_gesture_swipe_v1_destroy(app->swipe);
			app->swipe = NULL;
		}
		if (app->pinch) {
			zwp_pointer_gesture_pinch_v1_destroy(app->pinch);
			app->pinch = NULL;
		}
		if (app->cursor_shape) {
			wp_cursor_shape_device_v1_destroy(app->cursor_shape);
			app->cursor_shape = NULL;
		}
		wl_pointer_release(app->pointer);
		app->pointer = NULL;
	}
	if (want_keyboard && app->keyboard == NULL) {
		app->keyboard = wl_seat_get_keyboard(seat);
		wl_keyboard_add_listener(app->keyboard, &keyboard_listener, app);
	} else if (!want_keyboard && app->keyboard) {
		stop_repeat(app);
		wl_keyboard_release(app->keyboard);
		app->keyboard = NULL;
	}
}

static void seat_name(void *data, struct wl_seat *seat, const char *name) {
}

static const struct wl_seat_listener seat_listener = {
	.capabilities = seat_capabilities,
	.name = seat_name,
};

/* Windows */

static void xdg_surface_configure(void *data, struct xdg_surface *surface,
		uint32_t serial) {
	struct c8ui_window *win = data;
	xdg_surface_ack_configure(surface, serial);
	win->configured = true;
	c8ui_root_resize(win->root, win->width, win->height);
	win->dirty = win->damage_all = true;
	render(win);
	if (win->activate_token && win->app->activation) {
		/* Mapped by that commit: now the compositor can raise it */
		xdg_activation_v1_activate(win->app->activation, win->activate_token,
			win->surface);
	}
	free(win->activate_token);
	win->activate_token = NULL;
}

static const struct xdg_surface_listener xdg_surface_listener = {
	.configure = xdg_surface_configure,
};

static void toplevel_configure(void *data, struct xdg_toplevel *toplevel,
		int32_t width, int32_t height, struct wl_array *states) {
	struct c8ui_window *win = data;
	if (width > 0 && height > 0) {
		win->width = width;
		win->height = height;
	}
	bool fullscreen = false;
	uint32_t *state;
	wl_array_for_each(state, states) {
		if (*state == XDG_TOPLEVEL_STATE_FULLSCREEN) {
			fullscreen = true;
		}
	}
	if (fullscreen != win->fullscreen) {
		win->fullscreen = fullscreen;
		if (win->fullscreen_fn) {
			win->fullscreen_fn(win, win->fullscreen_data);
		}
	}
}

static void toplevel_close(void *data, struct xdg_toplevel *toplevel) {
	struct c8ui_window *win = data;
	struct c8ui_app *app = win->app;
	if (win->close_fn && !win->close_fn(win, win->close_data)) {
		return;
	}
	c8ui_window_destroy(win);
	if (wl_list_empty(&app->windows) && app->hold == 0) {
		c8ui_app_quit(app, 0);
	}
}

static void toplevel_bounds(void *data, struct xdg_toplevel *toplevel,
		int32_t width, int32_t height) {
}

static void toplevel_wm_capabilities(void *data, struct xdg_toplevel *toplevel,
		struct wl_array *caps) {
}

static const struct xdg_toplevel_listener toplevel_listener = {
	.configure = toplevel_configure,
	.close = toplevel_close,
	.configure_bounds = toplevel_bounds,
	.wm_capabilities = toplevel_wm_capabilities,
};

static void fractional_preferred(void *data,
		struct wp_fractional_scale_v1 *fractional, uint32_t scale) {
	struct c8ui_window *win = data;
	double s = scale / 120.0;
	if (s != win->scale) {
		win->scale = s;
		redraw_all(win);
		if (win->scale_fn) {
			win->scale_fn(win, win->scale_data);
		}
	}
}

static const struct wp_fractional_scale_v1_listener fractional_listener = {
	.preferred_scale = fractional_preferred,
};

static void surface_enter(void *data, struct wl_surface *surface,
		struct wl_output *output) {
}

static void surface_leave(void *data, struct wl_surface *surface,
		struct wl_output *output) {
}

static void surface_preferred_scale(void *data, struct wl_surface *surface,
		int32_t factor) {
	struct c8ui_window *win = data;
	if (win->viewport == NULL && factor != win->scale) {
		win->scale = factor;
		redraw_all(win);
		if (win->scale_fn) {
			win->scale_fn(win, win->scale_data);
		}
	}
}

static void surface_preferred_transform(void *data, struct wl_surface *surface,
		uint32_t transform) {
}

static const struct wl_surface_listener surface_listener = {
	.enter = surface_enter,
	.leave = surface_leave,
	.preferred_buffer_scale = surface_preferred_scale,
	.preferred_buffer_transform = surface_preferred_transform,
};

static struct c8ui_window *window_create(struct c8ui_app *app, int width,
		int height) {
	struct c8ui_window *win = calloc(1, sizeof(*win));
	win->app = app;
	win->width = width;
	win->height = height;
	win->scale = 1;
	win->background = 0xffffff;
	win->background_alpha = 1;
	win->root = c8ui_root_new(&window_host, win, &app->theme);
	win->surface = wl_compositor_create_surface(app->compositor);
	wl_surface_add_listener(win->surface, &surface_listener, win);
	if (app->fractional_manager && app->viewporter) {
		win->fractional = wp_fractional_scale_manager_v1_get_fractional_scale(
			app->fractional_manager, win->surface);
		wp_fractional_scale_v1_add_listener(win->fractional,
			&fractional_listener, win);
		win->viewport = wp_viewporter_get_viewport(app->viewporter, win->surface);
	}
	wl_list_insert(&app->windows, &win->link);
	return win;
}

struct c8ui_window *c8ui_window_new(struct c8ui_app *app, const char *title,
		int width, int height) {
	struct c8ui_window *win = window_create(app, width > 0 ? width : 1024,
		height > 0 ? height : 700);
	win->xdg_surface = xdg_wm_base_get_xdg_surface(app->wm_base, win->surface);
	xdg_surface_add_listener(win->xdg_surface, &xdg_surface_listener, win);
	win->toplevel = xdg_surface_get_toplevel(win->xdg_surface);
	xdg_toplevel_add_listener(win->toplevel, &toplevel_listener, win);
	xdg_toplevel_set_app_id(win->toplevel, app->app_id);
	xdg_toplevel_set_title(win->toplevel, title ? title : app->app_id);
	wl_surface_commit(win->surface);
	return win;
}

struct c8ui_window *c8ui_window_new_bare(struct c8ui_app *app) {
	return window_create(app, 0, 0);
}

struct wl_surface *c8ui_window_surface(struct c8ui_window *win) {
	return win->surface;
}

void c8ui_window_configure(struct c8ui_window *win, int width, int height) {
	if (width <= 0 || height <= 0) {
		return;
	}
	win->width = width;
	win->height = height;
	win->configured = true;
	c8ui_root_resize(win->root, width, height);
	win->dirty = win->damage_all = true;
	render(win);
}

void c8ui_window_unmap(struct c8ui_window *win) {
	if (!win->configured) {
		return;
	}
	win->configured = false;
	if (win->idle) {
		g_source_remove(win->idle);
		win->idle = 0;
	}
	/* No frames come for a hidden surface */
	if (win->frame_cb) {
		wl_callback_destroy(win->frame_cb);
		win->frame_cb = NULL;
	}
	win->frame_pending = false;
	wl_surface_attach(win->surface, NULL, 0, 0);
	wl_surface_commit(win->surface);
	drop_buffers(win);
}

void c8ui_window_suspend(struct c8ui_window *win, bool suspended) {
	if (win->suspended == suspended) {
		return;
	}
	win->suspended = suspended;
	if (suspended) {
		drop_buffers(win);
	} else if (win->dirty || win->animating) {
		schedule(win);
	}
}

void c8ui_window_on_pointer_leave(struct c8ui_window *win, c8ui_window_fn fn,
		void *data) {
	win->leave_fn = fn;
	win->leave_data = data;
}

void c8ui_window_on_modifiers(struct c8ui_window *win, c8ui_modifiers_fn fn,
		void *data) {
	win->modifiers_fn = fn;
	win->modifiers_data = data;
}

void c8ui_window_set_background(struct c8ui_window *win, uint32_t rgb,
		double alpha) {
	win->background = rgb;
	win->background_alpha = alpha;
	redraw_all(win);
}

void c8ui_window_set_opaque_region(struct c8ui_window *win,
		cairo_region_t *region) {
	if (region) {
		cairo_region_reference(region);
	}
	if (win->opaque) {
		cairo_region_destroy(win->opaque);
	}
	win->opaque = region;
}

void c8ui_window_destroy(struct c8ui_window *win) {
	struct c8ui_app *app = win->app;
	if (app->pointer_window == win) {
		app->pointer_window = NULL;
	}
	if (app->dnd.window == win) {
		app->dnd.window = NULL; // the drag goes on over nothing of ours
	}
	for (int i = 0; i < FINGERS; i++) {
		if (app->fingers[i].window == win) {
			app->fingers[i].window = NULL;
		}
	}
	if (app->keyboard_window == win) {
		stop_repeat(app);
		app->keyboard_window = NULL;
	}
	if (win->idle) {
		g_source_remove(win->idle);
	}
	c8ui_root_destroy(win->root);
	if (win->frame_cb) {
		wl_callback_destroy(win->frame_cb);
	}
	if (win->inhibitor) {
		zwp_keyboard_shortcuts_inhibitor_v1_destroy(win->inhibitor);
	}
	if (win->viewport) {
		wp_viewport_destroy(win->viewport);
	}
	if (win->fractional) {
		wp_fractional_scale_v1_destroy(win->fractional);
	}
	if (win->toplevel) {
		xdg_toplevel_destroy(win->toplevel);
		xdg_surface_destroy(win->xdg_surface);
	}
	wl_surface_destroy(win->surface);
	if (win->rest) {
		g_source_remove(win->rest);
	}
	for (int i = 0; i < 2; i++) {
		buffer_finish(&win->buffers[i]);
	}
	if (win->opaque) {
		cairo_region_destroy(win->opaque);
	}
	if (win->exported) {
		zxdg_exported_v2_destroy(win->exported);
	}
	if (win->imported) {
		zxdg_imported_v2_destroy(win->imported);
	}
	free(win->export_handle);
	free(win->activate_token);
	wl_list_remove(&win->link);
	free(win);
}

struct c8ui_root *c8ui_window_root(struct c8ui_window *win) {
	return win->root;
}

void c8ui_window_set_fullscreen(struct c8ui_window *win, bool fullscreen) {
	if (win->toplevel == NULL) {
		return;
	}
	if (fullscreen) {
		xdg_toplevel_set_fullscreen(win->toplevel, NULL);
	} else {
		xdg_toplevel_unset_fullscreen(win->toplevel);
	}
}

bool c8ui_window_is_fullscreen(struct c8ui_window *win) {
	return win->fullscreen;
}

void c8ui_window_on_fullscreen(struct c8ui_window *win, c8ui_window_fn fn,
		void *data) {
	win->fullscreen_fn = fn;
	win->fullscreen_data = data;
}

void c8ui_window_on_close_request(struct c8ui_window *win,
		c8ui_window_close_fn fn, void *data) {
	win->close_fn = fn;
	win->close_data = data;
}

double c8ui_window_scale(struct c8ui_window *win) {
	return win->scale > 0 ? win->scale : 1;
}

void c8ui_window_on_scale(struct c8ui_window *win, c8ui_window_fn fn,
		void *data) {
	win->scale_fn = fn;
	win->scale_data = data;
}

void c8ui_window_set_title(struct c8ui_window *win, const char *title) {
	if (win->toplevel) {
		xdg_toplevel_set_title(win->toplevel, title);
	}
}

/* Activation: bringing windows forward, and tokens for apps we launch */

struct token_request {
	c8ui_token_fn fn;
	void *data;
};

static void token_done(void *data, struct xdg_activation_token_v1 *token,
		const char *name) {
	struct token_request *req = data;
	xdg_activation_token_v1_destroy(token);
	req->fn(name, req->data);
	free(req);
}

static const struct xdg_activation_token_v1_listener token_listener = {
	.done = token_done,
};

void c8ui_window_request_token(struct c8ui_window *win, c8ui_token_fn fn,
		void *data) {
	struct c8ui_app *app = win->app;
	if (app->activation == NULL) {
		fn(NULL, data);
		return;
	}
	struct token_request *req = calloc(1, sizeof(*req));
	req->fn = fn;
	req->data = data;
	struct xdg_activation_token_v1 *token =
		xdg_activation_v1_get_activation_token(app->activation);
	xdg_activation_token_v1_add_listener(token, &token_listener, req);
	/* The compositor only grants it for real input on our window */
	if (app->seat && app->last_serial) {
		xdg_activation_token_v1_set_serial(token, app->last_serial, app->seat);
	}
	xdg_activation_token_v1_set_surface(token, win->surface);
	xdg_activation_token_v1_commit(token);
}

/* Comes forward with the token now, or once it is mapped */
static void activate_with(struct c8ui_window *win, const char *token) {
	if (win->configured) {
		xdg_activation_v1_activate(win->app->activation, token, win->surface);
	} else {
		free(win->activate_token);
		win->activate_token = strdup(token);
	}
}

static void present_with(const char *token, void *data) {
	struct c8ui_app *app = data;
	struct c8ui_window *win;
	/* The window may have gone meanwhile: find it again */
	wl_list_for_each(win, &app->windows, link) {
		if (win->present_waiting) {
			win->present_waiting = false;
			if (token) {
				activate_with(win, token);
			}
			return;
		}
	}
}

void c8ui_window_present(struct c8ui_window *win) {
	struct c8ui_app *app = win->app;
	if (app->activation == NULL) {
		return;
	}
	if (app->launch_token) {
		char *token = app->launch_token;
		app->launch_token = NULL;
		activate_with(win, token);
		free(token);
		return;
	}
	/* No launch: one of our windows has the input, which may hand it on */
	struct c8ui_window *from = app->keyboard_window ? app->keyboard_window :
		app->pointer_window;
	if (from == NULL || from == win) {
		return;
	}
	win->present_waiting = true;
	c8ui_window_request_token(from, present_with, app);
}

static void exported_handle(void *data, struct zxdg_exported_v2 *exported,
		const char *handle) {
	struct c8ui_window *win = data;
	free(win->export_handle);
	win->export_handle = g_strdup_printf("wayland:%s", handle);
}

static const struct zxdg_exported_v2_listener exported_listener = {
	.handle = exported_handle,
};

const char *c8ui_window_export_handle(struct c8ui_window *win) {
	struct c8ui_app *app = win->app;
	if (win->export_handle || win->exported) {
		return win->export_handle ? win->export_handle : "";
	}
	if (app->exporter == NULL || win->toplevel == NULL) {
		return "";
	}
	/* The handle comes straight back. Wait for it on a queue of its own,
	 * so no input is dispatched in the middle of whatever asked. */
	struct wl_event_queue *queue = wl_display_create_queue(app->display);
	struct zxdg_exporter_v2 *wrapper = wl_proxy_create_wrapper(app->exporter);
	wl_proxy_set_queue((struct wl_proxy *)wrapper, queue);
	win->exported = zxdg_exporter_v2_export_toplevel(wrapper, win->surface);
	wl_proxy_wrapper_destroy(wrapper);
	zxdg_exported_v2_add_listener(win->exported, &exported_listener, win);
	wl_display_roundtrip_queue(app->display, queue);
	wl_proxy_set_queue((struct wl_proxy *)win->exported, NULL);
	wl_event_queue_destroy(queue);
	return win->export_handle ? win->export_handle : "";
}

static void imported_destroyed(void *data, struct zxdg_imported_v2 *imported) {
	struct c8ui_window *win = data;
	zxdg_imported_v2_destroy(imported);
	win->imported = NULL; // the parent went: we stand alone
}

static const struct zxdg_imported_v2_listener imported_listener = {
	.destroyed = imported_destroyed,
};

void c8ui_window_set_parent_handle(struct c8ui_window *win,
		const char *handle) {
	struct c8ui_app *app = win->app;
	if (handle == NULL || !g_str_has_prefix(handle, "wayland:") ||
			app->importer == NULL || win->toplevel == NULL) {
		return;
	}
	if (win->imported) {
		zxdg_imported_v2_destroy(win->imported);
	}
	win->imported = zxdg_importer_v2_import_toplevel(app->importer,
		handle + strlen("wayland:"));
	zxdg_imported_v2_add_listener(win->imported, &imported_listener, win);
	zxdg_imported_v2_set_parent_of(win->imported, win->surface);
}

void c8ui_app_hold(struct c8ui_app *app) {
	app->hold++;
}

void c8ui_app_release(struct c8ui_app *app) {
	if (app->hold > 0 && --app->hold == 0 && wl_list_empty(&app->windows)) {
		c8ui_app_quit(app, 0);
	}
}

/* The one copy */

bool c8ui_app_has_windows(struct c8ui_app *app) {
	return !wl_list_empty(&app->windows) || app->hold > 0;
}

GDBusConnection *c8ui_app_unique_bus(struct c8ui_app *app) {
	return app->unique_bus;
}

void c8ui_app_set_unique_bus(struct c8ui_app *app, GDBusConnection *bus) {
	if (bus) {
		g_object_ref(bus);
	}
	if (app->unique_bus) {
		g_object_unref(app->unique_bus);
	}
	app->unique_bus = bus;
}

void c8ui_app_set_launch_token(struct c8ui_app *app, const char *token) {
	free(app->launch_token);
	app->launch_token = c8ui_dup_or_null(token);
}

/* App */

static void wm_base_ping(void *data, struct xdg_wm_base *base, uint32_t serial) {
	xdg_wm_base_pong(base, serial);
}

static const struct xdg_wm_base_listener wm_base_listener = {
	.ping = wm_base_ping,
};

static void registry_global(void *data, struct wl_registry *registry,
		uint32_t name, const char *interface, uint32_t version) {
	struct c8ui_app *app = data;
	app->globals = realloc(app->globals,
		sizeof(*app->globals) * (app->global_count + 1));
	app->globals[app->global_count++] = (struct global){
		.name = name, .interface = strdup(interface), .version = version,
	};
}

static void registry_global_remove(void *data, struct wl_registry *registry,
		uint32_t name) {
	struct c8ui_app *app = data;
	for (int i = 0; i < app->global_count; i++) {
		if (app->globals[i].name == name) {
			free(app->globals[i].interface);
			app->globals[i] = app->globals[--app->global_count];
			return;
		}
	}
}

static const struct wl_registry_listener registry_listener = {
	.global = registry_global,
	.global_remove = registry_global_remove,
};

void *c8ui_app_bind(struct c8ui_app *app, const struct wl_interface *interface,
		uint32_t version) {
	for (int i = 0; i < app->global_count; i++) {
		struct global *g = &app->globals[i];
		if (strcmp(g->interface, interface->name) == 0) {
			return wl_registry_bind(app->registry, g->name, interface,
				g->version < version ? g->version : version);
		}
	}
	return NULL;
}

static uint32_t global_version(struct c8ui_app *app, const char *interface) {
	for (int i = 0; i < app->global_count; i++) {
		if (strcmp(app->globals[i].interface, interface) == 0) {
			return app->globals[i].version;
		}
	}
	return 0;
}

static gboolean display_event(gint fd, GIOCondition cond, gpointer data) {
	struct c8ui_app *app = data;
	if ((cond & (G_IO_ERR | G_IO_HUP)) || wl_display_dispatch(app->display) < 0) {
		fprintf(stderr, "%s: lost the connection to the compositor\n",
			app->app_id);
		app->fd_source = 0;
		c8ui_app_quit(app, EXIT_FAILURE);
		return G_SOURCE_REMOVE;
	}
	return G_SOURCE_CONTINUE;
}

/* Send whatever the last round of callbacks asked for before sleeping */
static gboolean flush_prepare(GSource *source, gint *timeout) {
	struct c8ui_app *app = *(struct c8ui_app **)(source + 1);
	wl_display_dispatch_pending(app->display);
	wl_display_flush(app->display);
	*timeout = -1;
	return FALSE;
}

static gboolean flush_dispatch(GSource *source, GSourceFunc cb, gpointer data) {
	return G_SOURCE_CONTINUE;
}

static GSourceFuncs flush_funcs = {
	.prepare = flush_prepare,
	.dispatch = flush_dispatch,
};

static gboolean icons_ready(gint fd, GIOCondition cond, gpointer data) {
	c8ui_icon_loader_dispatch();
	return G_SOURCE_CONTINUE;
}

const char *c8ui_app_get_id(struct c8ui_app *app) {
	return app->app_id;
}

struct c8ui_app *c8ui_app_new(const char *app_id) {
	/* A paste target closing its pipe early must not kill us */
	signal(SIGPIPE, SIG_IGN);
	/* Light Selawik needs the autohinter's stem darkening or it is faint
	 * and ragged; c8 exports this to the session, but not when nested.
	 * FreeType reads it when it starts, so before any text is drawn */
	setenv("FREETYPE_PROPERTIES", "autofitter:no-stem-darkening=0", false);
	struct c8ui_app *app = calloc(1, sizeof(*app));
	app->app_id = strdup(app_id);
	app->repeat_rate = 25;
	app->repeat_delay = 600;
	wl_list_init(&app->windows);
	app->display = wl_display_connect(NULL);
	if (app->display == NULL) {
		free(app->app_id);
		free(app);
		return NULL;
	}
	app->registry = wl_display_get_registry(app->display);
	wl_registry_add_listener(app->registry, &registry_listener, app);
	wl_display_roundtrip(app->display);

	app->compositor_version = global_version(app, wl_compositor_interface.name);
	app->compositor = c8ui_app_bind(app, &wl_compositor_interface, 6);
	app->shm = c8ui_app_bind(app, &wl_shm_interface, 1);
	app->wm_base = c8ui_app_bind(app, &xdg_wm_base_interface, 5);
	if (app->compositor == NULL || app->shm == NULL || app->wm_base == NULL ||
			app->compositor_version < 4) {
		fprintf(stderr, "%s: the compositor lacks what windows need\n", app_id);
		wl_display_disconnect(app->display);
		free(app->app_id);
		free(app);
		return NULL;
	}
	xdg_wm_base_add_listener(app->wm_base, &wm_base_listener, app);
	app->cursor_shape_manager =
		c8ui_app_bind(app, &wp_cursor_shape_manager_v1_interface, 1);
	app->fractional_manager =
		c8ui_app_bind(app, &wp_fractional_scale_manager_v1_interface, 1);
	app->viewporter = c8ui_app_bind(app, &wp_viewporter_interface, 1);
	app->inhibit_manager = c8ui_app_bind(app,
		&zwp_keyboard_shortcuts_inhibit_manager_v1_interface, 1);
	app->data_manager = c8ui_app_bind(app, &wl_data_device_manager_interface, 3);
	app->gestures = c8ui_app_bind(app, &zwp_pointer_gestures_v1_interface, 1);
	app->activation = c8ui_app_bind(app, &xdg_activation_v1_interface, 1);
	app->exporter = c8ui_app_bind(app, &zxdg_exporter_v2_interface, 1);
	app->importer = c8ui_app_bind(app, &zxdg_importer_v2_interface, 1);
	app->seat = c8ui_app_bind(app, &wl_seat_interface, 9);
	app->xkb = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
	if (app->seat) {
		wl_seat_add_listener(app->seat, &seat_listener, app);
		if (app->data_manager) {
			app->data_device = wl_data_device_manager_get_data_device(
				app->data_manager, app->seat);
			wl_data_device_add_listener(app->data_device, &device_listener, app);
		}
	}
	wl_display_roundtrip(app->display);

	const char *xdg = getenv("XDG_CONFIG_HOME");
	app->config_dir = xdg && xdg[0] ?
		g_build_filename(xdg, "cont8nuum", NULL) :
		g_build_filename(g_get_home_dir(), ".config", "cont8nuum", NULL);
	load_theme(app);
	watch_theme(app);

	app->loop = g_main_loop_new(NULL, FALSE);
	int icon_fd = c8ui_icon_loader_start();
	if (icon_fd >= 0) {
		app->icon_source = g_unix_fd_add(icon_fd, G_IO_IN, icons_ready, NULL);
	}
	app->fd_source = g_unix_fd_add(wl_display_get_fd(app->display),
		G_IO_IN | G_IO_ERR | G_IO_HUP, display_event, app);
	app->flush_source = g_source_new(&flush_funcs,
		sizeof(GSource) + sizeof(struct c8ui_app *));
	*(struct c8ui_app **)(app->flush_source + 1) = app;
	g_source_attach(app->flush_source, NULL);
	return app;
}

struct wl_display *c8ui_app_display(struct c8ui_app *app) {
	return app->display;
}

int c8ui_app_run(struct c8ui_app *app) {
	g_main_loop_run(app->loop);
	return app->status;
}

void c8ui_app_quit(struct c8ui_app *app, int status) {
	app->status = status;
	g_main_loop_quit(app->loop);
}

void c8ui_app_destroy(struct c8ui_app *app) {
	struct c8ui_window *win, *tmp;
	wl_list_for_each_safe(win, tmp, &app->windows, link) {
		c8ui_window_destroy(win);
	}
	stop_repeat(app);
	if (app->fd_source) {
		g_source_remove(app->fd_source);
	}
	if (app->icon_source) {
		g_source_remove(app->icon_source);
		c8ui_icon_loader_stop();
	}
	g_source_destroy(app->flush_source);
	g_source_unref(app->flush_source);
	for (int i = 0; i < 2; i++) {
		if (app->monitors[i]) {
			g_object_unref(app->monitors[i]);
		}
	}
	if (app->source) {
		wl_data_source_destroy(app->source);
	}
	if (app->selection) {
		offer_destroy(app->selection);
	}
	if (app->dnd.offer) {
		offer_destroy(app->dnd.offer);
	}
	app->drag.done = NULL; // too late to tell anyone
	drag_end(app, 0);
	if (app->exporter) {
		zxdg_exporter_v2_destroy(app->exporter);
	}
	if (app->importer) {
		zxdg_importer_v2_destroy(app->importer);
	}
	if (app->activation) {
		xdg_activation_v1_destroy(app->activation);
	}
	c8ui_app_set_unique_bus(app, NULL);
	free(app->launch_token);
	xkb_state_unref(app->state);
	xkb_keymap_unref(app->keymap);
	xkb_context_unref(app->xkb);
	wl_display_flush(app->display);
	wl_display_disconnect(app->display);
	g_main_loop_unref(app->loop);
	for (int i = 0; i < app->global_count; i++) {
		free(app->globals[i].interface);
	}
	free(app->globals);
	if (app->source_items) {
		g_ptr_array_unref(app->source_items);
	}
	free(app->theme.font);
	g_free(app->config_dir);
	free(app->app_id);
	free(app);
}
