#include <math.h>
#include <pixman.h>
#include <pango/pangocairo.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include "c8ui-private.h"
#include "text-private.h"

#define ENTER_MS 330
#define TIP_DELAY_MS 600 // the pointer rests this long before a tooltip
#define TIP_SHOW_MS 5000 // then it goes by itself
#define TIP_PAD_X 8
#define TIP_PAD_Y 5
#define TIP_MAX_W 320
#define ENTER_OFFSET 40
#define CULL_MARGIN 16

/* Colours */

void c8ui_set_source(cairo_t *cr, uint32_t rgb, double alpha) {
	cairo_set_source_rgba(cr, ((rgb >> 16) & 0xff) / 255.0,
		((rgb >> 8) & 0xff) / 255.0, (rgb & 0xff) / 255.0, alpha);
}

uint32_t c8ui_shade(uint32_t rgb, double factor) {
	uint32_t out = 0;
	for (int shift = 0; shift <= 16; shift += 8) {
		double c = ((rgb >> shift) & 0xff) * factor;
		out |= (uint32_t)(c > 255 ? 255 : c < 0 ? 0 : c) << shift;
	}
	return out;
}

bool c8ui_parse_color(const char *s, uint32_t *rgb) {
	if (s == NULL) {
		return false;
	}
	if (s[0] == '#') {
		s++;
	}
	if (strlen(s) != 6) {
		return false;
	}
	char *end;
	unsigned long v = strtoul(s, &end, 16);
	if (*end != '\0') {
		return false;
	}
	*rgb = (uint32_t)v;
	return true;
}

bool c8ui_rect_contains(const struct c8ui_rect *r, double x, double y) {
	return x >= r->x && y >= r->y && x < r->x + r->width &&
		y < r->y + r->height;
}

/* Text */

struct c8ui_font c8ui_text_font(enum c8ui_text_style style) {
	switch (style) {
	case C8UI_TEXT_HEADER:
		return (struct c8ui_font){ 42, C8UI_WEIGHT_LIGHT };
	case C8UI_TEXT_SUBHEADER:
		return (struct c8ui_font){ 26, C8UI_WEIGHT_LIGHT };
	case C8UI_TEXT_TITLE:
		return (struct c8ui_font){ 20, C8UI_WEIGHT_SEMILIGHT };
	case C8UI_TEXT_ITEM:
		return (struct c8ui_font){ 20, C8UI_WEIGHT_LIGHT };
	case C8UI_TEXT_BODY:
		return (struct c8ui_font){ 15, C8UI_WEIGHT_NORMAL };
	case C8UI_TEXT_BODY_STRONG:
		return (struct c8ui_font){ 15, C8UI_WEIGHT_SEMIBOLD };
	case C8UI_TEXT_CAPTION:
		return (struct c8ui_font){ 12, C8UI_WEIGHT_NORMAL };
	}
	return (struct c8ui_font){ 15, C8UI_WEIGHT_NORMAL };
}

cairo_t *c8ui_measure_cr(void) {
	static cairo_t *cr;
	if (cr == NULL) {
		cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1, 1);
		cr = cairo_create(s);
		cairo_surface_destroy(s);
	}
	return cr;
}

PangoLayout *c8ui_text_layout(cairo_t *cr, const char *family,
		struct c8ui_font font, const char *text, double max_width,
		int max_lines) {
	static const PangoWeight weights[] = {
		[C8UI_WEIGHT_LIGHT] = PANGO_WEIGHT_LIGHT,
		[C8UI_WEIGHT_SEMILIGHT] = PANGO_WEIGHT_SEMILIGHT,
		[C8UI_WEIGHT_NORMAL] = PANGO_WEIGHT_NORMAL,
		[C8UI_WEIGHT_SEMIBOLD] = PANGO_WEIGHT_SEMIBOLD,
		[C8UI_WEIGHT_BOLD] = PANGO_WEIGHT_BOLD,
	};
	PangoLayout *layout = pango_cairo_create_layout(cr);
	PangoFontDescription *desc = pango_font_description_from_string(
		family && family[0] ? family : C8UI_DEFAULT_FONT);
	pango_font_description_set_absolute_size(desc, font.size * PANGO_SCALE);
	pango_font_description_set_weight(desc, weights[font.weight]);
	pango_layout_set_font_description(layout, desc);
	pango_font_description_free(desc);
	pango_layout_set_text(layout, text ? text : "", -1);
	if (max_width > 0) {
		pango_layout_set_width(layout, (int)(max_width * PANGO_SCALE));
		pango_layout_set_wrap(layout, PANGO_WRAP_WORD_CHAR);
		pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END);
		pango_layout_set_height(layout, max_lines > 0 ? -max_lines : -1000);
	}

	cairo_font_options_t *options = cairo_font_options_create();
	cairo_font_options_set_antialias(options, CAIRO_ANTIALIAS_GRAY);
	cairo_font_options_set_hint_style(options, CAIRO_HINT_STYLE_SLIGHT);
	cairo_font_options_set_hint_metrics(options, CAIRO_HINT_METRICS_OFF);
	pango_cairo_context_set_font_options(pango_layout_get_context(layout),
		options);
	cairo_font_options_destroy(options);
	pango_layout_context_changed(layout);
	return layout;
}

/* Drawing shapes the text too, and a window is drawn again whole for
 * every frame of a scroll: the layouts of what was drawn lately are kept
 * and only told about the cairo context they're shown on next (a new
 * scale lays them out again, a scroll doesn't). One set per thread,
 * since a layout can't be shared between two. */
#define LAYOUT_CACHE_MAX 512
#define LAYOUT_CACHE_TEXT 256

/* Everything a text's layout (and so its size) depends on */
static char *text_key(const char *family, struct c8ui_font font,
		const char *text, double max_width, int max_lines) {
	return g_strdup_printf("%g\x1f%d\x1f%g\x1f%d\x1f%s\x1f%s", font.size,
		(int)font.weight, max_width, max_lines, family ? family : "",
		text ? text : "");
}

static void layout_cache_free(gpointer cache) {
	g_hash_table_destroy(cache);
}

static GPrivate layout_cache = G_PRIVATE_INIT(layout_cache_free);

double c8ui_text_draw(cairo_t *cr, const char *family, struct c8ui_font font,
		const char *text, double x, double y, double max_width, int max_lines) {
	PangoLayout *layout = NULL;
	char *key = NULL;
	GHashTable *cache = NULL;
	if (text == NULL || strlen(text) <= LAYOUT_CACHE_TEXT) {
		cache = g_private_get(&layout_cache);
		if (cache == NULL) {
			cache = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
				g_object_unref);
			g_private_set(&layout_cache, cache);
		}
		key = text_key(family, font, text, max_width, max_lines);
		layout = g_hash_table_lookup(cache, key);
	}
	if (layout) {
		g_free(key);
		pango_cairo_update_layout(cr, layout);
	} else {
		layout = c8ui_text_layout(cr, family, font, text, max_width,
			max_lines);
		if (cache) {
			if (g_hash_table_size(cache) >= LAYOUT_CACHE_MAX) {
				g_hash_table_remove_all(cache);
			}
			g_hash_table_insert(cache, key, layout);
		}
	}
	int w, h;
	pango_layout_get_size(layout, &w, &h);
	cairo_move_to(cr, x, y);
	pango_cairo_show_layout(cr, layout);
	cairo_new_path(cr);
	if (cache == NULL) {
		g_object_unref(layout);
	}
	return (double)h / PANGO_SCALE;
}

/* Measuring shapes the text, and the same labels are measured on every
 * layout and draw (list rows ask for a line's height per item), so the
 * answers are kept. The key is everything the size depends on. */
#define SIZE_CACHE_MAX 2048
#define SIZE_CACHE_TEXT 256 // longer texts are rare and not worth keeping

struct text_size {
	double width, height;
};

void c8ui_text_size(const char *family, struct c8ui_font font,
		const char *text, double max_width, int max_lines, double *width,
		double *height) {
	static GHashTable *cache;
	static GMutex lock;
	char *key = NULL;
	if (text == NULL || strlen(text) <= SIZE_CACHE_TEXT) {
		key = text_key(family, font, text, max_width, max_lines);
		g_mutex_lock(&lock);
		if (cache == NULL) {
			cache = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
				g_free);
		}
		struct text_size *hit = g_hash_table_lookup(cache, key);
		if (hit) {
			*width = hit->width;
			*height = hit->height;
		}
		g_mutex_unlock(&lock);
		if (hit) {
			g_free(key);
			return;
		}
	}
	PangoLayout *layout = c8ui_text_layout(c8ui_measure_cr(), family, font,
		text, max_width, max_lines);
	int w, h;
	pango_layout_get_size(layout, &w, &h);
	g_object_unref(layout);
	*width = ceil((double)w / PANGO_SCALE);
	*height = ceil((double)h / PANGO_SCALE);
	if (key) {
		struct text_size *size = g_new(struct text_size, 1);
		size->width = *width;
		size->height = *height;
		g_mutex_lock(&lock);
		if (g_hash_table_size(cache) >= SIZE_CACHE_MAX) {
			g_hash_table_remove_all(cache);
		}
		g_hash_table_insert(cache, key, size);
		g_mutex_unlock(&lock);
	}
}

int c8ui_text_index_at(const char *family, struct c8ui_font font,
		const char *text, double x) {
	PangoLayout *layout = c8ui_text_layout(c8ui_measure_cr(), family, font,
		text, 0, 0);
	int index, trailing;
	pango_layout_xy_to_index(layout, (int)(x * PANGO_SCALE), 0, &index,
		&trailing);
	/* trailing counts characters, not bytes */
	const char *p = text + index;
	while (trailing-- > 0 && *p) {
		p = g_utf8_next_char(p);
	}
	g_object_unref(layout);
	return (int)(p - text);
}

double c8ui_text_x_of(const char *family, struct c8ui_font font,
		const char *text, int index) {
	PangoLayout *layout = c8ui_text_layout(c8ui_measure_cr(), family, font,
		text, 0, 0);
	PangoRectangle pos;
	pango_layout_index_to_pos(layout, index, &pos);
	g_object_unref(layout);
	return (double)pos.x / PANGO_SCALE;
}

/* Widgets */

struct c8ui_widget *c8ui_widget_new(const struct c8ui_widget_impl *impl,
		void *data) {
	struct c8ui_widget *w = calloc(1, sizeof(*w));
	w->impl = impl;
	w->data = data;
	return w;
}

/* Tells w and what is in it, children first, whether the window is
 * narrow, where that differs from what each was last told. A hook may
 * change the children: they are walked from a copy, and those it moves
 * away (no longer w's) are left to where they went. */
static void tell_narrow(struct c8ui_widget *w, bool narrow) {
	if (w->child_count > 0) {
		int n = w->child_count;
		struct c8ui_widget **kids = malloc(sizeof(*kids) * n);
		memcpy(kids, w->children, sizeof(*kids) * n);
		for (int i = 0; i < n; i++) {
			if (kids[i]->parent == w) {
				tell_narrow(kids[i], narrow);
			}
		}
		free(kids);
	}
	if (w->narrow != narrow || !w->narrow_told) {
		w->narrow = narrow;
		w->narrow_told = true;
		if (w->narrow_hides) {
			c8ui_widget_set_hidden(w, narrow);
		}
		if (w->impl->narrow) {
			w->impl->narrow(w, narrow);
		}
	}
}

static void set_root_only(struct c8ui_widget *w, struct c8ui_root *root) {
	w->root = root;
	for (int i = 0; i < w->child_count; i++) {
		set_root_only(w->children[i], root);
	}
}

static void set_root(struct c8ui_widget *w, struct c8ui_root *root) {
	set_root_only(w, root);
	if (root && root->width > 0) {
		tell_narrow(w, c8ui_root_is_narrow(root));
	}
}

bool c8ui_widget_narrow(struct c8ui_widget *w) {
	return w && w->root && c8ui_root_is_narrow(w->root);
}

void c8ui_widget_set_narrow_hidden(struct c8ui_widget *w, bool hidden) {
	w->narrow_hides = hidden;
	if (w->narrow_told) {
		c8ui_widget_set_hidden(w, hidden && w->narrow);
	}
}

bool c8ui_widget_is_shown(struct c8ui_widget *w) {
	for (; w; w = w->parent) {
		if (w->hidden) {
			return false;
		}
	}
	return true;
}

bool c8ui_widget_shows_focus(struct c8ui_widget *w) {
	return w->focused && w->root && w->root->focus_visible;
}

static bool is_disabled(struct c8ui_widget *w) {
	for (; w; w = w->parent) {
		if (w->disabled) {
			return true;
		}
	}
	return false;
}

/* Damage: what a frame has to draw again. Widgets say what changed and
 * the root keeps it as a region until the host draws; everything is the
 * answer whenever that is simpler (a layout, an overlay coming or going)
 * or the pieces have become too many. */

#define DAMAGE_MAX_RECTS 32

static void damage_all(struct c8ui_root *root) {
	root->damage_all = true;
	if (root->damage) {
		cairo_region_destroy(root->damage);
		root->damage = NULL;
	}
	root->impl->queue_redraw(root->host);
}

/* x1, y1 to x2, y2 of w, in root coordinates, as it will show: inside
 * every ancestor that clips, the whole of one that draws its children
 * somewhere else, and with room for the entrance slide */
static void damage_box(struct c8ui_widget *w, double x1, double y1,
		double x2, double y2) {
	struct c8ui_root *root = w->root;
	if (root->damage_all) {
		root->impl->queue_redraw(root->host);
		return;
	}
	if (w->entering || w->leaving) {
		*(w->enter_up ? &y2 : &x2) += ENTER_OFFSET;
	}
	for (struct c8ui_widget *p = w->parent; p; p = p->parent) {
		double px2 = p->rect.x + p->rect.width;
		double py2 = p->rect.y + p->rect.height;
		if (p->moves_children) {
			x1 = p->rect.x;
			y1 = p->rect.y;
			x2 = px2;
			y2 = py2;
		} else if (p->impl->clips) {
			x1 = fmax(x1, p->rect.x);
			y1 = fmax(y1, p->rect.y);
			x2 = fmin(x2, px2);
			y2 = fmin(y2, py2);
		}
		if (p->entering || p->leaving) {
			*(p->enter_up ? &y2 : &x2) += ENTER_OFFSET;
		}
	}
	x1 = fmax(x1, 0);
	y1 = fmax(y1, 0);
	x2 = fmin(x2, root->width);
	y2 = fmin(y2, root->height);
	if (x2 <= x1 || y2 <= y1) {
		return; // nothing of it shows
	}
	cairo_rectangle_int_t r = { (int)floor(x1), (int)floor(y1), 0, 0 };
	r.width = (int)ceil(x2) - r.x;
	r.height = (int)ceil(y2) - r.y;
	if (root->damage == NULL) {
		root->damage = cairo_region_create();
	}
	cairo_region_union_rectangle(root->damage, &r);
	if (cairo_region_num_rectangles(root->damage) > DAMAGE_MAX_RECTS) {
		damage_all(root);
		return;
	}
	root->impl->queue_redraw(root->host);
}

void c8ui_widget_queue_draw(struct c8ui_widget *w) {
	if (w && w->root) {
		damage_box(w, w->rect.x - CULL_MARGIN, w->rect.y - CULL_MARGIN,
			w->rect.x + w->rect.width + CULL_MARGIN,
			w->rect.y + w->rect.height + CULL_MARGIN);
	}
}

void c8ui_widget_queue_draw_rect(struct c8ui_widget *w, double x, double y,
		double width, double height) {
	if (w && w->root && width > 0 && height > 0) {
		damage_box(w, x, y, x + width, y + height);
	}
}

/* The focus ring shows or not: what has the focus looks different */
void c8ui_root_show_focus(struct c8ui_root *root, bool visible) {
	if (root->focus_visible != visible) {
		root->focus_visible = visible;
		c8ui_widget_queue_draw(root->focus);
	}
}

cairo_region_t *c8ui_root_take_damage(struct c8ui_root *root) {
	cairo_region_t *region = root->damage;
	bool all = root->damage_all || root->needs_layout;
	root->damage = NULL;
	root->damage_all = false;
	if (all) {
		if (region) {
			cairo_region_destroy(region);
		}
		return NULL;
	}
	return region ? region : cairo_region_create();
}

bool c8ui_clip_shows(cairo_t *cr, double x, double y, double width,
		double height) {
	double x1, y1, x2, y2;
	cairo_clip_extents(cr, &x1, &y1, &x2, &y2);
	if (x >= x2 || y >= y2 || x + width <= x1 || y + height <= y1) {
		return false;
	}
	/* Inside the bounds; the clip may be several pieces apart (two
	 * tiles changed), with this in the gap */
	cairo_rectangle_list_t *list = cairo_copy_clip_rectangle_list(cr);
	bool shows = list->status != CAIRO_STATUS_SUCCESS;
	for (int i = 0; i < list->num_rectangles && !shows; i++) {
		cairo_rectangle_t *r = &list->rectangles[i];
		shows = x < r->x + r->width && y < r->y + r->height &&
			x + width > r->x && y + height > r->y;
	}
	cairo_rectangle_list_destroy(list);
	return shows;
}

void c8ui_widget_queue_layout(struct c8ui_widget *w) {
	if (w && w->root) {
		w->root->needs_layout = true;
		damage_all(w->root);
	}
}

void c8ui_widget_insert(struct c8ui_widget *parent, int index,
		struct c8ui_widget *child) {
	if (child->parent) {
		c8ui_widget_unparent(child);
	}
	if (parent->child_count == parent->child_cap) {
		parent->child_cap = parent->child_cap ? parent->child_cap * 2 : 4;
		parent->children = realloc(parent->children,
			sizeof(*parent->children) * parent->child_cap);
	}
	if (index < 0 || index > parent->child_count) {
		index = parent->child_count;
	}
	memmove(&parent->children[index + 1], &parent->children[index],
		sizeof(*parent->children) * (parent->child_count - index));
	parent->children[index] = child;
	parent->child_count++;
	child->parent = parent;
	set_root(child, parent->root);
	c8ui_widget_queue_layout(parent);
}

void c8ui_widget_add(struct c8ui_widget *parent, struct c8ui_widget *child) {
	c8ui_widget_insert(parent, -1, child);
}

/* Tooltips */

static int tip_timeout(void *data) {
	struct c8ui_root *root = data;
	if (root->tip_owner == NULL) {
		root->tip_timer = NULL;
		return 0;
	}
	if (!root->tip_shown) {
		root->tip_shown = true;
		root->tip_x = root->px;
		root->tip_y = root->py;
		damage_all(root);
		return TIP_SHOW_MS;
	}
	/* Shown long enough; it comes back when the pointer moves on */
	root->tip_shown = false;
	root->tip_timer = NULL;
	damage_all(root);
	return 0;
}

/* The tooltip is now owner's (NULL: none), waiting to show */
static void tip_reset(struct c8ui_root *root, struct c8ui_widget *owner) {
	if (root->tip_timer) {
		c8ui_root_timer_remove(root, root->tip_timer);
		root->tip_timer = NULL;
	}
	if (root->tip_shown) {
		root->tip_shown = false;
		damage_all(root);
	}
	root->tip_owner = owner;
	if (owner) {
		root->tip_timer = c8ui_root_timer_add(root, TIP_DELAY_MS,
			tip_timeout, root);
	}
}

/* Hides the tooltip until the pointer goes to something else */
static void tip_dismiss(struct c8ui_root *root) {
	if (root->tip_owner) {
		struct c8ui_widget *owner = root->tip_owner;
		tip_reset(root, NULL);
		root->tip_owner = owner;
	}
}

static struct c8ui_widget *hit(struct c8ui_widget *w, double x, double y);
static struct c8ui_widget *top_layer(struct c8ui_root *root);

static void tip_update(struct c8ui_root *root) {
	struct c8ui_widget *owner = NULL;
	/* Not for fingers, or while something is held down */
	if (root->pointer_in && root->touch_mouse < 0 && root->grab == NULL) {
		owner = hit(top_layer(root), root->px, root->py);
		while (owner && owner->tooltip == NULL) {
			owner = owner->parent;
		}
	}
	if (owner != root->tip_owner) {
		tip_reset(root, owner);
	}
}

static void tip_draw(struct c8ui_root *root, cairo_t *cr) {
	struct c8ui_widget *w = root->tip_owner;
	if (!root->tip_shown || w == NULL || w->tooltip == NULL) {
		return;
	}
	const char *family = c8ui_widget_font(w);
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY);
	double tw, th;
	c8ui_text_size(family, font, w->tooltip, TIP_MAX_W, 0, &tw, &th);
	double bw = tw + 2 * TIP_PAD_X, bh = th + 2 * TIP_PAD_Y;
	/* Under the pointer, clear of the cursor, or above it if no room */
	double x = root->tip_x - bw / 2;
	double y = root->tip_y + 24;
	if (y + bh > root->height - 4) {
		y = root->tip_y - 8 - bh;
	}
	x = x + bw > root->width - 4 ? root->width - 4 - bw : x;
	x = x < 4 ? 4 : x;
	y = y < 4 ? 4 : y;
	x = round(x);
	y = round(y);
	struct c8ui_colors c = c8ui_widget_colors(w);
	uint32_t bg = c.dark ? 0x2b2b2b : 0xffffff;
	uint32_t fg = c.dark ? 0xffffff : 0x000000;
	c8ui_set_source(cr, bg, 1);
	cairo_rectangle(cr, x, y, bw, bh);
	cairo_fill(cr);
	c8ui_set_source(cr, fg, c.dark ? 0.4 : 0.3);
	cairo_set_line_width(cr, 1);
	cairo_rectangle(cr, x + 0.5, y + 0.5, bw - 1, bh - 1);
	cairo_stroke(cr);
	c8ui_set_source(cr, fg, 1);
	c8ui_text_draw(cr, family, font, w->tooltip, x + TIP_PAD_X, y + TIP_PAD_Y,
		TIP_MAX_W, 0);
}

void c8ui_widget_set_tooltip(struct c8ui_widget *w, const char *text) {
	free(w->tooltip);
	w->tooltip = c8ui_dup_or_null(text);
	if (w->root && w->root->tip_owner == w) {
		if (w->tooltip == NULL) {
			tip_reset(w->root, NULL);
		} else {
			damage_all(w->root);
		}
	}
}

/* Drop every reference the root holds to w */
static void root_forget(struct c8ui_root *root, struct c8ui_widget *w) {
	if (root == NULL) {
		return;
	}
	if (root->hover == w) {
		root->hover = NULL;
	}
	if (root->grab == w) {
		root->grab = NULL;
	}
	if (root->swipe == w) {
		root->swipe = NULL;
	}
	if (root->pinch == w) {
		root->pinch = NULL;
	}
	for (int i = 0; i < 10; i++) {
		if (root->touches[i].owner == w) {
			root->touches[i].owner = NULL;
		}
	}
	if (root->focus == w) {
		root->focus = NULL;
	}
	if (root->tip_owner == w) {
		tip_reset(root, NULL);
	}
	if (root->back == w) {
		root->back = NULL;
	}
	for (int i = 0; i < root->overlay_count; i++) {
		if (root->saved_focus[i] == w) {
			root->saved_focus[i] = NULL;
		}
	}
	for (int i = 0; i < root->tick_count; i++) {
		if (root->ticking[i] == w) {
			root->ticking[i] = NULL;
		}
	}
}

static void forget_tree(struct c8ui_root *root, struct c8ui_widget *w) {
	root_forget(root, w);
	for (int i = 0; i < w->child_count; i++) {
		forget_tree(root, w->children[i]);
	}
}

void c8ui_widget_unparent(struct c8ui_widget *w) {
	struct c8ui_widget *parent = w->parent;
	if (parent == NULL) {
		return;
	}
	for (int i = 0; i < parent->child_count; i++) {
		if (parent->children[i] == w) {
			memmove(&parent->children[i], &parent->children[i + 1],
				sizeof(*parent->children) * (parent->child_count - i - 1));
			parent->child_count--;
			break;
		}
	}
	c8ui_widget_queue_layout(parent);
	forget_tree(w->root, w);
	w->parent = NULL;
	set_root(w, NULL);
}

static void destroy_tree(struct c8ui_widget *w) {
	for (int i = 0; i < w->child_count; i++) {
		w->children[i]->parent = NULL;
		destroy_tree(w->children[i]);
	}
	root_forget(w->root, w);
	if (w->on_destroy) {
		w->on_destroy(w, w->user_data);
	}
	for (int i = 0; i < w->track_count; i++) {
		if (*w->tracks[i] == w) {
			*w->tracks[i] = NULL;
		}
	}
	free(w->tracks);
	if (w->impl->destroy) {
		w->impl->destroy(w);
	}
	free(w->tooltip);
	free(w->children);
	free(w);
}

void c8ui_dispatch_begin(struct c8ui_root *root) {
	root->dispatching++;
}

void c8ui_dispatch_end(struct c8ui_root *root) {
	if (--root->dispatching > 0) {
		return;
	}
	/* Freeing may destroy more (on_destroy handlers): keep going */
	while (root->grave_count > 0) {
		struct c8ui_widget *w = root->graveyard[--root->grave_count];
		destroy_tree(w);
	}
}

void c8ui_widget_track(struct c8ui_widget *w, struct c8ui_widget **slot) {
	*slot = w;
	for (int i = 0; i < w->track_count; i++) {
		if (w->tracks[i] == slot) {
			return;
		}
	}
	w->tracks = realloc(w->tracks, (w->track_count + 1) * sizeof(*w->tracks));
	w->tracks[w->track_count++] = slot;
}

void c8ui_widget_destroy(struct c8ui_widget *w) {
	if (w == NULL) {
		return;
	}
	struct c8ui_root *root = w->root;
	if (w->parent) {
		c8ui_widget_unparent(w);
	} else if (root) {
		if (root->child == w) {
			root->child = NULL;
		}
		for (int i = 0; i < root->overlay_count; i++) {
			if (root->overlays[i] == w) {
				c8ui_root_remove_overlay(root, w);
				break;
			}
		}
	}
	if (root && root->dispatching > 0) {
		forget_tree(root, w);
		set_root(w, NULL);
		if (root->grave_count == root->grave_cap) {
			root->grave_cap = root->grave_cap ? root->grave_cap * 2 : 8;
			root->graveyard = realloc(root->graveyard,
				sizeof(*root->graveyard) * root->grave_cap);
		}
		root->graveyard[root->grave_count++] = w;
		return;
	}
	destroy_tree(w);
}

void c8ui_widget_clear(struct c8ui_widget *w) {
	while (w->child_count > 0) {
		c8ui_widget_destroy(w->children[w->child_count - 1]);
	}
}

void c8ui_widget_set_hidden(struct c8ui_widget *w, bool hidden) {
	if (w->hidden == hidden) {
		return;
	}
	w->hidden = hidden;
	if (hidden && w->root) {
		forget_tree(w->root, w);
	}
	c8ui_widget_queue_layout(w);
}

void c8ui_widget_set_disabled(struct c8ui_widget *w, bool disabled) {
	w->disabled = disabled;
	c8ui_widget_queue_draw(w);
}

void c8ui_widget_set_scheme(struct c8ui_widget *w, enum c8ui_scheme scheme) {
	w->scheme = scheme;
	c8ui_widget_queue_draw(w);
}

void c8ui_widget_set_background(struct c8ui_widget *w, uint32_t rgb) {
	w->has_background = true;
	w->background = rgb;
	c8ui_widget_queue_draw(w);
}

struct c8ui_colors c8ui_widget_colors(struct c8ui_widget *w) {
	enum c8ui_scheme scheme = C8UI_SCHEME_LIGHT;
	uint32_t bg = 0;
	bool has_bg = false;
	for (struct c8ui_widget *p = w; p; p = p->parent) {
		if (!has_bg && p->has_background) {
			bg = p->background;
			has_bg = true;
		}
		if (p->scheme != C8UI_SCHEME_INHERIT) {
			scheme = p->scheme;
			break;
		}
	}
	struct c8ui_colors c;
	const struct c8ui_theme *theme = w->root ? &w->root->theme : NULL;
	c.accent = theme ? theme->accent : C8UI_DEFAULT_ACCENT;
	c.dark = scheme == C8UI_SCHEME_DARK;
	if (c.dark) {
		c.bg = 0x1d1d1d;
		c.fg = 0xffffff;
		c.fg_secondary = 0.65;
		c.border = 0.6;
		c.border_hover = 0.85;
		c.fill = 0.15;
	} else {
		c.bg = 0xffffff;
		c.fg = 0x000000;
		c.fg_secondary = 0.6;
		c.border = 0.45;
		c.border_hover = 0.7;
		c.fill = 0.1;
	}
	if (has_bg) {
		c.bg = bg;
	}
	if (is_disabled(w)) {
		c.border *= 0.5;
		c.border_hover = c.border;
		c.fg_secondary *= 0.6;
	}
	return c;
}

const char *c8ui_widget_font(struct c8ui_widget *w) {
	if (w->root && w->root->theme.font) {
		return w->root->theme.font;
	}
	return C8UI_DEFAULT_FONT;
}

void c8ui_widget_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	*width = *height = 0;
	if (w->hidden) {
		return;
	}
	if (w->max_width > 0 && avail > w->max_width) {
		avail = w->max_width;
	}
	/* A fixed width gives way when there isn't that much room (a narrow
	 * window), rather than run off the edge */
	double fixed = w->fixed_width;
	if (fixed > 0 && avail > 0 && avail < fixed) {
		fixed = avail;
	}
	if (fixed > 0) {
		avail = fixed;
	}
	if (w->impl->measure) {
		w->impl->measure(w, avail, width, height);
	}
	if (fixed > 0) {
		*width = fixed;
	}
	if (w->fixed_height > 0) {
		*height = w->fixed_height;
	}
	if (w->min_width > 0 && *width < w->min_width) {
		*width = w->min_width;
	}
}

void c8ui_widget_layout(struct c8ui_widget *w, struct c8ui_rect rect) {
	w->rect = rect;
	if (!w->hidden && w->impl->layout) {
		w->impl->layout(w);
	}
}

void c8ui_widget_animate(struct c8ui_widget *w) {
	struct c8ui_root *root = w->root;
	if (root == NULL) {
		return;
	}
	for (int i = 0; i < root->tick_count; i++) {
		if (root->ticking[i] == w) {
			root->impl->request_frame(root->host);
			return;
		}
	}
	if (root->tick_count == root->tick_cap) {
		root->tick_cap = root->tick_cap ? root->tick_cap * 2 : 8;
		root->ticking = realloc(root->ticking,
			sizeof(*root->ticking) * root->tick_cap);
	}
	root->ticking[root->tick_count++] = w;
	root->impl->request_frame(root->host);
}

void c8ui_widget_enter(struct c8ui_widget *w) {
	w->leaving = false;
	w->enter_up = false;
	w->entering = true;
	w->enter_start = 0;
	c8ui_widget_animate(w);
	c8ui_widget_queue_draw(w);
}

void c8ui_widget_enter_up(struct c8ui_widget *w) {
	c8ui_widget_enter(w);
	w->enter_up = true;
	c8ui_widget_queue_draw(w);
}

void c8ui_widget_leave_down(struct c8ui_widget *w) {
	w->entering = false;
	w->enter_up = true;
	w->leaving = true;
	w->enter_start = 0;
	c8ui_widget_animate(w);
	c8ui_widget_queue_draw(w);
}

/* Press tilt, see struct c8ui_tilt */

#define TILT_DOWN_MS 100
#define TILT_UP_MS 200
/* The item is a card turned in space, seen from TILT_EYE px away: it
 * goes back TILT_SINK px all over, and turns so the edge pressed goes
 * back TILT_TURN px more and the far one comes forward as much */
#define TILT_EYE 800
#define TILT_SINK 10
#define TILT_TURN 24
/* But no corner moves more than this many px, in or out: the same
 * depth moves a point by its distance from the middle, so a list row
 * 960 px long swung its ends a long way (and the corner coming forward,
 * fitted back in, shrank the whole row) where a tile hardly moved */
#define TILT_REACH 6
/* A long thin item (a list row) reaches less, by how much longer than
 * twice its width it is, down to this: a row tilting as far as a tile
 * looked far too much, even under the reach */
#define TILT_REACH_THIN 2

int64_t c8ui_now(void) {
	return c8ui_now_ms();
}

double c8ui_tilt_depth(const struct c8ui_tilt *t, int64_t now) {
	if (t->start == 0) {
		return t->down ? 1 : 0;
	}
	double e = (double)(now - t->start) / (t->down ? TILT_DOWN_MS : TILT_UP_MS);
	e = c8ui_ease_out(e < 0 ? 0 : e > 1 ? 1 : e);
	return t->from + ((t->down ? 1 : 0) - t->from) * e;
}

bool c8ui_tilt_moving(const struct c8ui_tilt *t, int64_t now) {
	return t->start &&
		now - t->start < (t->down ? TILT_DOWN_MS : TILT_UP_MS) + 20;
}

void c8ui_tilt_set(struct c8ui_tilt *t, bool down, double x, double y,
		int64_t now) {
	if (down) {
		t->x = x;
		t->y = y;
	}
	if (down == t->down) {
		return;
	}
	t->from = c8ui_tilt_depth(t, now);
	t->down = down;
	t->start = now;
}

bool c8ui_tilt_begin(cairo_t *cr, const struct c8ui_rect *r, double depth) {
	if (depth <= 0.001 || r->width < 1 || r->height < 1) {
		return false;
	}
	cairo_save(cr);
	cairo_rectangle(cr, r->x, r->y, r->width, r->height);
	cairo_clip(cr);
	cairo_push_group(cr);
	return true;
}

/* Draws src (w x h, premultiplied ARGB) into dst turned in perspective:
 * a projective map, which cairo hasn't got and pixman has. Coordinates
 * are device pixels, (px, py) the press. */
static bool tilt_warp(cairo_surface_t *src, cairo_surface_t *dst, int w,
		int h, double px, double py, double depth, double scale,
		double quad[4][2]) {
	double cx = w / 2.0, cy = h / 2.0;
	double nx = fmin(fmax((px - cx) / cx, -1), 1);
	double ny = fmin(fmax((py - cy) / cy, -1), 1);
	double eye = TILT_EYE * scale;
	double sink = TILT_SINK * scale * depth;
	double turn_x = TILT_TURN * scale * depth * nx;
	double turn_y = TILT_TURN * scale * depth * ny;
	/* A corner r px from the middle that goes z back (or forward) moves
	 * about r z / eye; all of it less until none moves past the reach */
	double most = 0;
	for (int i = 0; i < 4; i++) {
		most = fmax(most, fabs(sink + (i & 1 ? turn_x : -turn_x) +
			(i & 2 ? turn_y : -turn_y)));
	}
	double thin = fmin(1, 2 * fmin(cx, cy) / fmax(cx, cy));
	double reach = fmax(TILT_REACH_THIN, TILT_REACH * thin) * scale * eye /
		hypot(cx, cy);
	if (most > reach) {
		sink *= reach / most;
		turn_x *= reach / most;
		turn_y *= reach / most;
	}
	/* How far back a point is: sink + a x + b y, from the middle */
	double a = turn_x / cx, b = turn_y / cy;
	/* Seen from the eye, a point at x, y and that depth shows at
	 * (x, y) / k with k = (eye + depth) / eye. Smaller by fit all
	 * over, so the corner that comes forward stays inside the rect
	 * (DRAWING.md: nothing drawn outside it) */
	double fit = 1;
	for (int i = 0; i < 4; i++) {
		double x = i & 1 ? cx : -cx, y = i & 2 ? cy : -cy;
		fit = fmin(fit, (eye + sink + a * x + b * y) / eye);
	}
	/* From src to dst, about the middle, as a 3x3 matrix */
	struct pixman_f_transform fwd = { .m = {
		{ fit, 0, 0 },
		{ 0, fit, 0 },
		{ a / eye, b / eye, (eye + sink) / eye },
	} };
	struct pixman_f_transform to_mid, from_mid, m, inv;
	pixman_f_transform_init_translate(&to_mid, -cx, -cy);
	pixman_f_transform_init_translate(&from_mid, cx, cy);
	pixman_f_transform_multiply(&m, &fwd, &to_mid);
	pixman_f_transform_multiply(&m, &from_mid, &m);
	/* Where the corners went: only that is painted, as pixman's fixed
	 * point let a line of pixels outside it through */
	for (int i = 0; i < 4; i++) {
		double v[3] = { i == 1 || i == 2 ? w : 0, i >= 2 ? h : 0, 1 };
		if (!pixman_f_transform_point(&m, (struct pixman_f_vector *)v)) {
			return false;
		}
		quad[i][0] = v[0];
		quad[i][1] = v[1];
	}
	/* pixman goes the other way, each dst pixel to where it is in src */
	if (!pixman_f_transform_invert(&inv, &m)) {
		return false;
	}
	/* Its matrix is 16.16 fixed point, too coarse for the bottom row's
	 * tiny numbers. Any multiple is the same map, so made bigger; but
	 * what it gives for a pixel must stay a 16.16 number too (under
	 * 32768), and that is about the multiple times the size */
	double k = 16000 / fmax(w, h) / inv.m[2][2];
	for (int i = 0; i < 3; i++) {
		for (int j = 0; j < 3; j++) {
			inv.m[i][j] *= k;
		}
	}
	struct pixman_transform fixed;
	if (!pixman_transform_from_pixman_f_transform(&fixed, &inv)) {
		return false;
	}
	cairo_surface_flush(src);
	pixman_image_t *s = pixman_image_create_bits(PIXMAN_a8r8g8b8, w, h,
		(uint32_t *)cairo_image_surface_get_data(src),
		cairo_image_surface_get_stride(src));
	pixman_image_t *d = pixman_image_create_bits(PIXMAN_a8r8g8b8, w, h,
		(uint32_t *)cairo_image_surface_get_data(dst),
		cairo_image_surface_get_stride(dst));
	bool ok = s && d;
	if (ok) {
		pixman_image_set_transform(s, &fixed);
		pixman_image_set_filter(s, PIXMAN_FILTER_BILINEAR, NULL, 0);
		pixman_image_composite32(PIXMAN_OP_SRC, s, NULL, d, 0, 0, 0, 0, 0,
			0, w, h);
		cairo_surface_mark_dirty(dst);
	}
	if (s) {
		pixman_image_unref(s);
	}
	if (d) {
		pixman_image_unref(d);
	}
	return ok;
}

void c8ui_tilt_end(cairo_t *cr, const struct c8ui_tilt *t,
		const struct c8ui_rect *r, double depth) {
	cairo_pattern_t *item = cairo_pop_group(cr);
	double quad[4][2];
	/* Copied out at the device's size (the ctm only scales and moves),
	 * turned into a second picture, and that put back 1:1 */
	double scale = 1, unused = 0;
	cairo_user_to_device_distance(cr, &scale, &unused);
	scale = fabs(scale);
	int w = (int)ceil(r->width * scale), h = (int)ceil(r->height * scale);
	cairo_surface_t *src = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
		w, h);
	cairo_surface_t *dst = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
		w, h);
	bool ok = scale > 0 &&
		cairo_surface_status(src) == CAIRO_STATUS_SUCCESS &&
		cairo_surface_status(dst) == CAIRO_STATUS_SUCCESS;
	if (ok) {
		cairo_t *c = cairo_create(src);
		cairo_scale(c, scale, scale);
		cairo_translate(c, -r->x, -r->y);
		cairo_set_source(c, item);
		cairo_paint(c);
		cairo_destroy(c);
		ok = tilt_warp(src, dst, w, h, t->x * scale, t->y * scale, depth,
			scale, quad);
	}
	if (ok) {
		cairo_translate(cr, r->x, r->y);
		cairo_scale(cr, 1 / scale, 1 / scale);
		cairo_move_to(cr, quad[0][0], quad[0][1]);
		for (int i = 1; i < 4; i++) {
			cairo_line_to(cr, quad[i][0], quad[i][1]);
		}
		cairo_close_path(cr);
		cairo_clip(cr);
		cairo_set_source_surface(cr, dst, 0, 0);
	} else {
		cairo_set_source(cr, item); // as it was, untilted
	}
	cairo_paint(cr);
	cairo_surface_destroy(src);
	cairo_surface_destroy(dst);
	cairo_pattern_destroy(item);
	cairo_restore(cr);
}

void c8ui_widget_draw(struct c8ui_widget *w, cairo_t *cr) {
	if (w->hidden || w->rect.width <= 0 || w->rect.height <= 0) {
		return;
	}
	double leave_t = 0;
	if (w->leaving) {
		leave_t = w->enter_start == 0 || w->root == NULL ? 0 :
			(double)(w->root->now - w->enter_start) / C8UI_LEAVE_MS;
		if (leave_t >= 1) {
			return; // gone, until the owner takes it away
		}
	}
	if (w->child_count == 0 && !w->entering && !w->leaving) {
		/* Scrolled out of sight (a scroll or hub only clips): shaping its
		 * text and scaling its pictures would draw nothing. Only widgets
		 * without children, whose rect is all they are, and with room
		 * for what is drawn just outside it (focus rings). */
		double x1, y1, x2, y2;
		cairo_clip_extents(cr, &x1, &y1, &x2, &y2);
		if (w->rect.x - CULL_MARGIN >= x2 || w->rect.y - CULL_MARGIN >= y2 ||
				w->rect.x + w->rect.width + CULL_MARGIN <= x1 ||
				w->rect.y + w->rect.height + CULL_MARGIN <= y1) {
			return;
		}
	}
	cairo_save(cr);
	double alpha = 1;
	if (w->entering) {
		double t = w->enter_start == 0 || w->root == NULL ? 0 :
			(double)(w->root->now - w->enter_start) / ENTER_MS;
		double e = c8ui_ease_out(t);
		alpha = e;
		double off = (1 - e) * ENTER_OFFSET;
		cairo_translate(cr, w->enter_up ? 0 : off, w->enter_up ? off : 0);
		cairo_push_group(cr);
	} else if (w->leaving) {
		double e = leave_t * leave_t; // easing in: it sets off slowly
		alpha = 1 - e;
		cairo_translate(cr, 0, e * ENTER_OFFSET);
		cairo_push_group(cr);
	}
	double tilt = w->tilts ? c8ui_tilt_depth(&w->tilt, c8ui_now_ms()) : 0;
	bool tilted = tilt > 0 && c8ui_tilt_begin(cr, &w->rect, tilt);
	if (w->tilts) {
		/* Its children aren't where their rects say: a change in one
		 * draws all of it */
		w->moves_children = tilted;
	}
	if (w->has_background) {
		c8ui_set_source(cr, w->background, 1);
		cairo_rectangle(cr, w->rect.x, w->rect.y, w->rect.width, w->rect.height);
		cairo_fill(cr);
	}
	if (w->impl->draw) {
		w->impl->draw(w, cr);
	}
	for (int i = 0; i < w->child_count; i++) {
		c8ui_widget_draw(w->children[i], cr);
	}
	if (w->impl->draw_over) {
		w->impl->draw_over(w, cr);
	}
	if (tilted) {
		c8ui_tilt_end(cr, &w->tilt, &w->rect, tilt);
	}
	if (w->entering || w->leaving) {
		cairo_pop_group_to_source(cr);
		cairo_paint_with_alpha(cr, alpha);
	}
	cairo_restore(cr);
}

void c8ui_widget_grab_focus(struct c8ui_widget *w) {
	if (w->root) {
		c8ui_root_set_focus(w->root, w);
	}
}

/* Root */

struct c8ui_root *c8ui_root_new(const struct c8ui_host_impl *impl, void *host,
		const struct c8ui_theme *theme) {
	struct c8ui_root *root = calloc(1, sizeof(*root));
	root->impl = impl;
	root->host = host;
	root->touch_mouse = -1;
	root->tpinch.leftover = -1;
	c8ui_root_set_theme(root, theme);
	return root;
}

void c8ui_root_keep(struct c8ui_root *root, struct c8ui_widget *w) {
	if (root->kept_count == root->kept_cap) {
		root->kept_cap = root->kept_cap ? root->kept_cap * 2 : 4;
		root->kept = realloc(root->kept, sizeof(*root->kept) * root->kept_cap);
	}
	root->kept[root->kept_count++] = w;
}

void c8ui_root_unkeep(struct c8ui_root *root, struct c8ui_widget *w) {
	for (int i = 0; i < root->kept_count; i++) {
		if (root->kept[i] == w) {
			root->kept[i] = root->kept[--root->kept_count];
			return;
		}
	}
}

void c8ui_root_destroy(struct c8ui_root *root) {
	/* Their destroy unkeeps them, and takes them off if shown */
	while (root->kept_count > 0) {
		c8ui_widget_destroy(root->kept[root->kept_count - 1]);
	}
	while (root->overlay_count > 0) {
		c8ui_widget_destroy(root->overlays[root->overlay_count - 1]);
	}
	c8ui_widget_destroy(root->child);
	tip_reset(root, NULL);
	if (root->damage) {
		cairo_region_destroy(root->damage);
	}
	free(root->graveyard);
	free(root->kept);
	free(root->overlays);
	free(root->saved_focus);
	free(root->popups);
	free(root->ticking);
	free(root->theme.font);
	free(root);
}

void c8ui_root_set_child(struct c8ui_root *root, struct c8ui_widget *child) {
	if (root->child) {
		c8ui_widget_destroy(root->child);
	}
	root->child = child;
	set_root(child, root);
	root->needs_layout = true;
	damage_all(root);
}

void c8ui_root_set_theme(struct c8ui_root *root, const struct c8ui_theme *theme) {
	char *font = theme && theme->font ? strdup(theme->font) : NULL;
	free(root->theme.font);
	root->theme.font = font;
	root->theme.accent = theme ? theme->accent : C8UI_DEFAULT_ACCENT;
	root->theme.background = theme ? theme->background : C8UI_DEFAULT_BACKGROUND;
	root->needs_layout = true;
	damage_all(root);
}

const struct c8ui_theme *c8ui_root_theme(struct c8ui_root *root) {
	return &root->theme;
}

double c8ui_root_width(struct c8ui_root *root) {
	return root->width;
}

double c8ui_root_height(struct c8ui_root *root) {
	return root->height;
}

void c8ui_root_resize(struct c8ui_root *root, double width, double height) {
	if (width == root->width && height == root->height) {
		return;
	}
	root->width = width;
	root->height = height;
	root->needs_layout = true;
	if (root->resize_fn) {
		root->resize_fn(root, width, height, root->resize_data);
	}
	/* Narrow or wide now: what changes shape is told (only what differs
	 * from what it was told, so a resize within one does nothing) */
	bool narrow = c8ui_root_is_narrow(root);
	if (width > 0) {
		if (root->child) {
			tell_narrow(root->child, narrow);
		}
		for (int i = 0; i < root->overlay_count; i++) {
			tell_narrow(root->overlays[i], narrow);
		}
	}
	damage_all(root);
}

bool c8ui_root_is_narrow(struct c8ui_root *root) {
	return root->width > 0 && root->width < C8UI_NARROW_WIDTH;
}

void c8ui_root_on_resize(struct c8ui_root *root, c8ui_resize_fn fn,
		void *data) {
	root->resize_fn = fn;
	root->resize_data = data;
}

static void update_hover(struct c8ui_root *root);

static void do_layout(struct c8ui_root *root) {
	root->needs_layout = false;
	struct c8ui_rect full = { 0, 0, root->width, root->height };
	if (root->child) {
		c8ui_widget_layout(root->child, full);
	}
	for (int i = 0; i < root->overlay_count; i++) {
		c8ui_widget_layout(root->overlays[i], full);
	}
	update_hover(root);
}

/* The dotted rectangle around what has the keyboard, after Tab */
static void draw_focus_visual(struct c8ui_root *root, cairo_t *cr) {
	struct c8ui_widget *w = root->focus;
	if (w == NULL || !root->focus_visible || !root->keyboard_focused ||
			!c8ui_widget_is_shown(w)) {
		return;
	}
	cairo_save(cr);
	for (struct c8ui_widget *p = w->parent; p; p = p->parent) {
		if (p->impl->clips) {
			cairo_rectangle(cr, p->rect.x, p->rect.y, p->rect.width,
				p->rect.height);
			cairo_clip(cr);
		}
	}
	struct c8ui_colors c = c8ui_widget_colors(w);
	c8ui_set_source(cr, c.fg, 1);
	cairo_set_line_width(cr, 1);
	double dash[] = { 1, 1 };
	cairo_set_dash(cr, dash, 2, 0);
	cairo_rectangle(cr, w->rect.x - 2.5, w->rect.y - 2.5, w->rect.width + 5,
		w->rect.height + 5);
	cairo_stroke(cr);
	cairo_restore(cr);
}

void c8ui_root_draw(struct c8ui_root *root, cairo_t *cr) {
	if (root->needs_layout) {
		do_layout(root);
	}
	if (root->child) {
		c8ui_widget_draw(root->child, cr);
	}
	for (int i = 0; i < root->overlay_count; i++) {
		c8ui_widget_draw(root->overlays[i], cr);
	}
	draw_focus_visual(root, cr);
	tip_draw(root, cr);
}

bool c8ui_root_tick(struct c8ui_root *root, int64_t now) {
	root->now = now;
	bool redraw = false;
	c8ui_dispatch_begin(root);
	for (int i = 0; i < root->tick_count; i++) {
		struct c8ui_widget *w = root->ticking[i];
		bool more = false;
		bool entered = w && w->entering;
		if (w && w->entering) {
			if (w->enter_start == 0) {
				w->enter_start = now;
			}
			w->entering = now - w->enter_start < ENTER_MS;
			more |= w->entering;
		}
		if (w && w->leaving) { // stays leaving: not drawn once over
			if (w->enter_start == 0) {
				w->enter_start = now;
			}
			entered = true;
			more |= now - w->enter_start < C8UI_LEAVE_MS + 20;
		}
		if (w && w->impl->tick) {
			more |= w->impl->tick(w, now);
		}
		if (w && w->root == root && w->tilts) {
			more |= c8ui_tilt_moving(&w->tilt, c8ui_now_ms());
		}
		redraw |= w != NULL;
		if (w && w->root == root && (entered || !w->impl->tick ||
				!w->impl->tick_damages)) {
			/* Where it was a frame ago too: further along its slide */
			damage_box(w, w->rect.x - CULL_MARGIN, w->rect.y - CULL_MARGIN,
				w->rect.x + w->rect.width + CULL_MARGIN +
				(entered && !w->entering && !w->enter_up ? ENTER_OFFSET : 0),
				w->rect.y + w->rect.height + CULL_MARGIN +
				(entered && (w->leaving || !w->entering) && w->enter_up ?
				ENTER_OFFSET : 0));
		}
		if (!more) {
			/* Tick may have destroyed widgets: only clear the slot */
			root->ticking[i] = NULL;
		}
	}
	int n = 0;
	for (int i = 0; i < root->tick_count; i++) {
		if (root->ticking[i]) {
			root->ticking[n++] = root->ticking[i];
		}
	}
	root->tick_count = n;
	c8ui_dispatch_end(root);
	if (redraw) {
		root->impl->queue_redraw(root->host);
	}
	return n > 0;
}

/* Input */

static struct c8ui_widget *top_layer(struct c8ui_root *root) {
	return root->overlay_count > 0 ? root->overlays[root->overlay_count - 1] :
		root->child;
}

static struct c8ui_widget *hit(struct c8ui_widget *w, double x, double y) {
	if (w == NULL || w->hidden || !c8ui_rect_contains(&w->rect, x, y)) {
		return NULL;
	}
	for (int i = w->child_count - 1; i >= 0; i--) {
		struct c8ui_widget *h = hit(w->children[i], x, y);
		if (h) {
			return h;
		}
	}
	return w;
}

/* The widget that takes events at a point: the deepest one that can */
static struct c8ui_widget *target_at(struct c8ui_root *root, double x,
		double y) {
	struct c8ui_widget *w = hit(top_layer(root), x, y);
	while (w && (w->impl->event == NULL || is_disabled(w))) {
		w = w->parent;
	}
	return w;
}

static bool send(struct c8ui_widget *w, struct c8ui_event *ev) {
	if (w == NULL || w->impl->event == NULL || is_disabled(w)) {
		return false;
	}
	return w->impl->event(w, ev);
}

static void set_cursor(struct c8ui_root *root, enum c8ui_cursor cursor) {
	if (root->cursor != cursor && root->impl->set_cursor) {
		root->cursor = cursor;
		root->impl->set_cursor(root->host, cursor);
	}
}

void c8ui_widget_set_cursor(struct c8ui_widget *w, enum c8ui_cursor cursor) {
	w->cursor = cursor;
	if (w->root && w->hovered && w->root->grab == NULL) {
		set_cursor(w->root, cursor);
	}
}

static void update_hover(struct c8ui_root *root) {
	if (root->grab) {
		return;
	}
	struct c8ui_widget *t = root->pointer_in ?
		target_at(root, root->px, root->py) : NULL;
	if (t != root->hover) {
		struct c8ui_widget *old = root->hover;
		root->hover = t;
		if (old) {
			old->hovered = false;
			struct c8ui_event ev = { .type = C8UI_EVENT_LEAVE };
			send(old, &ev);
			c8ui_widget_queue_draw(old);
		}
		if (t) {
			t->hovered = true;
			struct c8ui_event ev = { .type = C8UI_EVENT_ENTER,
				.x = root->px, .y = root->py };
			send(t, &ev);
			c8ui_widget_queue_draw(t);
		}
	}
	set_cursor(root, t ? t->cursor : C8UI_CURSOR_DEFAULT);
	tip_update(root);
}

void c8ui_root_pointer_motion(struct c8ui_root *root, double x, double y) {
	root->px = x;
	root->py = y;
	root->pointer_in = true;
	if (root->needs_layout) {
		do_layout(root);
	}
	struct c8ui_event ev = { .type = C8UI_EVENT_MOTION, .x = x, .y = y };
	c8ui_dispatch_begin(root);
	if (root->grab) {
		send(root->grab, &ev);
	} else {
		update_hover(root);
		send(root->hover, &ev);
	}
	c8ui_dispatch_end(root);
}

/* Nothing has the press any more; returns what had it */
static struct c8ui_widget *grab_end(struct c8ui_root *root) {
	struct c8ui_widget *grab = root->grab;
	root->grab = NULL;
	root->grab_buttons = 0;
	if (grab) {
		grab->pressed = false;
		if (grab->tilts) {
			c8ui_tilt_set(&grab->tilt, false, 0, 0, c8ui_now_ms());
			c8ui_widget_animate(grab);
		}
	}
	return grab;
}

void c8ui_root_cancel_press(struct c8ui_root *root) {
	struct c8ui_widget *grab = grab_end(root);
	if (grab == NULL) {
		return;
	}
	c8ui_widget_queue_draw(grab);
	c8ui_dispatch_begin(root);
	update_hover(root);
	c8ui_dispatch_end(root);
}

struct c8ui_widget *c8ui_root_widget_at(struct c8ui_root *root, double x,
		double y) {
	return hit(top_layer(root), x, y);
}

void c8ui_root_pointer_leave(struct c8ui_root *root) {
	root->pointer_in = false;
	c8ui_dispatch_begin(root);
	update_hover(root);
	c8ui_dispatch_end(root);
}

static struct c8ui_widget *focusable_ancestor(struct c8ui_widget *w) {
	for (; w; w = w->parent) {
		if (w->focusable) {
			return w;
		}
	}
	return NULL;
}

static void pointer_button(struct c8ui_root *root, uint32_t button,
		bool pressed);

static bool in_tree(struct c8ui_widget *w, struct c8ui_widget *tree);

/* The back button, if one shows on the layer that has input */
static bool back_shown(struct c8ui_root *root) {
	return root->back && c8ui_widget_is_shown(root->back) &&
		!root->back->disabled && in_tree(root->back, top_layer(root));
}

void c8ui_root_set_back(struct c8ui_root *root, struct c8ui_widget *back) {
	root->back = back;
}

void c8ui_root_set_mods(struct c8ui_root *root, uint32_t mods) {
	root->mods = mods;
}

void c8ui_root_pointer_button(struct c8ui_root *root, uint32_t button,
		bool pressed) {
	c8ui_dispatch_begin(root);
	pointer_button(root, button, pressed);
	c8ui_dispatch_end(root);
}

static void pointer_button(struct c8ui_root *root, uint32_t button,
		bool pressed) {
	struct c8ui_event ev = {
		.type = pressed ? C8UI_EVENT_PRESS : C8UI_EVENT_RELEASE,
		.x = root->px, .y = root->py, .button = button,
		.mods = root->mods,
	};
	if (!pressed) {
		if (root->grab && --root->grab_buttons <= 0) {
			struct c8ui_widget *grab = grab_end(root);
			c8ui_widget_queue_draw(grab);
			send(grab, &ev);
			update_hover(root);
		}
		return;
	}
	tip_dismiss(root);
	if (root->grab) {
		root->grab_buttons++;
		send(root->grab, &ev);
		return;
	}
	if (button == C8UI_BUTTON_BACK && back_shown(root)) {
		c8ui_back_activate(root->back);
		return;
	}
	c8ui_root_show_focus(root, false);
	struct c8ui_widget *t = root->hover;
	/* A popup keeps the focus where it is */
	bool popup = root->overlay_count > 0 &&
		root->popups[root->overlay_count - 1];
	if (!popup || focusable_ancestor(t)) {
		c8ui_root_set_focus(root, focusable_ancestor(t));
	}
	root->repress = false;
	for (struct c8ui_widget *w = t; w; w = w->parent) {
		if (send(w, &ev)) {
			/* Not if the press took it away (closed a popup) */
			if (w->root == root) {
				root->grab = w;
				root->grab_buttons = 1;
				w->pressed = true;
				if (w->tilts && button == C8UI_BUTTON_LEFT) {
					c8ui_tilt_set(&w->tilt, true, ev.x - w->rect.x,
						ev.y - w->rect.y, c8ui_now_ms());
					c8ui_widget_animate(w);
				}
				c8ui_widget_queue_draw(w);
			}
			break;
		}
		if (w->root != root) {
			break;
		}
	}
	if (root->repress) {
		root->repress = false;
		update_hover(root);
		pointer_button(root, button, true);
	}
}

/* Touch */

#define TOUCHES (int)(sizeof(((struct c8ui_root *)0)->touches) / \
	sizeof(((struct c8ui_root *)0)->touches[0]))

static int touch_slot(struct c8ui_root *root, int32_t id) {
	for (int i = 0; i < TOUCHES; i++) {
		if (root->touches[i].owner && root->touches[i].id == id) {
			return i;
		}
	}
	return -1;
}

static void touch_mouse_end(struct c8ui_root *root) {
	root->touch_mouse = -1;
	/* A finger has no hover: once it lifts nothing stays lit */
	root->pointer_in = false;
	update_hover(root);
}

/* The touchscreen's pinch: a second finger landing while one is down
 * is offered, with the first, as a pinch at their midpoint to the
 * widgets there (as a touchpad's is); one that takes it gets both
 * fingers as PINCH_UPDATEs, and the first finger's touch is cancelled */

static void tpinch_send(struct c8ui_root *root, enum c8ui_event_type type,
		bool cancelled) {
	struct c8ui_widget *w = root->pinch;
	if (w == NULL) {
		return;
	}
	double mx = (root->tpinch.x[0] + root->tpinch.x[1]) / 2;
	double my = (root->tpinch.y[0] + root->tpinch.y[1]) / 2;
	double d = hypot(root->tpinch.x[1] - root->tpinch.x[0],
		root->tpinch.y[1] - root->tpinch.y[0]);
	struct c8ui_event ev = { .type = type, .x = mx, .y = my,
		.dx = mx - root->tpinch.mx, .dy = my - root->tpinch.my,
		.fingers = 2, .precise = true, .cancelled = cancelled,
		.scale = type == C8UI_EVENT_PINCH_UPDATE ?
			d / root->tpinch.d0 : 1 };
	root->tpinch.mx = mx;
	root->tpinch.my = my;
	if (type == C8UI_EVENT_PINCH_END) {
		root->pinch = NULL;
	}
	send(w, &ev);
}

/* The finger that is the mouse lets go somewhere nothing is, so no
 * click lands */
static void touch_mouse_drop(struct c8ui_root *root) {
	root->px = root->py = -1e6;
	if (root->grab) {
		struct c8ui_event ev = { .type = C8UI_EVENT_MOTION,
			.x = root->px, .y = root->py };
		send(root->grab, &ev);
	}
	pointer_button(root, C8UI_BUTTON_LEFT, false);
	touch_mouse_end(root);
}

/* A finger some widget owns is done: lifted (UP) or taken away (CANCEL) */
static void touch_end(struct c8ui_root *root, int slot,
		enum c8ui_event_type type, uint32_t time) {
	struct c8ui_widget *w = root->touches[slot].owner;
	root->touches[slot].owner = NULL;
	struct c8ui_event ev = { .type = type,
		.touch_id = root->touches[slot].id, .time = time };
	send(w, &ev);
}

/* The first finger's touch ends without doing anything */
static void touch_let_go(struct c8ui_root *root, int32_t id) {
	if (id == root->touch_mouse) {
		touch_mouse_drop(root);
		return;
	}
	int slot = touch_slot(root, id);
	if (slot >= 0) {
		touch_end(root, slot, C8UI_EVENT_TOUCH_CANCEL, 0);
	}
}

static bool tpinch_begin(struct c8ui_root *root, int32_t id, double x,
		double y) {
	if (root->tpinch.on || root->pinch || root->tpinch.leftover >= 0) {
		return false;
	}
	/* Exactly one finger down before this one */
	int32_t first = -1;
	double fx = 0, fy = 0;
	int count = 0;
	if (root->touch_mouse >= 0) {
		first = root->touch_mouse;
		fx = root->mouse_x;
		fy = root->mouse_y;
		count++;
	}
	for (int i = 0; i < TOUCHES; i++) {
		if (root->touches[i].owner) {
			first = root->touches[i].id;
			fx = root->touches[i].x;
			fy = root->touches[i].y;
			count++;
		}
	}
	double d = hypot(x - fx, y - fy);
	if (count != 1 || d < 1) {
		return false;
	}
	double mx = (x + fx) / 2, my = (y + fy) / 2;
	struct c8ui_event ev = { .type = C8UI_EVENT_PINCH_BEGIN, .x = mx,
		.y = my, .fingers = 2, .precise = true, .scale = 1 };
	struct c8ui_widget *taker = NULL;
	for (struct c8ui_widget *w = hit(top_layer(root), mx, my); w;
			w = w->parent) {
		if (send(w, &ev)) {
			taker = w;
			break;
		}
		if (w->root != root) {
			break;
		}
	}
	if (taker == NULL || taker->root != root) {
		return false;
	}
	tip_dismiss(root);
	root->pinch = taker;
	root->pinch_fingers = 2;
	root->tpinch.on = true;
	root->tpinch.id[0] = first;
	root->tpinch.x[0] = fx;
	root->tpinch.y[0] = fy;
	root->tpinch.id[1] = id;
	root->tpinch.x[1] = x;
	root->tpinch.y[1] = y;
	root->tpinch.d0 = d;
	root->tpinch.mx = mx;
	root->tpinch.my = my;
	touch_let_go(root, first);
	return true;
}

/* Which of the pinch's two fingers it is, or -1 */
static int tpinch_finger(struct c8ui_root *root, int32_t id) {
	return id == root->tpinch.id[0] ? 0 : id == root->tpinch.id[1] ? 1 : -1;
}

/* A pinching finger moved (true), or isn't one (false) */
static bool tpinch_motion(struct c8ui_root *root, int32_t id, double x,
		double y) {
	if (id == root->tpinch.leftover) {
		return true;
	}
	if (!root->tpinch.on) {
		return false;
	}
	int k = tpinch_finger(root, id);
	if (k < 0) {
		return false;
	}
	root->tpinch.x[k] = x;
	root->tpinch.y[k] = y;
	c8ui_dispatch_begin(root);
	tpinch_send(root, C8UI_EVENT_PINCH_UPDATE, false);
	c8ui_dispatch_end(root);
	return true;
}

static bool tpinch_up(struct c8ui_root *root, int32_t id) {
	if (id == root->tpinch.leftover) {
		root->tpinch.leftover = -1;
		return true;
	}
	if (!root->tpinch.on) {
		return false;
	}
	int k = tpinch_finger(root, id);
	if (k < 0) {
		return false;
	}
	root->tpinch.on = false;
	root->tpinch.leftover = root->tpinch.id[1 - k];
	c8ui_dispatch_begin(root);
	tpinch_send(root, C8UI_EVENT_PINCH_END, false);
	c8ui_dispatch_end(root);
	return true;
}

void c8ui_root_touch_down(struct c8ui_root *root, int32_t id, uint32_t time,
		double x, double y) {
	if (root->needs_layout) {
		do_layout(root);
	}
	c8ui_dispatch_begin(root);
	if (tpinch_begin(root, id, x, y)) {
		goto out;
	}
	if (root->tpinch.on) {
		goto out; // a third finger: the pinch has the screen
	}
	struct c8ui_event ev = { .type = C8UI_EVENT_TOUCH_DOWN, .x = x, .y = y,
		.touch_id = id, .time = time };
	int slot = 0;
	while (slot < TOUCHES && root->touches[slot].owner) {
		slot++;
	}
	if (slot < TOUCHES && root->grab == NULL) {
		for (struct c8ui_widget *w = hit(top_layer(root), x, y); w;
				w = w->parent) {
			if (send(w, &ev)) {
				if (w->root == root) {
					root->touches[slot].id = id;
					root->touches[slot].owner = w;
					root->touches[slot].x = x;
					root->touches[slot].y = y;
				}
				goto out;
			}
			if (w->root != root) {
				goto out;
			}
		}
	}
	if (root->touch_mouse < 0 && root->grab == NULL) {
		root->touch_mouse = id;
		root->mouse_x = root->px = x;
		root->mouse_y = root->py = y;
		root->pointer_in = true;
		update_hover(root);
		struct c8ui_event motion = { .type = C8UI_EVENT_MOTION, .x = x,
			.y = y };
		send(root->hover, &motion);
		pointer_button(root, C8UI_BUTTON_LEFT, true);
	}
out:
	c8ui_dispatch_end(root);
}

void c8ui_root_touch_motion(struct c8ui_root *root, int32_t id, uint32_t time,
		double x, double y) {
	if (tpinch_motion(root, id, x, y)) {
		return;
	}
	if (id == root->touch_mouse) {
		root->mouse_x = x;
		root->mouse_y = y;
		c8ui_root_pointer_motion(root, x, y);
		return;
	}
	int slot = touch_slot(root, id);
	if (slot < 0) {
		return;
	}
	root->touches[slot].x = x;
	root->touches[slot].y = y;
	struct c8ui_event ev = { .type = C8UI_EVENT_TOUCH_MOTION, .x = x, .y = y,
		.touch_id = id, .time = time };
	c8ui_dispatch_begin(root);
	send(root->touches[slot].owner, &ev);
	c8ui_dispatch_end(root);
}

void c8ui_root_touch_up(struct c8ui_root *root, int32_t id, uint32_t time) {
	if (tpinch_up(root, id)) {
		return;
	}
	c8ui_dispatch_begin(root);
	if (id == root->touch_mouse) {
		pointer_button(root, C8UI_BUTTON_LEFT, false);
		touch_mouse_end(root);
	} else {
		int slot = touch_slot(root, id);
		if (slot >= 0) {
			touch_end(root, slot, C8UI_EVENT_TOUCH_UP, time);
		}
	}
	c8ui_dispatch_end(root);
}

void c8ui_root_touch_cancel(struct c8ui_root *root) {
	c8ui_dispatch_begin(root);
	root->tpinch.leftover = -1;
	if (root->tpinch.on) {
		root->tpinch.on = false;
		tpinch_send(root, C8UI_EVENT_PINCH_END, true);
	}
	for (int i = 0; i < TOUCHES; i++) {
		if (root->touches[i].owner) {
			touch_end(root, i, C8UI_EVENT_TOUCH_CANCEL, 0);
		}
	}
	if (root->touch_mouse >= 0) {
		touch_mouse_drop(root);
	}
	c8ui_dispatch_end(root);
}

static void dispatch_scroll(struct c8ui_root *root, struct c8ui_event *ev) {
	tip_dismiss(root);
	c8ui_dispatch_begin(root);
	for (struct c8ui_widget *w = hit(top_layer(root), root->px, root->py); w;
			w = w->parent) {
		if (send(w, ev) || w->root != root) {
			break;
		}
	}
	update_hover(root);
	c8ui_dispatch_end(root);
}

void c8ui_root_pointer_scroll(struct c8ui_root *root, double dx, double dy,
		bool precise, uint32_t mods) {
	struct c8ui_event ev = { .type = C8UI_EVENT_SCROLL, .x = root->px,
		.y = root->py, .dx = dx, .dy = dy, .precise = precise, .mods = mods };
	dispatch_scroll(root, &ev);
}

void c8ui_root_pointer_scroll_stop(struct c8ui_root *root) {
	struct c8ui_event ev = { .type = C8UI_EVENT_SCROLL_STOP, .x = root->px,
		.y = root->py, .precise = true };
	dispatch_scroll(root, &ev);
}

/* A swipe goes to whoever took its beginning, wherever the pointer is */
void c8ui_root_swipe_begin(struct c8ui_root *root, int fingers) {
	struct c8ui_event ev = { .type = C8UI_EVENT_SWIPE_BEGIN, .x = root->px,
		.y = root->py, .fingers = fingers, .precise = true };
	root->swipe = NULL;
	root->swipe_fingers = fingers;
	c8ui_dispatch_begin(root);
	for (struct c8ui_widget *w = hit(top_layer(root), root->px, root->py); w;
			w = w->parent) {
		if (send(w, &ev)) {
			/* Not one that went while taking it: it is freed when this
			 * dispatch ends, and the updates would go to it */
			if (w->root == root) {
				root->swipe = w;
			}
			break;
		}
		if (w->root != root) {
			break;
		}
	}
	c8ui_dispatch_end(root);
}

void c8ui_root_swipe_update(struct c8ui_root *root, double dx, double dy) {
	if (root->swipe == NULL) {
		return;
	}
	struct c8ui_event ev = { .type = C8UI_EVENT_SWIPE_UPDATE, .x = root->px,
		.y = root->py, .dx = dx, .dy = dy, .fingers = root->swipe_fingers,
		.precise = true };
	c8ui_dispatch_begin(root);
	send(root->swipe, &ev);
	c8ui_dispatch_end(root);
}

void c8ui_root_swipe_end(struct c8ui_root *root, bool cancelled) {
	struct c8ui_widget *w = root->swipe;
	root->swipe = NULL;
	if (w == NULL) {
		return;
	}
	struct c8ui_event ev = { .type = C8UI_EVENT_SWIPE_END, .x = root->px,
		.y = root->py, .fingers = root->swipe_fingers, .precise = true,
		.cancelled = cancelled };
	c8ui_dispatch_begin(root);
	send(w, &ev);
	c8ui_dispatch_end(root);
}

bool c8ui_tab_swipe(struct c8ui_tab_swipe *s, const struct c8ui_event *ev,
		int *step) {
	*step = 0;
	switch (ev->type) {
	case C8UI_EVENT_SWIPE_BEGIN:
		s->dx = s->dy = 0;
		s->done = false;
		return ev->fingers >= 3;
	case C8UI_EVENT_SWIPE_UPDATE:
		s->dx += ev->dx;
		s->dy += ev->dy;
		if (!s->done && fabs(s->dx) >= C8UI_TAB_SWIPE &&
				fabs(s->dx) >= 2 * fabs(s->dy)) {
			s->done = true;
			*step = s->dx < 0 ? 1 : -1;
		}
		return true;
	case C8UI_EVENT_SWIPE_END:
		return true;
	default:
		return false;
	}
}

/* A pinch, like a swipe, goes to whoever took its beginning */
void c8ui_root_pinch_begin(struct c8ui_root *root, int fingers) {
	if (root->tpinch.on) {
		return; // the screen's pinch has it
	}
	struct c8ui_event ev = { .type = C8UI_EVENT_PINCH_BEGIN, .x = root->px,
		.y = root->py, .fingers = fingers, .precise = true, .scale = 1 };
	root->pinch = NULL;
	root->pinch_fingers = fingers;
	tip_dismiss(root);
	c8ui_dispatch_begin(root);
	for (struct c8ui_widget *w = hit(top_layer(root), root->px, root->py); w;
			w = w->parent) {
		if (send(w, &ev)) {
			/* Not one that went while taking it: it is freed when this
			 * dispatch ends, and the updates would go to it */
			if (w->root == root) {
				root->pinch = w;
			}
			break;
		}
		if (w->root != root) {
			break;
		}
	}
	c8ui_dispatch_end(root);
}

void c8ui_root_pinch_update(struct c8ui_root *root, double dx, double dy,
		double scale) {
	if (root->tpinch.on) {
		return;
	}
	if (root->pinch == NULL) {
		return;
	}
	struct c8ui_event ev = { .type = C8UI_EVENT_PINCH_UPDATE, .x = root->px,
		.y = root->py, .dx = dx, .dy = dy, .scale = scale,
		.fingers = root->pinch_fingers, .precise = true };
	c8ui_dispatch_begin(root);
	send(root->pinch, &ev);
	c8ui_dispatch_end(root);
}

void c8ui_root_pinch_end(struct c8ui_root *root, bool cancelled) {
	if (root->tpinch.on) {
		return;
	}
	struct c8ui_widget *w = root->pinch;
	root->pinch = NULL;
	if (w == NULL) {
		return;
	}
	struct c8ui_event ev = { .type = C8UI_EVENT_PINCH_END, .x = root->px,
		.y = root->py, .fingers = root->pinch_fingers, .precise = true,
		.cancelled = cancelled, .scale = 1 };
	c8ui_dispatch_begin(root);
	send(w, &ev);
	c8ui_dispatch_end(root);
}

static bool in_tree(struct c8ui_widget *w, struct c8ui_widget *tree) {
	for (; w; w = w->parent) {
		if (w == tree) {
			return true;
		}
	}
	return false;
}

static void collect_focusable(struct c8ui_widget *w, struct c8ui_widget ***list,
		int *count, int *cap) {
	if (w->hidden || w->disabled) {
		return;
	}
	if (w->focusable) {
		if (*count == *cap) {
			*cap = *cap ? *cap * 2 : 32;
			*list = realloc(*list, sizeof(**list) * *cap);
		}
		(*list)[(*count)++] = w;
	}
	for (int i = 0; i < w->child_count; i++) {
		collect_focusable(w->children[i], list, count, cap);
	}
}

static void focus_step(struct c8ui_root *root, int dir) {
	struct c8ui_widget *layer = top_layer(root);
	if (layer == NULL) {
		return;
	}
	struct c8ui_widget **list = NULL;
	int count = 0, cap = 0;
	collect_focusable(layer, &list, &count, &cap);
	if (count > 0) {
		int at = -1;
		for (int i = 0; i < count; i++) {
			if (list[i] == root->focus) {
				at = i;
			}
		}
		int next = at < 0 ? (dir > 0 ? 0 : count - 1) :
			(at + dir + count) % count;
		c8ui_root_show_focus(root, true);
		c8ui_root_set_focus(root, list[next]);
	}
	free(list);
}

static void key(struct c8ui_root *root, uint32_t sym, uint32_t base_sym,
		uint32_t mods, const char *text);

void c8ui_root_key(struct c8ui_root *root, uint32_t sym, uint32_t base_sym,
		uint32_t mods, const char *text) {
	c8ui_dispatch_begin(root);
	key(root, sym, base_sym, mods, text);
	c8ui_dispatch_end(root);
}

static void key(struct c8ui_root *root, uint32_t sym, uint32_t base_sym,
		uint32_t mods, const char *text) {
	struct c8ui_event ev = { .type = C8UI_EVENT_KEY, .sym = sym,
		.base_sym = base_sym ? base_sym : sym, .mods = mods,
		.text = text && text[0] ? text : NULL };
	tip_dismiss(root);
	struct c8ui_widget *layer = top_layer(root);
	struct c8ui_widget *start = root->focus && in_tree(root->focus, layer) ?
		root->focus : layer;
	int overlays = root->overlay_count;
	for (struct c8ui_widget *w = start; w; w = w->parent) {
		if (send(w, &ev)) {
			return;
		}
		if (root->overlay_count != overlays || w->root != root) {
			return; /* what we were in went away */
		}
	}
	if (((sym == XKB_KEY_Left && mods == C8UI_MOD_ALT) ||
			sym == XKB_KEY_XF86Back) && back_shown(root)) {
		c8ui_back_activate(root->back);
		return;
	}
	if (root->key_fn && root->key_fn(&ev, root->key_data)) {
		return;
	}
	if (sym == XKB_KEY_Tab || sym == XKB_KEY_ISO_Left_Tab) {
		focus_step(root, (mods & C8UI_MOD_SHIFT) ? -1 : 1);
	}
}

void c8ui_root_set_key_handler(struct c8ui_root *root, c8ui_key_fn fn,
		void *data) {
	root->key_fn = fn;
	root->key_data = data;
}

void c8ui_root_keyboard_focus(struct c8ui_root *root, bool focused) {
	root->keyboard_focused = focused;
	damage_all(root);
}

static void reveal(struct c8ui_widget *w) {
	c8ui_widget_reveal(w, &w->rect);
}

static void set_focus(struct c8ui_root *root, struct c8ui_widget *w);

void c8ui_root_set_focus(struct c8ui_root *root, struct c8ui_widget *w) {
	c8ui_dispatch_begin(root);
	set_focus(root, w);
	c8ui_dispatch_end(root);
}

static void set_focus(struct c8ui_root *root, struct c8ui_widget *w) {
	if (root->focus == w) {
		return;
	}
	struct c8ui_widget *old = root->focus;
	root->focus = w;
	if (old) {
		old->focused = false;
		struct c8ui_event ev = { .type = C8UI_EVENT_FOCUS_OUT };
		send(old, &ev);
		c8ui_widget_queue_draw(old);
	}
	if (w && root->focus == w) {
		w->focused = true;
		struct c8ui_event ev = { .type = C8UI_EVENT_FOCUS_IN };
		send(w, &ev);
		if (root->focus_visible) {
			reveal(w);
		}
		c8ui_widget_queue_draw(w);
	}
}

struct c8ui_widget *c8ui_root_focus(struct c8ui_root *root) {
	return root->focus;
}

static void push_overlay(struct c8ui_root *root, struct c8ui_widget *overlay,
		bool keep_focus);

void c8ui_root_push_overlay(struct c8ui_root *root, struct c8ui_widget *overlay) {
	push_overlay(root, overlay, false);
}

void c8ui_root_push_popup(struct c8ui_root *root, struct c8ui_widget *popup) {
	push_overlay(root, popup, true);
}

void c8ui_root_repress(struct c8ui_root *root) {
	root->repress = true;
}

static void push_overlay(struct c8ui_root *root, struct c8ui_widget *overlay,
		bool keep_focus) {
	if (root->overlay_count == root->overlay_cap) {
		root->overlay_cap = root->overlay_cap ? root->overlay_cap * 2 : 4;
		root->overlays = realloc(root->overlays,
			sizeof(*root->overlays) * root->overlay_cap);
		root->saved_focus = realloc(root->saved_focus,
			sizeof(*root->saved_focus) * root->overlay_cap);
		root->popups = realloc(root->popups,
			sizeof(*root->popups) * root->overlay_cap);
	}
	root->popups[root->overlay_count] = keep_focus;
	struct c8ui_widget *focus = NULL;
	if (!keep_focus) {
		focus = root->focus;
		c8ui_root_set_focus(root, NULL);
	}
	root->saved_focus[root->overlay_count] = focus;
	root->overlays[root->overlay_count++] = overlay;
	set_root(overlay, root);
	grab_end(root);
	root->needs_layout = true;
	damage_all(root);
	do_layout(root);
}

void c8ui_root_remove_overlay(struct c8ui_root *root,
		struct c8ui_widget *overlay) {
	for (int i = 0; i < root->overlay_count; i++) {
		if (root->overlays[i] != overlay) {
			continue;
		}
		struct c8ui_widget *focus = root->saved_focus[i];
		forget_tree(root, overlay);
		memmove(&root->overlays[i], &root->overlays[i + 1],
			sizeof(*root->overlays) * (root->overlay_count - i - 1));
		memmove(&root->saved_focus[i], &root->saved_focus[i + 1],
			sizeof(*root->saved_focus) * (root->overlay_count - i - 1));
		memmove(&root->popups[i], &root->popups[i + 1],
			sizeof(*root->popups) * (root->overlay_count - i - 1));
		root->overlay_count--;
		if (focus) {
			c8ui_root_set_focus(root, focus);
		}
		root->needs_layout = true;
		damage_all(root);
		return;
	}
}

void *c8ui_root_timer_add(struct c8ui_root *root, int ms, c8ui_timer_fn fn,
		void *data) {
	return root->impl->timer_add(root->host, ms, fn, data);
}

void c8ui_root_timer_remove(struct c8ui_root *root, void *timer) {
	if (timer) {
		root->impl->timer_remove(root->host, timer);
	}
}

void c8ui_root_inhibit_shortcuts(struct c8ui_root *root, bool inhibit) {
	if (root->impl->inhibit_shortcuts) {
		root->impl->inhibit_shortcuts(root->host, inhibit);
	}
}

void c8ui_root_set_clipboard(struct c8ui_root *root, const char *text) {
	if (root->impl->set_clipboard) {
		root->impl->set_clipboard(root->host, text);
	}
}

void c8ui_root_request_paste(struct c8ui_root *root, c8ui_paste_fn fn,
		void *data) {
	if (root->impl->request_paste) {
		root->impl->request_paste(root->host, fn, data);
	}
}

/* Boxes */

struct box {
	enum c8ui_orientation orientation;
	double spacing;
	double pad[4]; // left, top, right, bottom
	bool wrap;
	/* spacing and pad are what is in use; these are what they are
	 * wide and narrow (the narrow ones the wide ones unless set) */
	double wide_spacing, narrow_spacing;
	double wide_pad[4], narrow_pad[4];
	enum c8ui_orientation wide_orientation, narrow_orientation;
	bool has_narrow_spacing, has_narrow_pad, has_narrow_orientation;
};

static void box_apply(struct c8ui_widget *w) {
	struct box *box = w->data;
	bool n = w->narrow;
	box->spacing = n && box->has_narrow_spacing ?
		box->narrow_spacing : box->wide_spacing;
	memcpy(box->pad, n && box->has_narrow_pad ? box->narrow_pad :
		box->wide_pad, sizeof(box->pad));
	box->orientation = n && box->has_narrow_orientation ?
		box->narrow_orientation : box->wide_orientation;
	c8ui_widget_queue_layout(w);
}

static void box_narrow(struct c8ui_widget *w, bool narrow) {
	(void)narrow;
	box_apply(w);
}

/* Where a child of that width starts in the room there is across the
 * box, by its alignment (down a horizontal box as well) */
static double child_x(struct c8ui_widget *child, double x, double avail,
		double width) {
	if (child->align == C8UI_ALIGN_CENTER) {
		return x + (avail - width) / 2;
	} else if (child->align == C8UI_ALIGN_END) {
		return x + avail - width;
	}
	return x;
}

/* Widths along a horizontal box: fixed ones first, then the expanding
 * ones share the rest */
static void row_widths(struct c8ui_widget *w, double inner, double *widths,
		double *heights) {
	struct box *box = w->data;
	double used = 0;
	int expanders = 0, shown = 0;
	for (int i = 0; i < w->child_count; i++) {
		struct c8ui_widget *c = w->children[i];
		widths[i] = heights[i] = 0;
		if (c->hidden) {
			continue;
		}
		shown++;
		if (c->expand) {
			expanders++;
			continue;
		}
		c8ui_widget_measure(c, inner - used > 0 ? inner - used : 0,
			&widths[i], &heights[i]);
		used += widths[i];
	}
	used += box->spacing * (shown > 1 ? shown - 1 : 0);
	double share = expanders ? (inner - used) / expanders : 0;
	if (share < 0) {
		share = 0;
	}
	for (int i = 0; i < w->child_count; i++) {
		struct c8ui_widget *c = w->children[i];
		if (!c->hidden && c->expand) {
			double cw;
			c8ui_widget_measure(c, share, &cw, &heights[i]);
			widths[i] = share;
		}
	}
}

static void box_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct box *box = w->data;
	double inner = avail - box->pad[0] - box->pad[2];
	if (inner < 0) {
		inner = 0;
	}
	double mw = 0, mh = 0;
	int shown = 0;
	if (box->orientation == C8UI_VERTICAL) {
		for (int i = 0; i < w->child_count; i++) {
			struct c8ui_widget *c = w->children[i];
			if (c->hidden) {
				continue;
			}
			double cw, ch;
			c8ui_widget_measure(c, inner, &cw, &ch);
			mw = cw > mw ? cw : mw;
			mh += ch + (shown++ ? box->spacing : 0);
		}
	} else if (box->wrap) {
		double x = 0, row_h = 0;
		for (int i = 0; i < w->child_count; i++) {
			struct c8ui_widget *c = w->children[i];
			if (c->hidden) {
				continue;
			}
			double cw, ch;
			c8ui_widget_measure(c, inner, &cw, &ch);
			if (x > 0 && x + cw > inner) {
				mh += row_h + box->spacing;
				x = 0;
				row_h = 0;
			}
			x += cw + box->spacing;
			mw = x - box->spacing > mw ? x - box->spacing : mw;
			row_h = ch > row_h ? ch : row_h;
		}
		mh += row_h;
	} else {
		double *widths = calloc(w->child_count + 1, sizeof(double));
		double *heights = calloc(w->child_count + 1, sizeof(double));
		row_widths(w, inner, widths, heights);
		bool expanding = false;
		for (int i = 0; i < w->child_count; i++) {
			if (w->children[i]->hidden) {
				continue;
			}
			expanding |= w->children[i]->expand;
			mw += widths[i] + (shown++ ? box->spacing : 0);
			mh = heights[i] > mh ? heights[i] : mh;
		}
		if (expanding) {
			mw = inner;
		}
		free(widths);
		free(heights);
	}
	*width = mw + box->pad[0] + box->pad[2];
	*height = mh + box->pad[1] + box->pad[3];
}

static void box_layout(struct c8ui_widget *w) {
	struct box *box = w->data;
	struct c8ui_rect in = {
		w->rect.x + box->pad[0], w->rect.y + box->pad[1],
		w->rect.width - box->pad[0] - box->pad[2],
		w->rect.height - box->pad[1] - box->pad[3],
	};
	if (in.width < 0) {
		in.width = 0;
	}
	if (in.height < 0) {
		in.height = 0;
	}
	int n = w->child_count;
	double *widths = calloc(n + 1, sizeof(double));
	double *heights = calloc(n + 1, sizeof(double));

	if (box->orientation == C8UI_VERTICAL) {
		double total = 0;
		int expanders = 0, shown = 0;
		for (int i = 0; i < n; i++) {
			struct c8ui_widget *c = w->children[i];
			if (c->hidden) {
				continue;
			}
			c8ui_widget_measure(c, in.width, &widths[i], &heights[i]);
			total += heights[i] + (shown++ ? box->spacing : 0);
			expanders += c->expand;
		}
		double extra = expanders && in.height > total ?
			(in.height - total) / expanders : 0;
		double y = in.y;
		for (int i = 0; i < n; i++) {
			struct c8ui_widget *c = w->children[i];
			if (c->hidden) {
				continue;
			}
			double h = heights[i] + (c->expand ? extra : 0);
			double cw = c->fill ? in.width :
				(widths[i] < in.width ? widths[i] : in.width);
			c8ui_widget_layout(c, (struct c8ui_rect){
				child_x(c, in.x, in.width, cw), y, cw, h });
			y += h + box->spacing;
		}
	} else if (box->wrap) {
		double x = in.x, y = in.y, row_h = 0;
		for (int i = 0; i < n; i++) {
			struct c8ui_widget *c = w->children[i];
			if (c->hidden) {
				continue;
			}
			double cw, ch;
			c8ui_widget_measure(c, in.width, &cw, &ch);
			if (x > in.x && x + cw > in.x + in.width) {
				x = in.x;
				y += row_h + box->spacing;
				row_h = 0;
			}
			c8ui_widget_layout(c, (struct c8ui_rect){ x, y, cw, ch });
			x += cw + box->spacing;
			row_h = ch > row_h ? ch : row_h;
		}
	} else {
		row_widths(w, in.width, widths, heights);
		double x = in.x;
		for (int i = 0; i < n; i++) {
			struct c8ui_widget *c = w->children[i];
			if (c->hidden) {
				continue;
			}
			double h = c->fill ? in.height :
				(heights[i] < in.height ? heights[i] : in.height);
			/* A filled one is the full height, so any alignment
			 * leaves it at the top */
			double y = child_x(c, in.y, in.height, h);
			c8ui_widget_layout(c, (struct c8ui_rect){ x, y, widths[i], h });
			x += widths[i] + box->spacing;
		}
	}
	free(widths);
	free(heights);
}

static void free_data(struct c8ui_widget *w) {
	free(w->data);
}

static const struct c8ui_widget_impl box_impl = {
	.name = "box",
	.measure = box_measure,
	.layout = box_layout,
	.destroy = free_data,
	.narrow = box_narrow,
};

struct c8ui_widget *c8ui_box_new(enum c8ui_orientation orientation,
		double spacing) {
	struct box *box = calloc(1, sizeof(*box));
	box->orientation = box->wide_orientation = orientation;
	box->spacing = box->wide_spacing = spacing;
	return c8ui_widget_new(&box_impl, box);
}

void c8ui_box_set_padding(struct c8ui_widget *w, double left, double top,
		double right, double bottom) {
	struct box *box = w->data;
	box->wide_pad[0] = left;
	box->wide_pad[1] = top;
	box->wide_pad[2] = right;
	box->wide_pad[3] = bottom;
	box_apply(w);
}

void c8ui_box_set_narrow_padding(struct c8ui_widget *w, double left,
		double top, double right, double bottom) {
	struct box *box = w->data;
	box->narrow_pad[0] = left;
	box->narrow_pad[1] = top;
	box->narrow_pad[2] = right;
	box->narrow_pad[3] = bottom;
	box->has_narrow_pad = true;
	box_apply(w);
}

void c8ui_box_set_narrow_spacing(struct c8ui_widget *w, double spacing) {
	struct box *box = w->data;
	box->narrow_spacing = spacing;
	box->has_narrow_spacing = true;
	box_apply(w);
}

void c8ui_box_set_narrow_orientation(struct c8ui_widget *w,
		enum c8ui_orientation orientation) {
	struct box *box = w->data;
	box->narrow_orientation = orientation;
	box->has_narrow_orientation = true;
	box_apply(w);
}

void c8ui_box_set_wrap(struct c8ui_widget *w, bool wrap) {
	struct box *box = w->data;
	box->wrap = wrap;
	c8ui_widget_queue_layout(w);
}

/* Spacer */

static const struct c8ui_widget_impl spacer_impl = { .name = "spacer" };

struct c8ui_widget *c8ui_spacer_new(double width, double height) {
	struct c8ui_widget *w = c8ui_widget_new(&spacer_impl, NULL);
	w->fixed_width = width;
	w->fixed_height = height;
	return w;
}

/* Fingers dragging */

/* A finger on something that pans along one axis (scrolls, hubs, pivots).
 * Dragged along it pans; one that stays put is a click where it lifted
 * (held: a right click). One that sets off the other way is offered to
 * the widgets around (a vertical list in a sideways hub), and if none
 * takes it, it acts as the mouse, so sliders and text selection still
 * work by touch. */
#define DRAG_SLOP 8
#define HOLD_MS 550

/* A click (press and release) at x, y as a finger would make it, which
 * leaves nothing hovered */
static void touch_click(struct c8ui_root *root, double x, double y,
		uint32_t button) {
	root->px = x;
	root->py = y;
	root->pointer_in = true;
	update_hover(root);
	struct c8ui_event motion = { .type = C8UI_EVENT_MOTION, .x = x, .y = y };
	send(root->hover, &motion);
	pointer_button(root, button, true);
	pointer_button(root, button, false);
	root->pointer_in = false;
	update_hover(root);
}

static void drag_stop_hold(struct c8ui_drag *d) {
	if (d->hold) {
		c8ui_root_timer_remove(d->hold_root, d->hold);
		d->hold = NULL;
	}
}

void c8ui_drag_finish(struct c8ui_drag *d) {
	drag_stop_hold(d);
}

static int drag_held(void *data) {
	struct c8ui_drag *d = data;
	struct c8ui_root *root = d->hold_root;
	d->hold = NULL;
	d->held = true;
	c8ui_dispatch_begin(root);
	touch_click(root, d->x0, d->y0, C8UI_BUTTON_RIGHT);
	c8ui_dispatch_end(root);
	return 0;
}

/* The finger went the other way: offer it to the widgets around w, as if
 * it had just landed, else it becomes the mouse pressed where it landed */
static void drag_hand_off(struct c8ui_widget *w, struct c8ui_drag *d,
		const struct c8ui_event *ev) {
	struct c8ui_root *root = w->root;
	d->down = false;
	drag_stop_hold(d);
	int slot = touch_slot(root, ev->touch_id);
	if (slot < 0) {
		return;
	}
	struct c8ui_event down = { .type = C8UI_EVENT_TOUCH_DOWN, .x = d->x0,
		.y = d->y0, .touch_id = ev->touch_id, .time = ev->time };
	for (struct c8ui_widget *p = w->parent; p; p = p->parent) {
		if (send(p, &down)) {
			if (p->root != root) {
				return;
			}
			root->touches[slot].owner = p;
			struct c8ui_event motion = *ev;
			send(p, &motion);
			return;
		}
		if (p->root != root) {
			return;
		}
	}
	root->touches[slot].owner = NULL;
	if (root->touch_mouse >= 0 || root->grab) {
		return;
	}
	root->touch_mouse = ev->touch_id;
	root->px = d->x0;
	root->py = d->y0;
	root->pointer_in = true;
	update_hover(root);
	struct c8ui_event motion = { .type = C8UI_EVENT_MOTION,
		.x = root->px, .y = root->py };
	send(root->hover, &motion);
	pointer_button(root, C8UI_BUTTON_LEFT, true);
	c8ui_root_pointer_motion(root, ev->x, ev->y);
}

enum c8ui_drag_state c8ui_drag_touch(struct c8ui_widget *w,
		struct c8ui_drag *d, const struct c8ui_event *ev) {
	bool vertical = d->axis == C8UI_VERTICAL;
	switch (ev->type) {
	case C8UI_EVENT_TOUCH_DOWN:
		if (d->down) {
			return C8UI_DRAG_IGNORED; // one finger at a time
		}
		d->down = true;
		d->active = d->held = false;
		d->id = ev->touch_id;
		d->x0 = ev->x;
		d->y0 = ev->y;
		d->last = vertical ? ev->y : ev->x;
		d->last_time = ev->time;
		d->delta = d->velocity = 0;
		d->dx = d->dy = d->vx = d->vy = 0;
		d->last_x = ev->x;
		d->last_y = ev->y;
		drag_stop_hold(d);
		d->hold_root = w->root;
		d->hold = c8ui_root_timer_add(w->root, HOLD_MS, drag_held, d);
		return C8UI_DRAG_TAKEN;
	case C8UI_EVENT_TOUCH_MOTION: {
		if (!d->down || ev->touch_id != d->id || d->held) {
			return C8UI_DRAG_TAKEN;
		}
		double along = vertical ? ev->y - d->y0 : ev->x - d->x0;
		double across = vertical ? ev->x - d->x0 : ev->y - d->y0;
		bool starting = false;
		if (!d->active) {
			if (fabs(along) < DRAG_SLOP && fabs(across) < DRAG_SLOP) {
				return C8UI_DRAG_TAKEN;
			}
			if (!d->both && fabs(across) > fabs(along)) {
				drag_hand_off(w, d, ev);
				return C8UI_DRAG_TAKEN;
			}
			d->active = starting = true;
			drag_stop_hold(d);
		}
		double pos = vertical ? ev->y : ev->x;
		uint32_t dt = ev->time - d->last_time;
		if (dt > 0) {
			double v = (pos - d->last) / dt;
			d->velocity = d->velocity * 0.4 + v * 0.6;
			d->vx = d->vx * 0.4 + (ev->x - d->last_x) / dt * 0.6;
			d->vy = d->vy * 0.4 + (ev->y - d->last_y) / dt * 0.6;
		}
		d->last = pos;
		d->last_x = ev->x;
		d->last_y = ev->y;
		d->dx = ev->x - d->x0;
		d->dy = ev->y - d->y0;
		d->last_time = ev->time;
		d->delta = along;
		return starting ? C8UI_DRAG_START : C8UI_DRAG_MOVE;
	}
	case C8UI_EVENT_TOUCH_UP:
		if (!d->down || ev->touch_id != d->id) {
			return C8UI_DRAG_TAKEN;
		}
		d->down = false;
		drag_stop_hold(d);
		if (d->active) {
			d->active = false;
			/* A finger that stopped before lifting does not fling */
			if (ev->time - d->last_time > 80) {
				d->velocity = d->vx = d->vy = 0;
			}
			return C8UI_DRAG_END;
		}
		if (!d->held && w->root) {
			/* Last: the click may destroy w (not freed till after) */
			touch_click(w->root, d->x0, d->y0, C8UI_BUTTON_LEFT);
		}
		return C8UI_DRAG_TAKEN;
	case C8UI_EVENT_TOUCH_CANCEL: {
		bool was = d->down && d->active;
		d->down = d->active = false;
		drag_stop_hold(d);
		return was ? C8UI_DRAG_CANCEL : C8UI_DRAG_TAKEN;
	}
	default:
		return C8UI_DRAG_IGNORED;
	}
}

/* Revealing */

void c8ui_widget_reveal(struct c8ui_widget *w, const struct c8ui_rect *rect) {
	struct c8ui_rect r = *rect;
	for (struct c8ui_widget *p = w->parent; p; p = p->parent) {
		if (p->impl->reveal) {
			p->impl->reveal(p, &r);
			/* Then whatever p is in shows p */
			r = p->rect;
		}
	}
}

/* Touchpad kinetic scrolling: the speed of a swipe, kept while its scroll
 * events come, and what it carries on to when the fingers lift */

#define KINETIC_GAP_MS 120 // scrolls further apart than this aren't one swipe
#define KINETIC_MIN 0.05 // px/ms: slower than this lifts without coasting
#define KINETIC_MAX 3000 // px a swipe may carry on
#define KINETIC_MS 320 // how far: its speed times this

void c8ui_pad_reset(struct c8ui_pad *pad) {
	pad->vx = pad->vy = 0;
	pad->last = 0;
}

void c8ui_pad_sample(struct c8ui_pad *pad, double dx, double dy) {
	int64_t now = c8ui_now_ms();
	int64_t dt = pad->last ? now - pad->last : 0;
	if (pad->last == 0 || dt > KINETIC_GAP_MS) {
		pad->vx = pad->vy = 0;
		dt = 0;
	}
	pad->last = now;
	if (dt > 0) {
		double t = dt < 4 ? 4 : dt;
		pad->vx = pad->vx * 0.4 + dx / t * 0.6;
		pad->vy = pad->vy * 0.4 + dy / t * 0.6;
	}
}

bool c8ui_pad_lift(struct c8ui_pad *pad, double *vx, double *vy) {
	bool moving = pad->last && c8ui_now_ms() - pad->last < KINETIC_GAP_MS;
	*vx = fabs(pad->vx) > KINETIC_MIN ? pad->vx : 0;
	*vy = fabs(pad->vy) > KINETIC_MIN ? pad->vy : 0;
	c8ui_pad_reset(pad);
	return moving && (*vx != 0 || *vy != 0);
}

double c8ui_pad_distance(double v) {
	double d = v * KINETIC_MS;
	return d < -KINETIC_MAX ? -KINETIC_MAX : d > KINETIC_MAX ? KINETIC_MAX : d;
}

/* Scroll */

#define FLING_MS 320 // how far a flick carries: its speed times this
#define SCROLL_NATURAL 100000 // measuring sideways: room to be as wide as it is

/* One direction of a scroll */
struct scroll_axis {
	double offset, target;
	double content; // the child's size this way
};

struct scroll {
	bool horizontal, vertical; // the ways it scrolls
	/* What they are wide and narrow (c8ui_scroll_set_narrow_directions) */
	bool wide_h, wide_v, narrow_h, narrow_v, has_narrow;
	struct scroll_axis x, y;
	struct c8ui_drag drag;
	double drag_x, drag_y; // where the finger took it from
	struct c8ui_pad pad; // touchpad scrolling coasts on after the fingers lift
};

static double axis_size(struct c8ui_widget *w, bool horizontal) {
	return horizontal ? w->rect.width : w->rect.height;
}

static double axis_max(struct c8ui_widget *w, bool horizontal) {
	struct scroll *s = w->data;
	struct scroll_axis *a = horizontal ? &s->x : &s->y;
	double max = a->content - axis_size(w, horizontal);
	return max > 0 ? max : 0;
}

static void shift_tree(struct c8ui_widget *w, double dx, double dy) {
	w->rect.x += dx;
	w->rect.y += dy;
	for (int i = 0; i < w->child_count; i++) {
		shift_tree(w->children[i], dx, dy);
	}
}

static const struct c8ui_widget_impl scroll_impl;
static void scroll_narrow(struct c8ui_widget *w, bool narrow);

/* In something that scrolls down already, a scroll gives way: it is as
 * tall as what it holds, and the outer one scrolls (News's sections in
 * its narrow column, a list in a page) */
static bool scroll_in_scroll(struct c8ui_widget *w) {
	for (struct c8ui_widget *p = w->parent; p; p = p->parent) {
		if (p->impl == &scroll_impl &&
				((struct scroll *)p->data)->vertical) {
			return true;
		}
	}
	return false;
}

static void scroll_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct scroll *s = w->data;
	*width = avail;
	*height = 0;
	if (w->child_count == 0 || !scroll_in_scroll(w)) {
		return;
	}
	struct c8ui_widget *c = w->children[0];
	double cw = avail, mw;
	if (s->horizontal) {
		double nh;
		c8ui_widget_measure(c, SCROLL_NATURAL, &cw, &nh);
		cw = cw >= SCROLL_NATURAL / 2 || cw < avail ? avail : cw;
	}
	c8ui_widget_measure(c, cw, &mw, height);
}

static void scroll_layout(struct c8ui_widget *w) {
	struct scroll *s = w->data;
	if (w->child_count == 0) {
		return;
	}
	struct c8ui_widget *c = w->children[0];
	double cw = w->rect.width, ch;
	if (s->horizontal) {
		/* As wide as it is, given the room; something that takes all
		 * the room there is gets the scroll's width */
		double nw, nh;
		c8ui_widget_measure(c, SCROLL_NATURAL, &nw, &nh);
		cw = nw >= SCROLL_NATURAL / 2 ? w->rect.width : nw;
		cw = cw > w->rect.width ? cw : w->rect.width;
	}
	double mw;
	c8ui_widget_measure(c, cw, &mw, &ch);
	s->x.content = cw;
	s->y.content = s->vertical && ch > w->rect.height ? ch : w->rect.height;
	for (int i = 0; i < 2; i++) {
		struct scroll_axis *a = i ? &s->x : &s->y;
		double max = axis_max(w, i);
		a->offset = a->offset > max ? max : a->offset;
		a->target = a->target > max ? max : a->target;
	}
	c8ui_widget_layout(c, (struct c8ui_rect){ w->rect.x - s->x.offset,
		w->rect.y - s->y.offset, s->x.content, s->y.content });
}

static void scroll_set_axis(struct c8ui_widget *w, bool horizontal,
		double offset) {
	struct scroll *s = w->data;
	struct scroll_axis *a = horizontal ? &s->x : &s->y;
	double max = axis_max(w, horizontal);
	offset = offset < 0 ? 0 : offset > max ? max : offset;
	if (offset == a->offset) {
		return;
	}
	if (w->child_count > 0) {
		double d = a->offset - offset;
		shift_tree(w->children[0], horizontal ? d : 0, horizontal ? 0 : d);
	}
	a->offset = offset;
	c8ui_widget_queue_draw(w);
}

static bool scroll_tick(struct c8ui_widget *w, int64_t now) {
	struct scroll *s = w->data;
	bool more = false;
	for (int i = 0; i < 2; i++) {
		struct scroll_axis *a = i ? &s->x : &s->y;
		double d = a->target - a->offset;
		if (fabs(d) < 0.5) {
			scroll_set_axis(w, i, a->target);
		} else {
			scroll_set_axis(w, i, a->offset + d * 0.3);
			more = true;
		}
	}
	return more;
}

static void scroll_by_axis(struct c8ui_widget *w, bool horizontal, double d,
		bool smooth) {
	struct scroll *s = w->data;
	struct scroll_axis *a = horizontal ? &s->x : &s->y;
	double max = axis_max(w, horizontal);
	double base = smooth ? a->target : a->offset;
	a->target = base + d;
	a->target = a->target < 0 ? 0 : a->target > max ? max : a->target;
	if (smooth) {
		c8ui_widget_animate(w);
	} else {
		scroll_set_axis(w, horizontal, a->target);
	}
}

static void scroll_draw(struct c8ui_widget *w, cairo_t *cr) {
	cairo_rectangle(cr, w->rect.x, w->rect.y, w->rect.width, w->rect.height);
	cairo_clip(cr);
}

static void scroll_draw_over(struct c8ui_widget *w, cairo_t *cr) {
	struct scroll *s = w->data;
	/* Thin indicators, as in Metro apps */
	struct c8ui_colors c = c8ui_widget_colors(w);
	c8ui_set_source(cr, c.fg, w->hovered ? 0.4 : 0.2);
	if (s->y.content > w->rect.height + 1) {
		double h = w->rect.height * w->rect.height / s->y.content;
		h = h < 24 ? 24 : h;
		double y = w->rect.y + (w->rect.height - h) * s->y.offset /
			axis_max(w, false);
		cairo_rectangle(cr, w->rect.x + w->rect.width - 6, y, 4, h);
		cairo_fill(cr);
	}
	if (s->x.content > w->rect.width + 1) {
		double l = w->rect.width * w->rect.width / s->x.content;
		l = l < 24 ? 24 : l;
		double x = w->rect.x + (w->rect.width - l) * s->x.offset /
			axis_max(w, true);
		cairo_rectangle(cr, x, w->rect.y + w->rect.height - 6, l, 4);
		cairo_fill(cr);
	}
}

static bool scroll_touch(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct scroll *s = w->data;
	if (ev->type == C8UI_EVENT_TOUCH_DOWN) {
		/* Nothing to pan: let the finger be */
		if ((axis_max(w, false) <= 0 && axis_max(w, true) <= 0) ||
				s->drag.down) {
			return false;
		}
		/* Catch a scroll that is still moving */
		s->x.target = s->x.offset;
		s->y.target = s->y.offset;
		s->drag_x = s->x.offset;
		s->drag_y = s->y.offset;
	}
	switch (c8ui_drag_touch(w, &s->drag, ev)) {
	case C8UI_DRAG_IGNORED:
		return false;
	case C8UI_DRAG_START:
	case C8UI_DRAG_MOVE:
		if (s->horizontal) {
			scroll_set_axis(w, true, s->drag_x - s->drag.dx);
			s->x.target = s->x.offset;
		}
		if (s->vertical) {
			scroll_set_axis(w, false, s->drag_y - s->drag.dy);
			s->y.target = s->y.offset;
		}
		return true;
	case C8UI_DRAG_END:
		if (s->horizontal) {
			scroll_by_axis(w, true, -s->drag.vx * FLING_MS, true);
		}
		if (s->vertical) {
			scroll_by_axis(w, false, -s->drag.vy * FLING_MS, true);
		}
		return true;
	default:
		return true;
	}
}

static bool scroll_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct scroll *s = w->data;
	switch (ev->type) {
	case C8UI_EVENT_TOUCH_DOWN:
	case C8UI_EVENT_TOUCH_MOTION:
	case C8UI_EVENT_TOUCH_UP:
	case C8UI_EVENT_TOUCH_CANCEL:
		return scroll_touch(w, ev);
	case C8UI_EVENT_SCROLL: {
		if (ev->mods & C8UI_MOD_CTRL) {
			return false; // Ctrl+wheel zooms, whatever is around
		}
		double dx = ev->dx, dy = ev->dy;
		/* Shift turns the wheel sideways; with no other way to go, so
		 * does a plain wheel */
		if ((ev->mods & C8UI_MOD_SHIFT) && dx == 0) {
			dx = dy;
			dy = 0;
		}
		if (!s->vertical && dx == 0 && !ev->precise) {
			dx = dy;
		}
		/* Fingers going mostly sideways aren't for a scroll that only goes
		 * up and down: what it is in (a hub of columns) gets them */
		if (ev->precise && !s->horizontal && fabs(dx) > 2 * fabs(dy)) {
			return false;
		}
		if (ev->precise) {
			c8ui_pad_sample(&s->pad, dx, dy);
		} else {
			c8ui_pad_reset(&s->pad);
		}
		bool used = false;
		if (s->horizontal && dx != 0 && axis_max(w, true) > 0) {
			scroll_by_axis(w, true, dx, !ev->precise);
			used = true;
		}
		if (s->vertical && dy != 0 && axis_max(w, false) > 0) {
			scroll_by_axis(w, false, dy, !ev->precise);
			used = true;
		}
		return used;
	}
	case C8UI_EVENT_SCROLL_STOP: {
		/* Fingers lifted while still moving: carry on */
		double vx, vy;
		if (!c8ui_pad_lift(&s->pad, &vx, &vy)) {
			return false;
		}
		bool used = false;
		if (s->horizontal && vx != 0 && axis_max(w, true) > 0) {
			scroll_by_axis(w, true, c8ui_pad_distance(vx), true);
			used = true;
		}
		if (s->vertical && vy != 0 && axis_max(w, false) > 0) {
			scroll_by_axis(w, false, c8ui_pad_distance(vy), true);
			used = true;
		}
		return used;
	}
	case C8UI_EVENT_KEY: {
		if (ev->mods & (C8UI_MOD_CTRL | C8UI_MOD_ALT)) {
			return false;
		}
		bool side = !s->vertical;
		switch (ev->sym) {
		case XKB_KEY_Page_Down:
			scroll_by_axis(w, side, axis_size(w, side) * 0.9, true);
			return true;
		case XKB_KEY_Page_Up:
			scroll_by_axis(w, side, -axis_size(w, side) * 0.9, true);
			return true;
		case XKB_KEY_Down:
		case XKB_KEY_Up:
			if (!s->vertical) {
				return false;
			}
			scroll_by_axis(w, false, ev->sym == XKB_KEY_Up ? -48 : 48, true);
			return true;
		case XKB_KEY_Left:
		case XKB_KEY_Right:
			if (!s->horizontal) {
				return false;
			}
			scroll_by_axis(w, true, ev->sym == XKB_KEY_Left ? -48 : 48, true);
			return true;
		}
		return false;
	}
	case C8UI_EVENT_ENTER:
	case C8UI_EVENT_LEAVE:
		c8ui_widget_queue_draw(w);
		return false;
	default:
		return false;
	}
}

static void scroll_destroy(struct c8ui_widget *w) {
	struct scroll *sc = w->data;
	c8ui_drag_finish(&sc->drag);
	free(sc);
}

static void scroll_reveal_hook(struct c8ui_widget *w,
		const struct c8ui_rect *r) {
	c8ui_scroll_reveal(w, r);
}

static const struct c8ui_widget_impl scroll_impl = {
	.name = "scroll",
	.measure = scroll_measure,
	.layout = scroll_layout,
	.draw = scroll_draw,
	.draw_over = scroll_draw_over,
	.event = scroll_event,
	.tick = scroll_tick,
	.destroy = scroll_destroy,
	.reveal = scroll_reveal_hook,
	.clips = true,
	.narrow = scroll_narrow,
};

struct c8ui_widget *c8ui_scroll_new(struct c8ui_widget *child) {
	struct scroll *s = calloc(1, sizeof(*s));
	s->vertical = s->wide_v = s->narrow_v = true;
	s->drag.axis = C8UI_VERTICAL;
	struct c8ui_widget *w = c8ui_widget_new(&scroll_impl, s);
	if (child) {
		c8ui_widget_add(w, child);
	}
	return w;
}

static void scroll_directions(struct c8ui_widget *w, bool horizontal,
		bool vertical) {
	struct scroll *s = w->data;
	s->horizontal = horizontal;
	s->vertical = vertical;
	/* A finger pans along the one way, or freely when both */
	s->drag.axis = horizontal && !vertical ? C8UI_HORIZONTAL : C8UI_VERTICAL;
	s->drag.both = horizontal && vertical;
	if (!horizontal) {
		scroll_set_axis(w, true, 0);
		s->x.target = 0;
	}
	if (!vertical) {
		scroll_set_axis(w, false, 0);
		s->y.target = 0;
	}
	c8ui_widget_queue_layout(w);
}

static void scroll_apply(struct c8ui_widget *w) {
	struct scroll *s = w->data;
	bool n = w->narrow && s->has_narrow;
	bool h = n ? s->narrow_h : s->wide_h, v = n ? s->narrow_v : s->wide_v;
	if (h != s->horizontal || v != s->vertical) {
		scroll_directions(w, h, v);
	}
}

static void scroll_narrow(struct c8ui_widget *w, bool narrow) {
	(void)narrow;
	scroll_apply(w);
}

void c8ui_scroll_set_directions(struct c8ui_widget *w, bool horizontal,
		bool vertical) {
	struct scroll *s = w->data;
	s->wide_h = horizontal;
	s->wide_v = vertical;
	if (!s->has_narrow) {
		s->narrow_h = horizontal;
		s->narrow_v = vertical;
	}
	scroll_directions(w, horizontal, vertical);
	scroll_apply(w);
}

void c8ui_scroll_set_narrow_directions(struct c8ui_widget *w,
		bool horizontal, bool vertical) {
	struct scroll *s = w->data;
	s->narrow_h = horizontal;
	s->narrow_v = vertical;
	s->has_narrow = true;
	scroll_apply(w);
}

/* There at once, nothing left to ease towards */
static void scroll_jump(struct c8ui_widget *w, bool horizontal,
		double offset) {
	struct scroll *s = w->data;
	struct scroll_axis *a = horizontal ? &s->x : &s->y;
	scroll_set_axis(w, horizontal, offset);
	a->target = a->offset;
}

void c8ui_scroll_to(struct c8ui_widget *w, double offset) {
	scroll_jump(w, false, offset);
}

void c8ui_scroll_to_x(struct c8ui_widget *w, double offset) {
	scroll_jump(w, true, offset);
}

void c8ui_scroll_get_offset(struct c8ui_widget *w, double *x, double *y) {
	struct scroll *s = w->data;
	*x = s->x.offset;
	*y = s->y.offset;
}

/* start, len: the stretch to show along the axis, from the scroll's own
 * edge, as it will be once the scroll settles; room: the scroll's size */
static void reveal_axis(struct c8ui_widget *w, bool horizontal, double start,
		double len, double room) {
	struct scroll *s = w->data;
	struct scroll_axis *a = horizontal ? &s->x : &s->y;
	const double margin = 24;
	start += a->offset - a->target;
	if (start < margin) {
		scroll_by_axis(w, horizontal, start - margin, true);
	} else if (start + len > room - margin) {
		scroll_by_axis(w, horizontal, start + len - room + margin, true);
	}
}

void c8ui_scroll_reveal(struct c8ui_widget *w, const struct c8ui_rect *r) {
	struct scroll *s = w->data;
	if (s->vertical) {
		reveal_axis(w, false, r->y - w->rect.y, r->height, w->rect.height);
	}
	if (s->horizontal) {
		reveal_axis(w, true, r->x - w->rect.x, r->width, w->rect.width);
	}
}

/* Label */

struct label {
	char *text;
	enum c8ui_text_style style;
	enum c8ui_text_color color;
	int max_lines;
	int narrow_style; // -1: the same as wide
};

static enum c8ui_text_style label_style(struct c8ui_widget *w) {
	struct label *l = w->data;
	return w->narrow && l->narrow_style >= 0 ?
		(enum c8ui_text_style)l->narrow_style : l->style;
}

static void label_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct label *l = w->data;
	c8ui_text_size(c8ui_widget_font(w), c8ui_text_font(label_style(w)), l->text,
		avail, l->max_lines, width, height);
}

static void label_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct label *l = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	if (l->color == C8UI_COLOR_ACCENT) {
		c8ui_set_source(cr, c.accent, 1);
	} else {
		c8ui_set_source(cr, c.fg,
			l->color == C8UI_COLOR_SECONDARY ? c.fg_secondary : 1);
	}
	c8ui_text_draw(cr, c8ui_widget_font(w), c8ui_text_font(label_style(w)), l->text,
		w->rect.x, w->rect.y, w->rect.width + 1, l->max_lines);
}

static void label_destroy(struct c8ui_widget *w) {
	struct label *l = w->data;
	free(l->text);
	free(l);
}

static const struct c8ui_widget_impl label_impl = {
	.name = "label",
	.measure = label_measure,
	.draw = label_draw,
	.destroy = label_destroy,
};

struct c8ui_widget *c8ui_label_new(const char *text, enum c8ui_text_style style) {
	struct label *l = calloc(1, sizeof(*l));
	l->text = strdup(text ? text : "");
	l->style = style;
	l->narrow_style = -1;
	return c8ui_widget_new(&label_impl, l);
}

void c8ui_label_set_text(struct c8ui_widget *w, const char *text) {
	struct label *l = w->data;
	if (strcmp(l->text, text ? text : "") == 0) {
		return;
	}
	free(l->text);
	l->text = strdup(text ? text : "");
	c8ui_widget_queue_layout(w);
}

void c8ui_label_set_color(struct c8ui_widget *w, enum c8ui_text_color color) {
	struct label *l = w->data;
	l->color = color;
	c8ui_widget_queue_draw(w);
}

void c8ui_label_set_style(struct c8ui_widget *w, enum c8ui_text_style style) {
	struct label *l = w->data;
	if (l->style != style) {
		l->style = style;
		c8ui_widget_queue_layout(w);
	}
}

void c8ui_label_set_narrow_style(struct c8ui_widget *w,
		enum c8ui_text_style style) {
	struct label *l = w->data;
	l->narrow_style = style;
	c8ui_widget_queue_layout(w);
}

void c8ui_label_set_max_lines(struct c8ui_widget *w, int lines) {
	struct label *l = w->data;
	l->max_lines = lines;
	c8ui_widget_queue_layout(w);
}

/* Canvas */

struct canvas {
	double width, height;
	c8ui_draw_fn draw;
	c8ui_event_fn event;
	void *data;
};

static void canvas_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct canvas *c = w->data;
	*width = c->width > 0 ? c->width : avail;
	*height = c->height;
}

static void canvas_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct canvas *c = w->data;
	if (c->draw) {
		cairo_save(cr);
		c->draw(w, cr, c->data);
		cairo_restore(cr);
	}
}

static bool canvas_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct canvas *c = w->data;
	return c->event ? c->event(w, ev, c->data) : false;
}

static const struct c8ui_widget_impl canvas_impl = {
	.name = "canvas",
	.measure = canvas_measure,
	.draw = canvas_draw,
	.event = canvas_event,
	.destroy = free_data,
};

struct c8ui_widget *c8ui_canvas_new(double width, double height,
		c8ui_draw_fn draw, c8ui_event_fn event, void *data) {
	struct canvas *c = calloc(1, sizeof(*c));
	c->width = width;
	c->height = height;
	c->draw = draw;
	c->event = event;
	c->data = data;
	return c8ui_widget_new(&canvas_impl, c);
}
