#define _GNU_SOURCE
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <xkbcommon/xkbcommon.h>
#include "c8ui-private.h"

/* Containers that arrange: grid, stack, expander, split, separator, flip
 * view, and the info bar */

/* Places a child in a cell: across it if it fills, else by its align */
static void place(struct c8ui_widget *c, double x, double y, double width,
		double cw, double ch) {
	if (c->fill || cw > width) {
		cw = width;
	}
	double cx = x;
	if (c->align == C8UI_ALIGN_CENTER) {
		cx += (width - cw) / 2;
	} else if (c->align == C8UI_ALIGN_END) {
		cx += width - cw;
	}
	c8ui_widget_layout(c, (struct c8ui_rect){ round(cx), round(y), cw, ch });
}

/* Grid */

struct grid_column {
	double width; // 0: the widest child's
	bool expand;
};

struct grid_span {
	struct c8ui_widget *w;
	int span;
};

struct grid {
	int columns;
	double sx, sy;
	struct grid_column *cols;
	struct grid_span *spans;
	int span_count;
};

static int grid_span_of(struct grid *g, struct c8ui_widget *c) {
	for (int i = 0; i < g->span_count; i++) {
		if (g->spans[i].w == c) {
			int s = g->spans[i].span;
			return s < 1 ? 1 : s > g->columns ? g->columns : s;
		}
	}
	return 1;
}

/* The width of a cell spanning columns from col on, gaps between them in */
static double grid_cell_width(struct grid *g, const double *colw, int col,
		int span) {
	double width = g->sx * (span - 1);
	for (int m = col; m < col + span; m++) {
		width += colw[m];
	}
	return width;
}

/* Works out the columns and rows for a width, and places the children if
 * place; returns the size it needs */
static void grid_arrange(struct c8ui_widget *w, double avail, bool place_them,
		double *out_w, double *out_h) {
	struct grid *g = w->data;
	int n = g->columns;
	double *colw = calloc(n, sizeof(double));
	/* Natural widths from the children that take one column */
	int col = 0;
	for (int i = 0; i < w->child_count; i++) {
		struct c8ui_widget *c = w->children[i];
		if (c->hidden) {
			continue;
		}
		int span = grid_span_of(g, c);
		if (col + span > n) {
			col = 0;
		}
		if (span == 1 && g->cols[col].width <= 0) {
			double cw, ch;
			c8ui_widget_measure(c, avail, &cw, &ch);
			colw[col] = cw > colw[col] ? cw : colw[col];
		}
		col = (col + span) % n;
	}
	double total = g->sx * (n - 1);
	int expanding = 0;
	for (int i = 0; i < n; i++) {
		if (g->cols[i].width > 0) {
			colw[i] = g->cols[i].width;
		}
		total += colw[i];
		expanding += g->cols[i].expand;
	}
	/* Expanding columns take what is left, or give back what is too much
	 * (a wrapping label measures as wide as all the room it was offered) */
	if (expanding > 0 && avail > 0 && avail != total) {
		double extra = (avail - total) / expanding;
		total = g->sx * (n - 1);
		for (int i = 0; i < n; i++) {
			if (g->cols[i].expand) {
				colw[i] = colw[i] + extra > 0 ? colw[i] + extra : 0;
			}
			total += colw[i];
		}
	}

	/* Rows: as tall as their tallest */
	double y = 0;
	int row_start = 0;
	col = 0;
	double row_h = 0;
	for (int i = 0; i <= w->child_count; i++) {
		struct c8ui_widget *c = i < w->child_count ? w->children[i] : NULL;
		if (c && c->hidden) {
			continue;
		}
		int span = c ? grid_span_of(g, c) : 0;
		if (c == NULL || col + span > n) {
			/* The row is done: place what is in it */
			if (place_them) {
				int k = 0;
				for (int j = row_start; j < i; j++) {
					struct c8ui_widget *d = w->children[j];
					if (d->hidden) {
						continue;
					}
					int s = grid_span_of(g, d);
					double x = 0, cellw = grid_cell_width(g, colw, k, s);
					for (int m = 0; m < k; m++) {
						x += colw[m] + g->sx;
					}
					double cw, ch;
					c8ui_widget_measure(d, cellw, &cw, &ch);
					place(d, w->rect.x + x, w->rect.y + y + (row_h - ch) / 2,
						cellw, cw, ch);
					k += s;
				}
			}
			if (col > 0) {
				y += row_h + g->sy;
			}
			row_h = 0;
			row_start = i;
			col = 0;
			if (c == NULL) {
				break;
			}
		}
		double cellw = grid_cell_width(g, colw, col, span);
		double cw, ch;
		c8ui_widget_measure(c, cellw, &cw, &ch);
		row_h = ch > row_h ? ch : row_h;
		col += span;
	}
	*out_w = total;
	*out_h = y > 0 ? y - g->sy : 0;
	free(colw);
}

static void grid_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	grid_arrange(w, avail, false, width, height);
}

static void grid_layout(struct c8ui_widget *w) {
	double gw, gh;
	grid_arrange(w, w->rect.width, true, &gw, &gh);
}

static void grid_destroy(struct c8ui_widget *w) {
	struct grid *g = w->data;
	free(g->cols);
	free(g->spans);
	free(g);
}

static const struct c8ui_widget_impl grid_impl = {
	.name = "grid",
	.measure = grid_measure,
	.layout = grid_layout,
	.destroy = grid_destroy,
};

struct c8ui_widget *c8ui_grid_new(int columns, double column_spacing,
		double row_spacing) {
	struct grid *g = calloc(1, sizeof(*g));
	g->columns = columns > 0 ? columns : 1;
	g->sx = column_spacing;
	g->sy = row_spacing;
	g->cols = calloc(g->columns, sizeof(*g->cols));
	return c8ui_widget_new(&grid_impl, g);
}

void c8ui_grid_set_column(struct c8ui_widget *w, int column, double width,
		bool expand) {
	struct grid *g = w->data;
	if (column < 0 || column >= g->columns) {
		return;
	}
	g->cols[column].width = width;
	g->cols[column].expand = expand;
	c8ui_widget_queue_layout(w);
}

void c8ui_grid_add(struct c8ui_widget *w, struct c8ui_widget *child,
		int span) {
	struct grid *g = w->data;
	/* Forget spans of children gone since */
	int n = 0;
	for (int i = 0; i < g->span_count; i++) {
		if (g->spans[i].w->parent == w) {
			g->spans[n++] = g->spans[i];
		}
	}
	g->span_count = n;
	if (span > 1) {
		g->spans = realloc(g->spans, sizeof(*g->spans) * (n + 1));
		g->spans[g->span_count++] = (struct grid_span){ child, span };
	}
	c8ui_widget_add(w, child);
}

/* Stack */

struct stack {
	int selected;
};

static void stack_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct stack *s = w->data;
	*width = *height = 0;
	if (s->selected >= 0 && s->selected < w->child_count) {
		c8ui_widget_measure(w->children[s->selected], avail, width, height);
	}
	*width = w->fill ? avail : *width;
}

static void stack_layout(struct c8ui_widget *w) {
	struct stack *s = w->data;
	for (int i = 0; i < w->child_count; i++) {
		struct c8ui_widget *c = w->children[i];
		c->hidden = i != s->selected;
		c8ui_widget_layout(c, w->rect);
	}
}

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

static const struct c8ui_widget_impl stack_impl = {
	.name = "stack",
	.measure = stack_measure,
	.layout = stack_layout,
	.destroy = stack_destroy,
};

struct c8ui_widget *c8ui_stack_new(void) {
	struct stack *s = calloc(1, sizeof(*s));
	return c8ui_widget_new(&stack_impl, s);
}

void c8ui_stack_set(struct c8ui_widget *w, int index, bool enter) {
	struct stack *s = w->data;
	if (index < 0 || index >= w->child_count) {
		return;
	}
	s->selected = index;
	for (int i = 0; i < w->child_count; i++) {
		c8ui_widget_set_hidden(w->children[i], i != index);
	}
	if (enter) {
		c8ui_widget_enter(w->children[index]);
	}
	c8ui_widget_queue_layout(w);
}

int c8ui_stack_get(struct c8ui_widget *w) {
	return ((struct stack *)w->data)->selected;
}

void c8ui_stack_push(struct c8ui_widget *w, struct c8ui_widget *page,
		bool enter) {
	c8ui_widget_add(w, page);
	c8ui_stack_set(w, w->child_count - 1, enter);
}

void c8ui_stack_pop(struct c8ui_widget *w, bool enter) {
	if (w->child_count < 2) {
		return;
	}
	struct c8ui_widget *top = w->children[w->child_count - 1];
	c8ui_stack_set(w, w->child_count - 2, enter);
	c8ui_widget_destroy(top);
}

/* Expander */

#define EXPANDER_ROW 40
#define EXPANDER_GAP 8 // between the title row and the content
#define EXPANDER_ARROW 24 // room for the arrow left of the title

struct expander {
	char *title;
	bool expanded;
	c8ui_action_fn fn;
	void *data;
};

static void expander_measure(struct c8ui_widget *w, double avail,
		double *width, double *height) {
	struct expander *e = w->data;
	double tw, th;
	c8ui_text_size(c8ui_widget_font(w), c8ui_text_font(C8UI_TEXT_TITLE),
		e->title, 0, 0, &tw, &th);
	*width = EXPANDER_ARROW + tw;
	*height = EXPANDER_ROW;
	if (e->expanded && w->child_count > 0) {
		double cw, ch;
		c8ui_widget_measure(w->children[0], avail, &cw, &ch);
		*width = cw > *width ? cw : *width;
		*height += EXPANDER_GAP + ch;
	}
	*width = *width > avail ? avail : *width;
}

static void expander_layout(struct c8ui_widget *w) {
	struct expander *e = w->data;
	if (w->child_count == 0) {
		return;
	}
	struct c8ui_widget *c = w->children[0];
	c->hidden = !e->expanded;
	double cw, ch;
	c8ui_widget_measure(c, w->rect.width, &cw, &ch);
	place(c, w->rect.x, w->rect.y + EXPANDER_ROW + EXPANDER_GAP,
		w->rect.width, cw, ch);
}

static void expander_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct expander *e = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	bool over = w->hovered && w->root &&
		w->root->py < w->rect.y + EXPANDER_ROW;
	double alpha = w->disabled ? 0.4 : over ? 0.75 : 1;
	double cy = w->rect.y + EXPANDER_ROW / 2.0;
	double ax = w->rect.x + 7;
	c8ui_set_source(cr, c.fg, alpha);
	cairo_set_line_width(cr, 1.5);
	if (e->expanded) {
		cairo_move_to(cr, ax - 1, cy - 3);
		cairo_line_to(cr, ax + 5, cy + 3);
		cairo_line_to(cr, ax + 11, cy - 3);
	} else {
		cairo_move_to(cr, ax + 2, cy - 6);
		cairo_line_to(cr, ax + 8, cy);
		cairo_line_to(cr, ax + 2, cy + 6);
	}
	cairo_stroke(cr);
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_TITLE);
	double tw, th;
	c8ui_text_size(c8ui_widget_font(w), font, e->title, 0, 0, &tw, &th);
	c8ui_text_draw(cr, c8ui_widget_font(w), font, e->title,
		w->rect.x + EXPANDER_ARROW, cy - th / 2,
		w->rect.width - EXPANDER_ARROW, 1);
}

static void expander_toggle(struct c8ui_widget *w) {
	struct expander *e = w->data;
	c8ui_expander_set(w, !e->expanded);
	if (e->expanded && w->child_count > 0) {
		c8ui_widget_enter(w->children[0]);
	}
	if (e->fn) {
		e->fn(w, e->data);
	}
}

static bool expander_event(struct c8ui_widget *w,
		const struct c8ui_event *ev) {
	struct expander *e = w->data;
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		return ev->button == C8UI_BUTTON_LEFT &&
			ev->y < w->rect.y + EXPANDER_ROW;
	case C8UI_EVENT_RELEASE:
		if (c8ui_rect_contains(&w->rect, ev->x, ev->y) &&
				ev->y < w->rect.y + EXPANDER_ROW) {
			expander_toggle(w);
		}
		return true;
	case C8UI_EVENT_MOTION: {
		bool over = ev->y < w->rect.y + EXPANDER_ROW;
		w->cursor = over ? C8UI_CURSOR_POINTER : C8UI_CURSOR_DEFAULT;
		c8ui_widget_queue_draw(w);
		return false;
	}
	case C8UI_EVENT_LEAVE:
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_KEY:
		if (!w->focused) {
			return false;
		}
		if (c8ui_activates(ev) ||
				(ev->sym == XKB_KEY_Right && !e->expanded) ||
				(ev->sym == XKB_KEY_Left && e->expanded)) {
			expander_toggle(w);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void expander_destroy(struct c8ui_widget *w) {
	struct expander *e = w->data;
	free(e->title);
	free(e);
}

static const struct c8ui_widget_impl expander_impl = {
	.name = "expander",
	.measure = expander_measure,
	.layout = expander_layout,
	.draw = expander_draw,
	.event = expander_event,
	.destroy = expander_destroy,
};

struct c8ui_widget *c8ui_expander_new(const char *title,
		struct c8ui_widget *content, bool expanded, c8ui_action_fn fn,
		void *data) {
	struct expander *e = calloc(1, sizeof(*e));
	e->title = strdup(title ? title : "");
	e->expanded = expanded;
	e->fn = fn;
	e->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&expander_impl, e);
	w->focusable = true;
	w->fill = true;
	if (content) {
		content->hidden = !expanded;
		c8ui_widget_add(w, content);
	}
	return w;
}

bool c8ui_expander_get(struct c8ui_widget *w) {
	return ((struct expander *)w->data)->expanded;
}

void c8ui_expander_set(struct c8ui_widget *w, bool expanded) {
	struct expander *e = w->data;
	if (e->expanded == expanded) {
		return;
	}
	e->expanded = expanded;
	if (w->child_count > 0) {
		c8ui_widget_set_hidden(w->children[0], !expanded);
	}
	c8ui_widget_queue_layout(w);
}

/* Split */

#define SPLIT_HANDLE 8 // the strip that can be dragged
#define SPLIT_KEY_STEP 20

struct split {
	enum c8ui_orientation orientation;
	double position; // first's size, or below 0 the second's
	/* Above 0: the first's share of the room instead, kept as the room
	 * changes (and stacked, the same share of the height) */
	double share;
	double min_first, min_second;
	double first; // the first's size as laid out
	bool dragging;
	int32_t touch; // the finger dragging, -1: none
	double grab; // where in the handle it was taken
	c8ui_action_fn fn;
	void *data;
	bool narrow; // side by side is stacked while the window is narrow
};

static bool split_horizontal(struct split *s) {
	return s->orientation == C8UI_HORIZONTAL && !s->narrow;
}

static void split_narrow(struct c8ui_widget *w, bool narrow) {
	struct split *s = w->data;
	s->narrow = narrow;
	c8ui_widget_queue_layout(w);
}

static double split_total(struct c8ui_widget *w) {
	struct split *s = w->data;
	return split_horizontal(s) ? w->rect.width : w->rect.height;
}

/* The first pane's size for the room there is, kept to the minimums */
static double split_first(struct c8ui_widget *w) {
	struct split *s = w->data;
	double room = split_total(w) - SPLIT_HANDLE;
	double first = s->share > 0 ? room * s->share :
		s->position >= 0 ? s->position : room + s->position;
	if (first > room - s->min_second) {
		first = room - s->min_second;
	}
	if (first < s->min_first) {
		first = s->min_first;
	}
	if (s->min_first + s->min_second > room) {
		/* Not room for both: share it in the same proportion */
		first = room * s->min_first / (s->min_first + s->min_second);
	}
	return round(first > 0 ? first : 0);
}

static struct c8ui_rect split_handle(struct c8ui_widget *w) {
	struct split *s = w->data;
	if (split_horizontal(s)) {
		return (struct c8ui_rect){ w->rect.x + s->first, w->rect.y,
			SPLIT_HANDLE, w->rect.height };
	}
	return (struct c8ui_rect){ w->rect.x, w->rect.y + s->first,
		w->rect.width, SPLIT_HANDLE };
}

static void split_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct split *s = w->data;
	*width = avail;
	*height = 0;
	for (int i = 0; i < w->child_count && i < 2; i++) {
		double cw, ch;
		c8ui_widget_measure(w->children[i], avail, &cw, &ch);
		if (split_horizontal(s)) {
			*height = ch > *height ? ch : *height;
		} else {
			*height += ch;
		}
	}
	if (!split_horizontal(s)) {
		*height += SPLIT_HANDLE;
	}
}

static void split_layout(struct c8ui_widget *w) {
	struct split *s = w->data;
	s->first = split_first(w);
	double second = split_total(w) - SPLIT_HANDLE - s->first;
	second = second > 0 ? second : 0;
	struct c8ui_rect r = w->rect;
	for (int i = 0; i < w->child_count && i < 2; i++) {
		struct c8ui_rect cr = r;
		if (split_horizontal(s)) {
			cr.x = i == 0 ? r.x : r.x + s->first + SPLIT_HANDLE;
			cr.width = i == 0 ? s->first : second;
		} else {
			cr.y = i == 0 ? r.y : r.y + s->first + SPLIT_HANDLE;
			cr.height = i == 0 ? s->first : second;
		}
		c8ui_widget_layout(w->children[i], cr);
	}
}

static void split_draw_over(struct c8ui_widget *w, cairo_t *cr) {
	struct split *s = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	struct c8ui_rect h = split_handle(w);
	bool hot = s->dragging || (w->hovered && w->root &&
		c8ui_rect_contains(&h, w->root->px, w->root->py));
	double line = hot ? 2 : 1;
	if (s->dragging || (w->focused && w->root && w->root->focus_visible)) {
		c8ui_set_source(cr, c.accent, 1);
	} else {
		c8ui_set_source(cr, c.fg, hot ? 0.5 : 0.15);
	}
	if (split_horizontal(s)) {
		cairo_rectangle(cr, round(h.x + (h.width - line) / 2), h.y, line,
			h.height);
	} else {
		cairo_rectangle(cr, h.x, round(h.y + (h.height - line) / 2), h.width,
			line);
	}
	cairo_fill(cr);
}

/* Moves the divider so the handle's grab point is at x, y */
static void split_drag_to(struct c8ui_widget *w, double x, double y) {
	struct split *s = w->data;
	double at = split_horizontal(s) ? x - w->rect.x : y - w->rect.y;
	double first = at - s->grab;
	double room = split_total(w) - SPLIT_HANDLE;
	first = first > room - s->min_second ? room - s->min_second : first;
	first = first < s->min_first ? s->min_first : first;
	/* Keep it measured the way it was: a share, or from its side */
	if (s->share > 0) {
		s->share = room > 0 ? first / room : 0.5;
	} else {
		s->position = s->position >= 0 ? first : -(room - first);
	}
	c8ui_widget_queue_layout(w);
	if (s->fn) {
		s->fn(w, s->data);
	}
}

static void split_hover_cursor(struct c8ui_widget *w, double x, double y) {
	struct split *s = w->data;
	struct c8ui_rect h = split_handle(w);
	w->cursor = c8ui_rect_contains(&h, x, y) || s->dragging ?
		(split_horizontal(s) ? C8UI_CURSOR_RESIZE_H : C8UI_CURSOR_RESIZE_V) :
		C8UI_CURSOR_DEFAULT;
	c8ui_widget_queue_draw(w);
}

static bool split_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct split *s = w->data;
	struct c8ui_rect h = split_handle(w);
	switch (ev->type) {
	case C8UI_EVENT_ENTER:
	case C8UI_EVENT_MOTION:
		if (s->dragging && s->touch < 0) {
			split_drag_to(w, ev->x, ev->y);
		}
		split_hover_cursor(w, ev->x, ev->y);
		return s->dragging;
	case C8UI_EVENT_LEAVE:
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_PRESS:
		if (ev->button != C8UI_BUTTON_LEFT ||
				!c8ui_rect_contains(&h, ev->x, ev->y)) {
			return false;
		}
		s->dragging = true;
		s->touch = -1;
		s->grab = split_horizontal(s) ? ev->x - h.x : ev->y - h.y;
		return true;
	case C8UI_EVENT_RELEASE:
		s->dragging = false;
		c8ui_widget_queue_draw(w);
		return true;
	case C8UI_EVENT_TOUCH_DOWN:
		/* A finger has a wider handle */
		if (s->dragging || !c8ui_rect_contains(&(struct c8ui_rect){
				h.x - 12, h.y - 12, h.width + 24, h.height + 24 },
				ev->x, ev->y)) {
			return false;
		}
		s->dragging = true;
		s->touch = ev->touch_id;
		s->grab = SPLIT_HANDLE / 2.0;
		c8ui_widget_queue_draw(w);
		return true;
	case C8UI_EVENT_TOUCH_MOTION:
		if (s->dragging && ev->touch_id == s->touch) {
			split_drag_to(w, ev->x, ev->y);
		}
		return true;
	case C8UI_EVENT_TOUCH_UP:
	case C8UI_EVENT_TOUCH_CANCEL:
		s->dragging = false;
		s->touch = -1;
		c8ui_widget_queue_draw(w);
		return true;
	case C8UI_EVENT_KEY: {
		if (!w->focused) {
			return false;
		}
		int dir = 0;
		if (split_horizontal(s)) {
			dir = ev->sym == XKB_KEY_Left ? -1 : ev->sym == XKB_KEY_Right;
		} else {
			dir = ev->sym == XKB_KEY_Up ? -1 : ev->sym == XKB_KEY_Down;
		}
		if (dir == 0) {
			return false;
		}
		s->grab = 0;
		double at = s->first + dir * SPLIT_KEY_STEP;
		split_drag_to(w, split_horizontal(s) ? w->rect.x + at : 0,
			split_horizontal(s) ? 0 : w->rect.y + at);
		return true;
	}
	default:
		return false;
	}
}

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

static const struct c8ui_widget_impl split_impl = {
	.name = "split",
	.measure = split_measure,
	.layout = split_layout,
	.draw_over = split_draw_over,
	.event = split_event,
	.destroy = split_destroy,
	.narrow = split_narrow,
};

void c8ui_split_set_orientation(struct c8ui_widget *w,
		enum c8ui_orientation orientation) {
	struct split *s = w->data;
	s->orientation = orientation;
	c8ui_widget_queue_layout(w);
}

struct c8ui_widget *c8ui_split_new(enum c8ui_orientation orientation,
		struct c8ui_widget *first, struct c8ui_widget *second,
		double position) {
	struct split *s = calloc(1, sizeof(*s));
	s->orientation = orientation;
	s->position = position;
	s->min_first = s->min_second = 100;
	s->touch = -1;
	struct c8ui_widget *w = c8ui_widget_new(&split_impl, s);
	w->focusable = true;
	w->fill = true;
	if (first) {
		c8ui_widget_add(w, first);
	}
	if (second) {
		c8ui_widget_add(w, second);
	}
	return w;
}

void c8ui_split_set_position(struct c8ui_widget *w, double position) {
	struct split *s = w->data;
	s->position = position;
	s->share = 0;
	c8ui_widget_queue_layout(w);
}

void c8ui_split_set_share(struct c8ui_widget *w, double share) {
	struct split *s = w->data;
	s->share = share > 0 && share < 1 ? share : 0;
	c8ui_widget_queue_layout(w);
}

double c8ui_split_get_share(struct c8ui_widget *w) {
	return ((struct split *)w->data)->share;
}

double c8ui_split_get_position(struct c8ui_widget *w) {
	return ((struct split *)w->data)->position;
}

void c8ui_split_set_min(struct c8ui_widget *w, double first, double second) {
	struct split *s = w->data;
	s->min_first = first > 0 ? first : 0;
	s->min_second = second > 0 ? second : 0;
	c8ui_widget_queue_layout(w);
}

void c8ui_split_on_change(struct c8ui_widget *w, c8ui_action_fn fn,
		void *data) {
	struct split *s = w->data;
	s->fn = fn;
	s->data = data;
}

/* Separator */

struct separator {
	enum c8ui_orientation orientation;
};

static void separator_measure(struct c8ui_widget *w, double avail,
		double *width, double *height) {
	struct separator *s = w->data;
	*width = s->orientation == C8UI_HORIZONTAL ? avail : 1;
	*height = s->orientation == C8UI_HORIZONTAL ? 1 : 0;
}

static void separator_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct c8ui_colors c = c8ui_widget_colors(w);
	c8ui_set_source(cr, c.fg, 0.2);
	cairo_rectangle(cr, w->rect.x, w->rect.y, w->rect.width, w->rect.height);
	cairo_fill(cr);
}

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

static const struct c8ui_widget_impl separator_impl = {
	.name = "separator",
	.measure = separator_measure,
	.draw = separator_draw,
	.destroy = separator_destroy,
};

struct c8ui_widget *c8ui_separator_new(enum c8ui_orientation orientation) {
	struct separator *s = calloc(1, sizeof(*s));
	s->orientation = orientation;
	struct c8ui_widget *w = c8ui_widget_new(&separator_impl, s);
	w->fill = true;
	return w;
}

/* Flip view */

#define FLIP_SWIPE 0.25 // of the width, a drag that turns the page
#define FLIP_FLICK 0.4 // px/ms, a flick that does
#define FLIP_ARROW_W 40
#define FLIP_ARROW_H 60
#define FLIP_DOT 6
#define FLIP_DOT_GAP 8

struct flip {
	int selected;
	double offset; // the page's displacement while dragged or settling
	bool dots;
	int pressed; // -1, or the arrow: 0 left, 1 right
	struct c8ui_drag drag;
	double wheel; // touchpad: sideways scroll gathered
	bool wheeling;
	c8ui_action_fn fn;
	void *data;
};

/* Whether there's a page before (side 0) or after (1) the one showing */
static bool flip_has(struct c8ui_widget *w, int side) {
	struct flip *f = w->data;
	return side == 0 ? f->selected > 0 : f->selected < w->child_count - 1;
}

static double flip_resist(struct c8ui_widget *w, double offset) {
	/* Past the first or last page it only gives a little */
	if ((offset > 0 && !flip_has(w, 0)) || (offset < 0 && !flip_has(w, 1))) {
		return offset * 0.3;
	}
	return offset;
}

static void flip_set_offset(struct c8ui_widget *w, double offset) {
	struct flip *f = w->data;
	bool was_moving = f->offset != 0;
	f->offset = offset;
	w->moves_children = f->offset != 0;
	if ((offset != 0) != was_moving) {
		c8ui_widget_queue_layout(w); // the neighbours show, or go
	}
	c8ui_widget_queue_draw(w);
}

static void flip_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct flip *f = w->data;
	*width = avail;
	*height = 0;
	if (f->selected < w->child_count) {
		double cw, ch;
		c8ui_widget_measure(w->children[f->selected], avail, &cw, &ch);
		*height = ch;
	}
}

static void flip_layout(struct c8ui_widget *w) {
	struct flip *f = w->data;
	for (int i = 0; i < w->child_count; i++) {
		struct c8ui_widget *c = w->children[i];
		int d = i - f->selected;
		/* The ones either side only while something moves */
		c->hidden = d != 0 && (f->offset == 0 || d < -1 || d > 1);
		struct c8ui_rect r = w->rect;
		r.x += d * w->rect.width;
		c8ui_widget_layout(c, r);
	}
}

static bool flip_arrows_shown(struct c8ui_widget *w) {
	struct flip *f = w->data;
	struct c8ui_root *root = w->root;
	return root && root->pointer_in && root->touch_mouse < 0 &&
		!f->drag.down &&
		w->child_count > 1 &&
		c8ui_rect_contains(&w->rect, root->px, root->py);
}

static struct c8ui_rect flip_arrow(struct c8ui_widget *w, int side) {
	double y = w->rect.y + (w->rect.height - FLIP_ARROW_H) / 2;
	double x = side == 0 ? w->rect.x : w->rect.x + w->rect.width -
		FLIP_ARROW_W;
	return (struct c8ui_rect){ x, round(y), FLIP_ARROW_W, FLIP_ARROW_H };
}

static int flip_arrow_at(struct c8ui_widget *w, double x, double y) {
	for (int side = 0; side < 2; side++) {
		struct c8ui_rect r = flip_arrow(w, side);
		if (flip_has(w, side) && c8ui_rect_contains(&r, x, y)) {
			return side;
		}
	}
	return -1;
}

static void flip_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct flip *f = w->data;
	cairo_rectangle(cr, w->rect.x, w->rect.y, w->rect.width, w->rect.height);
	cairo_clip(cr);
	cairo_save(cr);
	/* Pages are drawn moved; draw_over puts it back for the arrows. The
	 * save is undone there. */
	cairo_translate(cr, round(f->offset), 0);
}

static void flip_draw_over(struct c8ui_widget *w, cairo_t *cr) {
	struct flip *f = w->data;
	cairo_restore(cr);
	struct c8ui_colors c = c8ui_widget_colors(w);
	if (flip_arrows_shown(w)) {
		struct c8ui_root *root = w->root;
		for (int side = 0; side < 2; side++) {
			if (!flip_has(w, side)) {
				continue;
			}
			struct c8ui_rect r = flip_arrow(w, side);
			bool over = c8ui_rect_contains(&r, root->px, root->py);
			bool down = over && f->pressed == side;
			c8ui_set_source(cr, down ? c.fg : c.bg, down ? 0.8 :
				over ? 0.95 : 0.7);
			cairo_rectangle(cr, r.x, r.y, r.width, r.height);
			cairo_fill(cr);
			double cx = r.x + r.width / 2, cy = r.y + r.height / 2;
			double d = side == 0 ? 1 : -1;
			c8ui_set_source(cr, down ? c.bg : c.fg, 1);
			cairo_set_line_width(cr, 2);
			cairo_move_to(cr, cx + 3 * d, cy - 7);
			cairo_line_to(cr, cx - 4 * d, cy);
			cairo_line_to(cr, cx + 3 * d, cy + 7);
			cairo_stroke(cr);
		}
	}
	if (f->dots && w->child_count > 1) {
		int n = w->child_count;
		double width = n * FLIP_DOT + (n - 1) * FLIP_DOT_GAP;
		double x = w->rect.x + (w->rect.width - width) / 2;
		double y = w->rect.y + w->rect.height - 16;
		for (int i = 0; i < n; i++) {
			/* White with a dark rim, to show on any picture */
			cairo_new_path(cr);
			cairo_arc(cr, x + FLIP_DOT / 2.0, y, FLIP_DOT / 2.0, 0, 2 * M_PI);
			c8ui_set_source(cr, 0xffffff, i == f->selected ? 1 : 0.45);
			cairo_fill_preserve(cr);
			c8ui_set_source(cr, 0x000000, 0.3);
			cairo_set_line_width(cr, 1);
			cairo_stroke(cr);
			x += FLIP_DOT + FLIP_DOT_GAP;
		}
	}
}

static bool flip_tick(struct c8ui_widget *w, int64_t now) {
	struct flip *f = w->data;
	if (f->drag.active || f->wheeling) {
		return false;
	}
	double offset = f->offset * 0.75;
	if (fabs(offset) < 0.5) {
		flip_set_offset(w, 0);
		return false;
	}
	flip_set_offset(w, offset);
	return true;
}

/* Turns to index; the page slides in from where the old one was */
static void flip_go(struct c8ui_widget *w, int index) {
	struct flip *f = w->data;
	if (index < 0 || index >= w->child_count) {
		c8ui_widget_animate(w); // back into place
		return;
	}
	if (index != f->selected) {
		int dir = index > f->selected ? 1 : -1;
		double offset = f->offset + dir * w->rect.width;
		if (abs(index - f->selected) > 1) {
			offset = dir * w->rect.width; // jumps: just slide in
		}
		f->selected = index;
		f->offset = 0;
		w->moves_children = f->offset != 0;
		flip_set_offset(w, offset);
		if (f->fn) {
			f->fn(w, f->data);
		}
	}
	c8ui_widget_animate(w);
}

/* A drag or a touchpad scroll let go at offset with speed velocity */
static void flip_settle(struct c8ui_widget *w, double velocity) {
	struct flip *f = w->data;
	double d = f->offset;
	if (fabs(d) > w->rect.width * FLIP_SWIPE ||
			fabs(velocity) > FLIP_FLICK) {
		int dir = (fabs(velocity) > FLIP_FLICK ? velocity : d) < 0 ? 1 : -1;
		flip_go(w, f->selected + dir);
	} else {
		c8ui_widget_animate(w);
	}
}

static bool flip_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct flip *f = w->data;
	switch (ev->type) {
	case C8UI_EVENT_TOUCH_DOWN:
		if (w->child_count < 2 || f->drag.down) {
			return false;
		}
		/* fall through */
	case C8UI_EVENT_TOUCH_MOTION:
	case C8UI_EVENT_TOUCH_UP:
	case C8UI_EVENT_TOUCH_CANCEL:
		switch (c8ui_drag_touch(w, &f->drag, ev)) {
		case C8UI_DRAG_IGNORED:
			return false;
		case C8UI_DRAG_START:
		case C8UI_DRAG_MOVE:
			flip_set_offset(w, flip_resist(w, f->drag.delta));
			return true;
		case C8UI_DRAG_END:
			flip_settle(w, f->drag.velocity);
			return true;
		case C8UI_DRAG_CANCEL:
			c8ui_widget_animate(w);
			return true;
		default:
			return true;
		}
	case C8UI_EVENT_ENTER:
	case C8UI_EVENT_MOTION:
	case C8UI_EVENT_LEAVE:
		w->cursor = ev->type != C8UI_EVENT_LEAVE &&
			flip_arrow_at(w, ev->x, ev->y) >= 0 ? C8UI_CURSOR_POINTER :
			C8UI_CURSOR_DEFAULT;
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_PRESS:
		f->pressed = ev->button == C8UI_BUTTON_LEFT ?
			flip_arrow_at(w, ev->x, ev->y) : -1;
		c8ui_widget_queue_draw(w);
		return f->pressed >= 0;
	case C8UI_EVENT_RELEASE:
		if (f->pressed >= 0 && flip_arrow_at(w, ev->x, ev->y) == f->pressed) {
			flip_go(w, f->selected + (f->pressed == 0 ? -1 : 1));
		}
		f->pressed = -1;
		c8ui_widget_queue_draw(w);
		return true;
	case C8UI_EVENT_SCROLL:
		if (w->child_count < 2 || (ev->mods & C8UI_MOD_CTRL)) {
			return false;
		}
		if (ev->precise) {
			/* Fingers on a touchpad drag the page sideways */
			if (ev->dx == 0 || fabs(ev->dy) > fabs(ev->dx)) {
				return false;
			}
			f->wheeling = true;
			f->wheel -= ev->dx;
			flip_set_offset(w, flip_resist(w, f->wheel));
			return true;
		}
		{
			double d = ev->dx != 0 ? ev->dx : ev->dy;
			if (d == 0) {
				return false;
			}
			flip_go(w, f->selected + (d > 0 ? 1 : -1));
		}
		return true;
	case C8UI_EVENT_SCROLL_STOP:
		if (!f->wheeling) {
			return false;
		}
		f->wheeling = false;
		f->wheel = 0;
		flip_settle(w, 0);
		return true;
	case C8UI_EVENT_KEY:
		if (!w->focused || ev->mods & (C8UI_MOD_CTRL | C8UI_MOD_ALT)) {
			return false;
		}
		switch (ev->sym) {
		case XKB_KEY_Left:
		case XKB_KEY_Prior:
			flip_go(w, f->selected - 1);
			return true;
		case XKB_KEY_Right:
		case XKB_KEY_Next:
			flip_go(w, f->selected + 1);
			return true;
		case XKB_KEY_Home:
			flip_go(w, 0);
			return true;
		case XKB_KEY_End:
			flip_go(w, w->child_count - 1);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void flip_destroy(struct c8ui_widget *w) {
	struct flip *f = w->data;
	c8ui_drag_finish(&f->drag);
	free(f);
}

static const struct c8ui_widget_impl flip_impl = {
	.name = "flip",
	.measure = flip_measure,
	.layout = flip_layout,
	.draw = flip_draw,
	.draw_over = flip_draw_over,
	.event = flip_event,
	.tick = flip_tick,
	.destroy = flip_destroy,
	.clips = true,
};

struct c8ui_widget *c8ui_flip_new(c8ui_action_fn fn, void *data) {
	struct flip *f = calloc(1, sizeof(*f));
	f->pressed = -1;
	f->drag.axis = C8UI_HORIZONTAL;
	f->fn = fn;
	f->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&flip_impl, f);
	w->focusable = true;
	w->fill = true;
	return w;
}

int c8ui_flip_get(struct c8ui_widget *w) {
	return ((struct flip *)w->data)->selected;
}

void c8ui_flip_set(struct c8ui_widget *w, int index) {
	struct flip *f = w->data;
	if (index < 0 || index >= w->child_count) {
		return;
	}
	f->selected = index;
	flip_set_offset(w, 0);
	c8ui_widget_queue_layout(w);
}

void c8ui_flip_set_dots(struct c8ui_widget *w, bool dots) {
	((struct flip *)w->data)->dots = dots;
	c8ui_widget_queue_draw(w);
}

/* Info bar */

#define INFO_PAD 12
#define INFO_MARK 20 // the round mark at the start
#define INFO_GAP 12
#define INFO_CLOSE 32

struct infobar {
	enum c8ui_severity severity;
	char *title, *message;
	bool closable;
	c8ui_action_fn close_fn;
	void *close_data;
	struct c8ui_widget *close; // the close button, a child
};

/* Its background and the colour of its mark */
static void infobar_colors(struct c8ui_widget *w, uint32_t *bg,
		uint32_t *mark) {
	struct infobar *b = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	switch (b->severity) {
	case C8UI_SEVERITY_SUCCESS:
		*bg = c.dark ? 0x393d1b : 0xdff6dd;
		*mark = c.dark ? 0x6ccb5f : 0x107c10;
		break;
	case C8UI_SEVERITY_WARNING:
		*bg = c.dark ? 0x433519 : 0xfff4ce;
		*mark = c.dark ? 0xfce100 : 0x9d5d00;
		break;
	case C8UI_SEVERITY_ERROR:
		*bg = c.dark ? 0x442726 : 0xfde7e9;
		*mark = c.dark ? 0xff99a4 : 0xc42b1c;
		break;
	default:
		*bg = c.dark ? 0x2b2b2b : 0xf2f2f2;
		*mark = c.accent;
		break;
	}
}

/* Buttons are the children; how wide they are together */
static double infobar_buttons_width(struct c8ui_widget *w, double *height) {
	double total = 0;
	*height = 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, 400, &cw, &ch);
		total += cw + INFO_GAP;
		*height = ch > *height ? ch : *height;
	}
	return total;
}

static double infobar_text_height(struct c8ui_widget *w, double width) {
	struct infobar *b = w->data;
	const char *family = c8ui_widget_font(w);
	double h = 0, tw, th;
	if (b->title) {
		c8ui_text_size(family, c8ui_text_font(C8UI_TEXT_BODY_STRONG),
			b->title, width, 0, &tw, &th);
		h += th;
	}
	if (b->message) {
		c8ui_text_size(family, c8ui_text_font(C8UI_TEXT_BODY), b->message,
			width, 0, &tw, &th);
		h += th;
	}
	return h;
}

/* buttons: what infobar_buttons_width says */
static double infobar_text_width(double width, double buttons) {
	double text = width - 2 * INFO_PAD - INFO_MARK - INFO_GAP - buttons;
	return text > 40 ? text : 40;
}

static void infobar_measure(struct c8ui_widget *w, double avail,
		double *width, double *height) {
	double bh;
	double bw = infobar_buttons_width(w, &bh);
	double th = infobar_text_height(w, infobar_text_width(avail, bw));
	th = th > INFO_MARK ? th : INFO_MARK;
	*width = avail;
	*height = (th > bh ? th : bh) + 2 * INFO_PAD;
}

static void infobar_layout(struct c8ui_widget *w) {
	double x = w->rect.x + w->rect.width - INFO_PAD;
	for (int i = w->child_count - 1; i >= 0; i--) {
		struct c8ui_widget *c = w->children[i];
		if (c->hidden) {
			continue;
		}
		double cw, ch;
		c8ui_widget_measure(c, 400, &cw, &ch);
		x -= cw;
		c8ui_widget_layout(c, (struct c8ui_rect){ x,
			round(w->rect.y + (w->rect.height - ch) / 2), cw, ch });
		x -= INFO_GAP;
	}
}

static void infobar_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct infobar *b = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	uint32_t bg, mark;
	infobar_colors(w, &bg, &mark);
	c8ui_set_source(cr, bg, 1);
	cairo_rectangle(cr, w->rect.x, w->rect.y, w->rect.width, w->rect.height);
	cairo_fill(cr);

	/* The mark: a filled circle with a sign in it */
	double mx = w->rect.x + INFO_PAD + INFO_MARK / 2.0;
	double bh;
	double tw = infobar_text_width(w->rect.width,
		infobar_buttons_width(w, &bh));
	double th = infobar_text_height(w, tw);
	double top = w->rect.y + INFO_PAD;
	double my = top + INFO_MARK / 2.0;
	cairo_new_path(cr);
	cairo_arc(cr, mx, my, INFO_MARK / 2.0, 0, 2 * M_PI);
	c8ui_set_source(cr, mark, 1);
	cairo_fill(cr);
	c8ui_set_source(cr, c.dark ? 0x000000 : 0xffffff, 1);
	cairo_set_line_width(cr, 2);
	switch (b->severity) {
	case C8UI_SEVERITY_SUCCESS:
		cairo_move_to(cr, mx - 5, my);
		cairo_line_to(cr, mx - 1, my + 4);
		cairo_line_to(cr, mx + 5, my - 4);
		cairo_stroke(cr);
		break;
	case C8UI_SEVERITY_ERROR:
		cairo_move_to(cr, mx - 4, my - 4);
		cairo_line_to(cr, mx + 4, my + 4);
		cairo_move_to(cr, mx + 4, my - 4);
		cairo_line_to(cr, mx - 4, my + 4);
		cairo_stroke(cr);
		break;
	case C8UI_SEVERITY_WARNING:
		cairo_move_to(cr, mx, my - 6);
		cairo_line_to(cr, mx, my + 2);
		cairo_stroke(cr);
		cairo_rectangle(cr, mx - 1, my + 4, 2, 2);
		cairo_fill(cr);
		break;
	default:
		cairo_rectangle(cr, mx - 1, my - 6, 2, 2);
		cairo_fill(cr);
		cairo_move_to(cr, mx, my - 2);
		cairo_line_to(cr, mx, my + 6);
		cairo_stroke(cr);
		break;
	}

	/* The text, centred on the mark when it is one line */
	const char *family = c8ui_widget_font(w);
	double x = w->rect.x + INFO_PAD + INFO_MARK + INFO_GAP;
	double y = th < INFO_MARK ? my - th / 2 :
		w->rect.y + (w->rect.height - th) / 2;
	c8ui_set_source(cr, c.fg, w->disabled ? 0.5 : 1);
	if (b->title) {
		y += c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_BODY_STRONG),
			b->title, x, y, tw, 0);
	}
	if (b->message) {
		c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_BODY),
			b->message, x, y, tw, 0);
	}
}

static void infobar_destroy(struct c8ui_widget *w) {
	struct infobar *b = w->data;
	free(b->title);
	free(b->message);
	free(b);
}

static const struct c8ui_widget_impl infobar_impl = {
	.name = "infobar",
	.measure = infobar_measure,
	.layout = infobar_layout,
	.draw = infobar_draw,
	.destroy = infobar_destroy,
};

/* The close button: a cross */

static void close_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	*width = *height = INFO_CLOSE;
}

static void close_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct c8ui_colors c = c8ui_widget_colors(w);
	if (w->hovered) {
		c8ui_set_source(cr, c.fg, w->pressed ? c.fill * 2.5 : c.fill * 1.5);
		cairo_rectangle(cr, w->rect.x, w->rect.y, w->rect.width,
			w->rect.height);
		cairo_fill(cr);
	}
	double cx = w->rect.x + w->rect.width / 2;
	double cy = w->rect.y + w->rect.height / 2;
	c8ui_set_source(cr, c.fg, 1);
	cairo_set_line_width(cr, 1.5);
	cairo_move_to(cr, cx - 5, cy - 5);
	cairo_line_to(cr, cx + 5, cy + 5);
	cairo_move_to(cr, cx + 5, cy - 5);
	cairo_line_to(cr, cx - 5, cy + 5);
	cairo_stroke(cr);
}

static void infobar_close(struct c8ui_widget *bar) {
	struct infobar *b = bar->data;
	c8ui_widget_set_hidden(bar, true);
	if (b->close_fn) {
		b->close_fn(bar, b->close_data);
	}
}

static void close_activate(struct c8ui_widget *w) {
	infobar_close(w->parent);
}

static bool close_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	return c8ui_push_event(w, ev, close_activate);
}

static const struct c8ui_widget_impl close_impl = {
	.name = "infobar-close",
	.measure = close_measure,
	.draw = close_draw,
	.event = close_event,
};

struct c8ui_widget *c8ui_infobar_new(enum c8ui_severity severity,
		const char *title, const char *message) {
	struct infobar *b = calloc(1, sizeof(*b));
	struct c8ui_widget *w = c8ui_widget_new(&infobar_impl, b);
	w->fill = true;
	c8ui_infobar_set(w, severity, title, message);
	return w;
}

void c8ui_infobar_set(struct c8ui_widget *w, enum c8ui_severity severity,
		const char *title, const char *message) {
	struct infobar *b = w->data;
	free(b->title);
	free(b->message);
	b->severity = severity;
	b->title = c8ui_dup_or_null(title);
	b->message = c8ui_dup_or_null(message);
	c8ui_widget_queue_layout(w);
}

struct c8ui_widget *c8ui_infobar_add_action(struct c8ui_widget *w,
		const char *label, c8ui_action_fn fn, void *data) {
	struct infobar *b = w->data;
	struct c8ui_widget *button = c8ui_button_new(label, fn, data);
	/* Before the close button, which stays last */
	int at = b->close ? w->child_count - 1 : -1;
	c8ui_widget_insert(w, at, button);
	return button;
}

void c8ui_infobar_set_closable(struct c8ui_widget *w, bool closable,
		c8ui_action_fn fn, void *data) {
	struct infobar *b = w->data;
	b->close_fn = fn;
	b->close_data = data;
	if (closable && b->close == NULL) {
		b->close = c8ui_widget_new(&close_impl, NULL);
		b->close->focusable = true;
		c8ui_widget_set_tooltip(b->close, "Close");
		c8ui_widget_add(w, b->close);
	} else if (!closable && b->close) {
		c8ui_widget_destroy(b->close);
		b->close = NULL;
	}
}

/* Semantic zoom */

#define ZOOM_MS 260
#define ZOOM_SCALE 0.3 // the view going away shrinks (or grows) this much
#define ZOOM_PINCH 0.4 // a pinch this far does the whole zoom
#define ZOOM_BUTTON 28 // the − button at the corner, for the mouse

struct zoom {
	bool out; // where it is going: the overview
	double t; // 0 the detail, 1 the overview, in between while moving
	double from;
	int64_t start; // of the animation, 0: not started
	bool pinching;
	bool button_down;
	c8ui_action_fn fn;
	void *data;
};

static bool zoom_moving(struct zoom *z) {
	return z->t != (z->out ? 1 : 0) || z->pinching;
}

/* The two views: only the one in place is shown; while moving both are
 * hidden and zoom_draw draws them itself */
static void zoom_sync(struct c8ui_widget *w) {
	struct zoom *z = w->data;
	if (w->child_count < 2) {
		return;
	}
	bool moving = zoom_moving(z);
	w->moves_children = moving;
	c8ui_widget_set_hidden(w->children[0], moving || z->t != 0);
	c8ui_widget_set_hidden(w->children[1], moving || z->t != 1);
}

static void zoom_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	*width = avail;
	*height = 0;
}

static void zoom_layout(struct c8ui_widget *w) {
	/* Both, so either can be drawn as it moves */
	for (int i = 0; i < w->child_count && i < 2; i++) {
		struct c8ui_widget *c = w->children[i];
		bool hidden = c->hidden;
		c->hidden = false;
		c8ui_widget_layout(c, w->rect);
		c->hidden = hidden;
	}
}

static void zoom_draw_view(struct c8ui_widget *w, cairo_t *cr,
		struct c8ui_widget *c, double scale, double alpha) {
	if (alpha <= 0.01) {
		return;
	}
	double cx = w->rect.x + w->rect.width / 2;
	double cy = w->rect.y + w->rect.height / 2;
	cairo_save(cr);
	cairo_translate(cr, cx, cy);
	cairo_scale(cr, scale, scale);
	cairo_translate(cr, -cx, -cy);
	cairo_push_group(cr);
	c->hidden = false;
	c8ui_widget_draw(c, cr);
	c->hidden = true;
	cairo_pop_group_to_source(cr);
	cairo_paint_with_alpha(cr, alpha);
	cairo_restore(cr);
}

static void zoom_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct zoom *z = w->data;
	if (w->child_count < 2 || !zoom_moving(z)) {
		return;
	}
	cairo_save(cr);
	cairo_rectangle(cr, w->rect.x, w->rect.y, w->rect.width, w->rect.height);
	cairo_clip(cr);
	double t = z->t;
	/* Going out, the detail shrinks away and the overview settles in
	 * from larger, as if stepping back */
	zoom_draw_view(w, cr, w->children[0], 1 - ZOOM_SCALE * t, 1 - t);
	zoom_draw_view(w, cr, w->children[1], 1 + ZOOM_SCALE * (1 - t), t);
	cairo_restore(cr);
}

static struct c8ui_rect zoom_button(struct c8ui_widget *w) {
	return (struct c8ui_rect){ w->rect.x + w->rect.width - ZOOM_BUTTON - 16,
		w->rect.y + w->rect.height - ZOOM_BUTTON - 16, ZOOM_BUTTON,
		ZOOM_BUTTON };
}

static bool zoom_button_shown(struct c8ui_widget *w) {
	struct zoom *z = w->data;
	struct c8ui_root *root = w->root;
	return root && !z->out && z->t == 0 && root->pointer_in &&
		root->touch_mouse < 0 &&
		c8ui_rect_contains(&w->rect, root->px, root->py);
}

static void zoom_draw_over(struct c8ui_widget *w, cairo_t *cr) {
	struct zoom *z = w->data;
	if (!zoom_button_shown(w)) {
		return;
	}
	struct c8ui_colors c = c8ui_widget_colors(w);
	struct c8ui_rect b = zoom_button(w);
	bool over = c8ui_rect_contains(&b, w->root->px, w->root->py);
	c8ui_set_source(cr, z->button_down && over ? c.fg : c.bg, over ? 1 : 0.8);
	cairo_rectangle(cr, b.x, b.y, b.width, b.height);
	cairo_fill(cr);
	c8ui_set_source(cr, c.fg, 0.5);
	cairo_set_line_width(cr, 1);
	cairo_rectangle(cr, b.x + 0.5, b.y + 0.5, b.width - 1, b.height - 1);
	cairo_stroke(cr);
	c8ui_set_source(cr, z->button_down && over ? c.bg : c.fg, 1);
	cairo_rectangle(cr, b.x + 8, b.y + b.height / 2 - 1, b.width - 16, 2);
	cairo_fill(cr);
}

static bool zoom_tick(struct c8ui_widget *w, int64_t now) {
	struct zoom *z = w->data;
	if (z->pinching) {
		return false;
	}
	if (z->start == 0) {
		z->start = now;
	}
	double to = z->out ? 1 : 0;
	double p = c8ui_ease_out((double)(now - z->start) / ZOOM_MS);
	z->t = z->from + (to - z->from) * p;
	c8ui_widget_queue_draw(w);
	if (p >= 1) {
		z->t = to;
		zoom_sync(w);
		return false;
	}
	return true;
}

static void zoom_go(struct c8ui_widget *w, bool out) {
	struct zoom *z = w->data;
	bool changed = z->out != out;
	z->out = out;
	z->from = z->t;
	z->start = 0;
	z->pinching = false;
	zoom_sync(w);
	c8ui_widget_animate(w);
	if (changed) {
		/* Focus in the view that went is gone: the zoom keeps the keyboard
		 * so Ctrl+plus comes back */
		if (w->root && w->root->focus == NULL) {
			c8ui_widget_grab_focus(w);
		}
		if (z->fn) {
			z->fn(w, z->data);
		}
	}
}

static bool zoom_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct zoom *z = w->data;
	if (w->child_count < 2) {
		return false;
	}
	switch (ev->type) {
	case C8UI_EVENT_SCROLL:
		if (!(ev->mods & C8UI_MOD_CTRL) || ev->dy == 0) {
			return false;
		}
		/* Ctrl and the wheel down steps back to the overview */
		zoom_go(w, ev->dy > 0);
		return true;
	case C8UI_EVENT_KEY:
		if ((ev->mods & C8UI_MOD_CTRL) && (ev->sym == XKB_KEY_minus ||
				ev->sym == XKB_KEY_KP_Subtract)) {
			zoom_go(w, true);
			return true;
		}
		if ((ev->mods & C8UI_MOD_CTRL) && (ev->sym == XKB_KEY_plus ||
				ev->sym == XKB_KEY_equal || ev->sym == XKB_KEY_KP_Add)) {
			zoom_go(w, false);
			return true;
		}
		return false;
	case C8UI_EVENT_PINCH_BEGIN:
		z->pinching = true;
		z->from = z->out ? 1 : 0;
		return true;
	case C8UI_EVENT_PINCH_UPDATE: {
		if (!z->pinching) {
			return true;
		}
		/* Fingers closing step back; opening go in */
		double t = z->from + (1 - ev->scale) / ZOOM_PINCH;
		z->t = t < 0 ? 0 : t > 1 ? 1 : t;
		zoom_sync(w);
		c8ui_widget_queue_draw(w);
		return true;
	}
	case C8UI_EVENT_PINCH_END:
		if (!z->pinching) {
			return true;
		}
		zoom_go(w, ev->cancelled ? z->out : z->t > 0.5);
		return true;
	case C8UI_EVENT_ENTER:
	case C8UI_EVENT_MOTION:
	case C8UI_EVENT_LEAVE:
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_PRESS: {
		struct c8ui_rect b = zoom_button(w);
		if (ev->button != C8UI_BUTTON_LEFT || !zoom_button_shown(w) ||
				!c8ui_rect_contains(&b, ev->x, ev->y)) {
			return false;
		}
		z->button_down = true;
		return true;
	}
	case C8UI_EVENT_RELEASE: {
		struct c8ui_rect b = zoom_button(w);
		if (z->button_down && c8ui_rect_contains(&b, ev->x, ev->y)) {
			zoom_go(w, true);
		}
		z->button_down = false;
		c8ui_widget_queue_draw(w);
		return true;
	}
	default:
		return false;
	}
}

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

static const struct c8ui_widget_impl zoom_impl = {
	.name = "zoom",
	.measure = zoom_measure,
	.layout = zoom_layout,
	.draw = zoom_draw,
	.draw_over = zoom_draw_over,
	.event = zoom_event,
	.tick = zoom_tick,
	.destroy = zoom_destroy,
	.clips = true,
};

struct c8ui_widget *c8ui_zoom_new(struct c8ui_widget *in,
		struct c8ui_widget *out, c8ui_action_fn fn, void *data) {
	struct zoom *z = calloc(1, sizeof(*z));
	z->fn = fn;
	z->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&zoom_impl, z);
	w->fill = true;
	w->expand = true;
	w->focusable = true;
	c8ui_widget_add(w, in);
	c8ui_widget_add(w, out);
	zoom_sync(w);
	return w;
}

bool c8ui_zoom_get(struct c8ui_widget *w) {
	return ((struct zoom *)w->data)->out;
}

void c8ui_zoom_set(struct c8ui_widget *w, bool out) {
	zoom_go(w, out);
}

void c8ui_zoom_in_to(struct c8ui_widget *w, struct c8ui_widget *target) {
	zoom_go(w, false);
	if (target == NULL) {
		return;
	}
	/* Laid out where it will be, then scrolled to, as it comes in */
	if (w->root && w->root->needs_layout) {
		c8ui_widget_layout(w, w->rect);
	}
	struct c8ui_widget *in = w->children[0];
	bool hidden = in->hidden;
	in->hidden = false;
	/* Asking for a page's worth from its top brings the group to the top,
	 * not just into sight */
	struct c8ui_rect r = target->rect;
	double page = in->rect.height - 48; // the margins reveal keeps
	r.height = page > r.height ? page : r.height;
	c8ui_widget_reveal(target, &r);
	in->hidden = hidden;
}
