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

/* Containers that move: the pivot, the hub, and flyouts */

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

static double text_h(struct c8ui_widget *w, enum c8ui_text_style style) {
	double tw, th;
	c8ui_text_size(c8ui_widget_font(w), c8ui_text_font(style), "Ag", 0, 0,
		&tw, &th);
	return th;
}

static double text_w(struct c8ui_widget *w, enum c8ui_text_style style,
		const char *text) {
	double tw, th;
	c8ui_text_size(c8ui_widget_font(w), c8ui_text_font(style), text, 0, 0,
		&tw, &th);
	return tw;
}

/* Pivot */

#define PIVOT_HEADER_GAP 28 // between headers
#define PIVOT_BELOW 16 // between the headers and the page
#define PIVOT_SLIDE 80 // a new page comes in from this far to the side
#define PIVOT_SWIPE 0.2 // of the width, a swipe that changes page
#define PIVOT_FLICK 0.4 // px/ms, a flick that does
#define PIVOT_TITLE_GAP 6 // under the title

struct pivot {
	char **titles;
	char *title; // small capitals over the headers; NULL: none
	int count, selected, hover, pressed;
	double offset; // the page, sideways: dragged or sliding in
	double header_scroll; // so the selected header shows
	/* c8ui_pivot_set_wrap: the headers go round, the selected one
	 * first; header_shift is how far they still have to slide */
	bool wrap;
	double header_shift;
	/* Where the pointer last was over the pivot, for the hover when
	 * the headers move under a pointer that doesn't */
	bool pointer_in;
	double pointer_x, pointer_y;
	struct c8ui_drag drag;
	struct c8ui_tab_swipe swipe;
	c8ui_action_fn fn;
	void *data;
};

static double pivot_title_height(struct c8ui_widget *w) {
	struct pivot *p = w->data;
	return p->title ? text_h(w, C8UI_TEXT_BODY_STRONG) + PIVOT_TITLE_GAP : 0;
}

/* Where the headers' row starts, from the top */
static double pivot_headers_y(struct c8ui_widget *w) {
	return w->rect.y + pivot_title_height(w);
}

/* The title and the headers: where the page starts */
static double pivot_header_height(struct c8ui_widget *w) {
	return pivot_title_height(w) + text_h(w, C8UI_TEXT_SUBHEADER) +
		PIVOT_BELOW;
}

static double header_step(struct c8ui_widget *w, int i) {
	struct pivot *p = w->data;
	return text_w(w, C8UI_TEXT_SUBHEADER, p->titles[i]) + PIVOT_HEADER_GAP;
}

/* All the headers and their gaps, once round */
static double pivot_ring(struct c8ui_widget *w) {
	struct pivot *p = w->data;
	double len = 0;
	for (int i = 0; i < p->count; i++) {
		len += header_step(w, i);
	}
	return len;
}

/* How far along from header from it is to header to, going right and
 * round the end when wrapping */
static double pivot_ahead(struct c8ui_widget *w, int from, int to) {
	struct pivot *p = w->data;
	double d = 0;
	for (int i = from; i != to; i = (i + 1) % p->count) {
		d += header_step(w, i);
	}
	return d;
}

static double pivot_header_x(struct c8ui_widget *w, int i) {
	struct pivot *p = w->data;
	if (p->wrap && p->selected >= 0) {
		return w->rect.x + p->header_shift + pivot_ahead(w, p->selected, i);
	}
	double x = w->rect.x - p->header_scroll;
	for (int j = 0; j < i; j++) {
		x += header_step(w, j);
	}
	return x;
}

static int pivot_header_at(struct c8ui_widget *w, double x, double y) {
	struct pivot *p = w->data;
	double hy = pivot_headers_y(w);
	if (y < hy || y >= w->rect.y + pivot_header_height(w)) {
		return -1;
	}
	/* Wrapping, one may also show a ring's length to the left while
	 * the headers slide */
	double ring = p->wrap ? pivot_ring(w) : 0;
	for (int i = 0; i < p->count; i++) {
		double hw = text_w(w, C8UI_TEXT_SUBHEADER, p->titles[i]);
		for (int copy = 0; copy < (p->wrap ? 2 : 1); copy++) {
			double hx = pivot_header_x(w, i) - copy * ring;
			if (x >= hx - PIVOT_HEADER_GAP / 2 &&
					x < hx + hw + PIVOT_HEADER_GAP / 2) {
				return i;
			}
		}
	}
	return -1;
}

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

/* The header under the pointer, found again after the headers moved */
static void pivot_rehover(struct c8ui_widget *w) {
	struct pivot *p = w->data;
	int i = p->pointer_in ? pivot_header_at(w, p->pointer_x, p->pointer_y) :
		-1;
	if (i != p->hover) {
		p->hover = i;
		w->cursor = i >= 0 ? C8UI_CURSOR_POINTER : C8UI_CURSOR_DEFAULT;
		c8ui_widget_queue_draw(w);
	}
}

static void pivot_layout(struct c8ui_widget *w) {
	struct pivot *p = w->data;
	/* The selected header in sight (wrapping, it is always first) */
	if (!p->wrap && p->selected >= 0 && p->selected < p->count) {
		double saved = p->header_scroll;
		p->header_scroll = 0;
		double hx = pivot_header_x(w, p->selected) - w->rect.x;
		double hw = text_w(w, C8UI_TEXT_SUBHEADER, p->titles[p->selected]);
		p->header_scroll = saved;
		if (hx + hw - p->header_scroll > w->rect.width) {
			p->header_scroll = hx + hw - w->rect.width;
		}
		if (hx < p->header_scroll) {
			p->header_scroll = hx;
		}
	}
	double top = pivot_header_height(w);
	for (int i = 0; i < w->child_count; i++) {
		struct c8ui_widget *c = w->children[i];
		c->hidden = i != p->selected;
		c8ui_widget_layout(c, (struct c8ui_rect){ w->rect.x, w->rect.y + top,
			w->rect.width, w->rect.height - top });
	}
	pivot_rehover(w); // the selected one scrolled into sight
}

static void pivot_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct pivot *p = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	cairo_rectangle(cr, w->rect.x, w->rect.y, w->rect.width, w->rect.height);
	cairo_clip(cr);
	const char *family = c8ui_widget_font(w);
	if (p->title) {
		c8ui_set_source(cr, c.fg, w->disabled ? 0.5 : 1);
		c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_BODY_STRONG),
			p->title, w->rect.x, w->rect.y, w->rect.width, 1);
	}
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_SUBHEADER);
	double hy = pivot_headers_y(w);
	double ring = p->wrap ? pivot_ring(w) : 0;
	for (int i = 0; i < p->count; i++) {
		double alpha = i == p->selected ? 1 : i == p->hover ? 0.7 : 0.4;
		c8ui_set_source(cr, c.fg, w->disabled ? alpha * 0.5 : alpha);
		double hx = pivot_header_x(w, i);
		c8ui_text_draw(cr, family, font, p->titles[i], hx, hy, 0, 0);
		if (p->wrap && p->header_shift > 0 && hx - ring + header_step(w, i) >
				w->rect.x) {
			/* Sliding left: the one going off the left edge, which
			 * already has its place at the end of the row */
			c8ui_text_draw(cr, family, font, p->titles[i], hx - ring, hy, 0, 0);
		}
	}
	if (w->focused && w->root && w->root->focus_visible &&
			p->selected >= 0) {
		double hx = pivot_header_x(w, p->selected);
		double hw = text_w(w, C8UI_TEXT_SUBHEADER, p->titles[p->selected]);
		c8ui_set_source(cr, c.fg, 1);
		c8ui_dotted_rect(cr, hx - 3.5, hy + 0.5, hw + 7,
			text_h(w, C8UI_TEXT_SUBHEADER) + 4);
	}
	/* The page follows the finger, or slides in; children draw after */
	cairo_translate(cr, round(p->offset), 0);
}

static bool pivot_tick(struct c8ui_widget *w, int64_t now) {
	struct pivot *p = w->data;
	bool more = false;
	if (p->header_shift != 0) {
		p->header_shift *= 0.72;
		if (fabs(p->header_shift) < 0.5) {
			p->header_shift = 0;
		}
		more = p->header_shift != 0;
		c8ui_widget_queue_draw(w);
		pivot_rehover(w);
	}
	if (p->drag.active) {
		return more;
	}
	p->offset *= 0.72;
	c8ui_widget_queue_draw(w);
	if (fabs(p->offset) < 0.5) {
		p->offset = 0;
		w->moves_children = p->offset != 0;
		return more;
	}
	return true;
}

/* dir: which side the new page comes in from (1: the right) */
static void pivot_go(struct c8ui_widget *w, int index, int dir) {
	struct pivot *p = w->data;
	if (p->count == 0) {
		return;
	}
	index = ((index % p->count) + p->count) % p->count;
	if (index == p->selected) {
		c8ui_widget_animate(w); // back into place
		return;
	}
	if (p->wrap && p->selected >= 0) {
		/* The headers slide round from where they are now: the new one
		 * starts where it is and goes to the left edge */
		double from = pivot_header_x(w, index) - w->rect.x;
		double ring = pivot_ring(w);
		if (dir < 0 && from > 0) {
			from -= ring; // it comes in from the left, round the end
		}
		p->header_shift = from;
	}
	p->selected = index;
	p->offset = dir * PIVOT_SLIDE;
	w->moves_children = p->offset != 0;
	c8ui_widget_queue_layout(w);
	c8ui_widget_animate(w);
	if (p->fn) {
		p->fn(w, p->data);
	}
}

static bool pivot_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct pivot *p = w->data;
	int step;
	switch (ev->type) {
	case C8UI_EVENT_SWIPE_BEGIN:
		if (p->count < 2) {
			return false;
		}
		/* fall through */
	case C8UI_EVENT_SWIPE_UPDATE:
	case C8UI_EVENT_SWIPE_END: {
		bool took = c8ui_tab_swipe(&p->swipe, ev, &step);
		if (step) {
			pivot_go(w, p->selected + step, step);
		}
		return took;
	}
	case C8UI_EVENT_TOUCH_DOWN:
		if (p->count < 2 || p->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, &p->drag, ev)) {
		case C8UI_DRAG_IGNORED:
			return false;
		case C8UI_DRAG_START:
		case C8UI_DRAG_MOVE:
			p->offset = p->drag.delta;
			w->moves_children = p->offset != 0;
			c8ui_widget_queue_draw(w);
			return true;
		case C8UI_DRAG_END: {
			double d = p->drag.delta;
			if (fabs(d) > w->rect.width * PIVOT_SWIPE ||
					fabs(p->drag.velocity) > PIVOT_FLICK) {
				int dir = (d != 0 ? d : p->drag.velocity) < 0 ? 1 : -1;
				pivot_go(w, p->selected + dir, dir);
			} else {
				c8ui_widget_animate(w);
			}
			return true;
		}
		case C8UI_DRAG_CANCEL:
			c8ui_widget_animate(w);
			return true;
		default:
			return true;
		}
	case C8UI_EVENT_MOTION:
		p->pointer_in = true;
		p->pointer_x = ev->x;
		p->pointer_y = ev->y;
		pivot_rehover(w);
		return false;
	case C8UI_EVENT_LEAVE:
		p->pointer_in = false;
		p->hover = -1;
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_PRESS:
		p->pressed = ev->button == C8UI_BUTTON_LEFT ?
			pivot_header_at(w, ev->x, ev->y) : -1;
		return p->pressed >= 0;
	case C8UI_EVENT_RELEASE:
		if (p->pressed >= 0 &&
				pivot_header_at(w, ev->x, ev->y) == p->pressed) {
			/* Wrapping, every other header is to the right */
			pivot_go(w, p->pressed, p->wrap || p->pressed > p->selected ?
				1 : -1);
		}
		p->pressed = -1;
		return true;
	case C8UI_EVENT_KEY: {
		bool ctrl = ev->mods & C8UI_MOD_CTRL;
		bool shift = ev->mods & C8UI_MOD_SHIFT;
		if ((ctrl && (ev->sym == XKB_KEY_Tab ||
				ev->sym == XKB_KEY_ISO_Left_Tab)) ||
				(ctrl && (ev->sym == XKB_KEY_Next ||
				ev->sym == XKB_KEY_Prior))) {
			int dir = ev->sym == XKB_KEY_Prior || shift ||
				ev->sym == XKB_KEY_ISO_Left_Tab ? -1 : 1;
			pivot_go(w, p->selected + dir, dir);
			return true;
		}
		/* The arrows only while the headers have the keyboard */
		if (w->focused && !ctrl &&
				(ev->sym == XKB_KEY_Left || ev->sym == XKB_KEY_Right)) {
			int dir = ev->sym == XKB_KEY_Left ? -1 : 1;
			pivot_go(w, p->selected + dir, dir);
			return true;
		}
		return false;
	}
	default:
		return false;
	}
}

static void pivot_destroy(struct c8ui_widget *w) {
	struct pivot *p = w->data;
	c8ui_drag_finish(&p->drag);
	for (int i = 0; i < p->count; i++) {
		free(p->titles[i]);
	}
	free(p->titles);
	free(p->title);
	free(p);
}

static const struct c8ui_widget_impl pivot_impl = {
	.name = "pivot",
	.measure = pivot_measure,
	.layout = pivot_layout,
	.draw = pivot_draw,
	.event = pivot_event,
	.tick = pivot_tick,
	.destroy = pivot_destroy,
	.clips = true,
};

struct c8ui_widget *c8ui_pivot_new(c8ui_action_fn fn, void *data) {
	struct pivot *p = calloc(1, sizeof(*p));
	p->hover = p->pressed = -1;
	p->drag.axis = C8UI_HORIZONTAL;
	p->fn = fn;
	p->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&pivot_impl, p);
	w->focusable = true;
	w->fill = true;
	return w;
}

void c8ui_pivot_add(struct c8ui_widget *w, const char *title,
		struct c8ui_widget *page) {
	struct pivot *p = w->data;
	p->titles = realloc(p->titles, sizeof(char *) * (p->count + 1));
	p->titles[p->count++] = strdup(title ? title : "");
	page->hidden = p->count - 1 != p->selected;
	c8ui_widget_add(w, page);
	c8ui_widget_queue_layout(w);
}

int c8ui_pivot_get(struct c8ui_widget *w) {
	return ((struct pivot *)w->data)->selected;
}

void c8ui_pivot_set(struct c8ui_widget *w, int index) {
	struct pivot *p = w->data;
	if (index < 0 || index >= p->count || index == p->selected) {
		return;
	}
	p->selected = index;
	p->offset = 0;
	p->header_shift = 0;
	w->moves_children = p->offset != 0;
	c8ui_widget_queue_layout(w);
}

void c8ui_pivot_set_wrap(struct c8ui_widget *w, bool wrap) {
	struct pivot *p = w->data;
	p->wrap = wrap;
	p->header_shift = 0;
	p->header_scroll = 0;
	c8ui_widget_queue_layout(w);
}

void c8ui_pivot_set_title(struct c8ui_widget *w, const char *title) {
	struct pivot *p = w->data;
	free(p->title);
	/* In capitals, as Metro writes an app's name over its pivot */
	p->title = title && *title ? g_utf8_strup(title, -1) : NULL;
	c8ui_widget_queue_layout(w);
}

/* Hub */

#define HUB_PAD 60 // left of the title and the first section, right of the last
#define HUB_GAP 80 // between sections
#define HUB_TOP 30
#define HUB_TITLE_GAP 24
#define HUB_HEADER_GAP 12
#define HUB_BOTTOM 24
#define HUB_PARALLAX 0.4 // how much slower the title moves
#define HUB_BG_PARALLAX 0.5 // the background at most, see hub_draw
#define HUB_FLING_MS 320
#define HUB_PEEK 160 // of the next section, beside a full one of width 0
#define HUB_NARROW_PAD C8UI_HUB_NARROW_EDGE
#define HUB_NARROW_TOP 6

struct hub {
	char *title;
	struct hub_section {
		char *header;
		char *name; // its pivot header when narrow, if it has none
		double width; // 0: the hub's less a peek of the next
		bool full; // edge to edge and top to bottom, no header
		bool was_fill; // the content's own, while a column has it
		struct c8ui_widget *content;
	} *sections;
	/* Narrow, the hub is a pivot of its named sections, which are the
	 * pivot's while it is; those without a name are left out. Or, with
	 * c8ui_hub_set_narrow_column, one column of them all going down
	 * (column, a scroll), each named one under its name. */
	struct c8ui_widget *pivot, *column, *column_title;
	bool column_mode;
	int column_at; // a section to bring into view once laid out, or -1
	/* A section to pan to once laid out wide, or -1: a section without
	 * a width is as wide as the hub, which isn't known until then */
	int wide_at;
	int count;
	double offset, target, content;
	struct c8ui_drag drag;
	double drag_offset;
	struct c8ui_tab_swipe swipe;
	struct c8ui_pad pad;
	/* HUB_PAD, HUB_GAP, HUB_TOP and HUB_BOTTOM unless set: see
	 * c8ui_hub_set_spacing */
	double edge, gap, top, bottom;
	cairo_surface_t *background; // NULL: none, see c8ui_hub_set_background
};

static double hub_title_height(struct c8ui_widget *w) {
	struct hub *h = w->data;
	return h->title ? text_h(w, C8UI_TEXT_HEADER) + HUB_TITLE_GAP : 0;
}

static double hub_header_y(struct c8ui_widget *w) {
	return w->rect.y + ((struct hub *)w->data)->top + hub_title_height(w);
}

/* Room for headers only when some section has one */
static double hub_content_y(struct c8ui_widget *w) {
	struct hub *h = w->data;
	bool headers = false;
	for (int i = 0; i < h->count; i++) {
		headers |= h->sections[i].header != NULL;
	}
	return hub_header_y(w) + (headers ? text_h(w, C8UI_TEXT_SUBHEADER) +
		HUB_HEADER_GAP : 0);
}

static double hub_width(struct c8ui_widget *w, int i) {
	struct hub *h = w->data;
	if (h->sections[i].width > 0) {
		return h->sections[i].width;
	}
	double width = w->rect.width - HUB_PEEK;
	return width > 400 ? width : 400;
}

/* A full first section starts at the edge, not after the margin */
static double hub_start(struct c8ui_widget *w) {
	struct hub *h = w->data;
	return h->count && h->sections[0].full ? 0 : ((struct hub *)w->data)->edge;
}

static double hub_max(struct c8ui_widget *w) {
	struct hub *h = w->data;
	double max = h->content - w->rect.width;
	return max > 0 ? max : 0;
}

/* How far along the sections section i starts */
static double hub_section_pos(struct c8ui_widget *w, int i) {
	double pos = 0;
	for (int j = 0; j < i; j++) {
		pos += hub_width(w, j) + ((struct hub *)w->data)->gap;
	}
	return pos;
}

/* Where section i starts, at the current offset */
static double hub_section_x(struct c8ui_widget *w, int i) {
	struct hub *h = w->data;
	return w->rect.x + hub_start(w) - h->offset + hub_section_pos(w, i);
}

static void hub_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	*width = avail;
	*height = 0; // as tall as it is given
}

/* Narrow: the sections are the pivot's or the column's */
static bool hub_folded(struct hub *h) {
	return h->pivot || h->column;
}

static void hub_layout(struct c8ui_widget *w) {
	struct hub *h = w->data;
	if (h->column) {
		c8ui_widget_layout(h->column, w->rect);
		if (h->column_at >= 0) {
			struct c8ui_widget *holder =
				h->sections[h->column_at].content->parent;
			h->column_at = -1;
			/* Its top at the top: the column's child starts at
			 * the column's top less how far it is along */
			c8ui_scroll_to(h->column,
				holder->rect.y - h->column->children[0]->rect.y);
		}
		return;
	}
	if (h->pivot) {
		c8ui_widget_layout(h->pivot, (struct c8ui_rect){
			w->rect.x + HUB_NARROW_PAD, w->rect.y + HUB_NARROW_TOP,
			w->rect.width - HUB_NARROW_PAD,
			w->rect.height - HUB_NARROW_TOP });
		return;
	}
	h->content = hub_start(w) + ((struct hub *)w->data)->edge;
	for (int i = 0; i < h->count; i++) {
		h->content += hub_width(w, i) + (i ? ((struct hub *)w->data)->gap : 0);
	}
	if (h->wide_at >= 0) {
		h->offset = h->target = hub_section_pos(w, h->wide_at);
		h->wide_at = -1;
	}
	double max = hub_max(w);
	h->offset = h->offset > max ? max : h->offset;
	h->target = h->target > max ? max : h->target;
	double top = hub_content_y(w);
	double bottom = w->rect.y + w->rect.height - ((struct hub *)w->data)->bottom;
	for (int i = 0; i < h->count; i++) {
		bool full = h->sections[i].full;
		c8ui_widget_layout(h->sections[i].content, (struct c8ui_rect){
			hub_section_x(w, i), full ? w->rect.y : top, hub_width(w, i),
			full ? w->rect.height : bottom > top ? bottom - top : 0 });
	}
}

static void hub_set_offset(struct c8ui_widget *w, double offset) {
	struct hub *h = w->data;
	double max = hub_max(w);
	offset = offset < 0 ? 0 : offset > max ? max : offset;
	if (offset == h->offset || hub_folded(h)) {
		return;
	}
	for (int i = 0; i < h->count; i++) {
		shift_x(h->sections[i].content, h->offset - offset);
	}
	h->offset = offset;
	c8ui_widget_queue_draw(w);
}

static bool hub_tick(struct c8ui_widget *w, int64_t now) {
	struct hub *h = w->data;
	double d = h->target - h->offset;
	if (fabs(d) < 0.5) {
		hub_set_offset(w, h->target);
		return false;
	}
	hub_set_offset(w, h->offset + d * 0.3);
	return true;
}

static void hub_scroll_by(struct c8ui_widget *w, double dx, bool smooth) {
	struct hub *h = w->data;
	double max = hub_max(w);
	h->target = (smooth ? h->target : h->offset) + dx;
	h->target = h->target < 0 ? 0 : h->target > max ? max : h->target;
	if (smooth) {
		c8ui_widget_animate(w);
	} else {
		hub_set_offset(w, h->target);
	}
}

/* Three fingers: the next section (step 1) or the one before to the
 * left edge, from the one there now */
static void hub_step(struct c8ui_widget *w, int step) {
	struct hub *h = w->data;
	int at = 0;
	double pos = 0, best = INFINITY;
	for (int i = 0; i < h->count; i++) {
		if (fabs(pos - h->target) < best) {
			best = fabs(pos - h->target);
			at = i;
		}
		pos += hub_width(w, i) + ((struct hub *)w->data)->gap;
	}
	int to = at + step;
	if (to < 0 || to >= h->count) {
		return;
	}
	hub_scroll_by(w, hub_section_pos(w, to) - h->target, true);
}

static void hub_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct hub *h = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	cairo_rectangle(cr, w->rect.x, w->rect.y, w->rect.width, w->rect.height);
	cairo_clip(cr);
	if (h->background &&
			cairo_surface_get_type(h->background) == CAIRO_SURFACE_TYPE_IMAGE) {
		/* As tall as the hub (or as wide, if that's bigger), panning its
		 * extra width over the sections' whole run: its left edge at the
		 * first, its right edge at the last, so it never runs out. Never
		 * faster than HUB_BG_PARALLAX of the sections, though: one wider
		 * than that loses its right-hand part, or it would race ahead of
		 * them. c8ui_draw_surface keeps the scaled copy, so a frame is a
		 * copy. */
		double iw = cairo_image_surface_get_width(h->background);
		double ih = cairo_image_surface_get_height(h->background);
		if (iw > 0 && ih > 0) {
			double s = fmax(w->rect.height / ih, w->rect.width / iw);
			double bw = round(iw * s), bh = round(ih * s);
			double max = hub_max(w);
			double extra = fmin(bw - w->rect.width, max * HUB_BG_PARALLAX);
			double pan = max > 0 ? extra * h->offset / max : 0;
			c8ui_draw_surface(cr, h->background, round(w->rect.x - pan),
				w->rect.y, bw, bh);
		}
	}
	if (hub_folded(h)) {
		return; // the pivot or the column has the title and headers
	}
	const char *family = c8ui_widget_font(w);
	c8ui_set_source(cr, c.fg, 1);
	if (h->title) {
		c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_HEADER), h->title,
			w->rect.x + ((struct hub *)w->data)->edge - h->offset * HUB_PARALLAX,
			w->rect.y + ((struct hub *)w->data)->top, 0, 0);
	}
	double hy = hub_header_y(w);
	for (int i = 0; i < h->count; i++) {
		if (h->sections[i].header == NULL) {
			continue;
		}
		c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_SUBHEADER),
			h->sections[i].header, hub_section_x(w, i), hy, hub_width(w, i), 1);
	}
}

static void hub_draw_over(struct c8ui_widget *w, cairo_t *cr) {
	struct hub *h = w->data;
	if (hub_folded(h) || h->content <= w->rect.width + 1) {
		return;
	}
	/* A thin indicator along the bottom */
	struct c8ui_colors c = c8ui_widget_colors(w);
	double len = w->rect.width * w->rect.width / h->content;
	len = len < 24 ? 24 : len;
	double x = w->rect.x + (w->rect.width - len) * h->offset / hub_max(w);
	c8ui_set_source(cr, c.fg, w->hovered ? 0.4 : 0.2);
	cairo_rectangle(cr, x, w->rect.y + w->rect.height - 6, len, 4);
	cairo_fill(cr);
}

static bool hub_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct hub *h = w->data;
	if (hub_folded(h)) {
		return false; // the pivot's or the column's
	}
	switch (ev->type) {
	case C8UI_EVENT_TOUCH_DOWN:
		if (hub_max(w) <= 0 || h->drag.down) {
			return false;
		}
		h->target = h->offset;
		h->drag_offset = h->offset;
		/* fall through */
	case C8UI_EVENT_TOUCH_MOTION:
	case C8UI_EVENT_TOUCH_UP:
	case C8UI_EVENT_TOUCH_CANCEL:
		switch (c8ui_drag_touch(w, &h->drag, ev)) {
		case C8UI_DRAG_IGNORED:
			return false;
		case C8UI_DRAG_START:
		case C8UI_DRAG_MOVE:
			hub_set_offset(w, h->drag_offset - h->drag.delta);
			h->target = h->offset;
			return true;
		case C8UI_DRAG_END:
			hub_scroll_by(w, -h->drag.velocity * HUB_FLING_MS, true);
			return true;
		default:
			return true;
		}
	case C8UI_EVENT_SWIPE_BEGIN:
		if (hub_max(w) <= 0) {
			return false;
		}
		/* fall through */
	case C8UI_EVENT_SWIPE_UPDATE:
	case C8UI_EVENT_SWIPE_END: {
		int step;
		bool took = c8ui_tab_swipe(&h->swipe, ev, &step);
		if (step) {
			hub_step(w, step);
		}
		return took;
	}
	case C8UI_EVENT_SCROLL: {
		/* A wheel scrolls it sideways, whichever way it turns */
		double d = ev->dx != 0 ? ev->dx : ev->dy;
		if (d == 0 || hub_max(w) <= 0 || (ev->mods & C8UI_MOD_CTRL)) {
			return false;
		}
		if (ev->precise) {
			c8ui_pad_sample(&h->pad, d, 0);
		} else {
			c8ui_pad_reset(&h->pad);
		}
		hub_scroll_by(w, d, !ev->precise);
		return true;
	}
	case C8UI_EVENT_SCROLL_STOP: {
		double vx, vy;
		if (hub_max(w) <= 0 || !c8ui_pad_lift(&h->pad, &vx, &vy) || vx == 0) {
			return false;
		}
		hub_scroll_by(w, c8ui_pad_distance(vx), true);
		return true;
	}
	case C8UI_EVENT_KEY:
		if (ev->mods & ~C8UI_MOD_SHIFT) {
			return false;
		}
		switch (ev->sym) {
		case XKB_KEY_Page_Down:
			hub_scroll_by(w, w->rect.width * 0.8, true);
			return true;
		case XKB_KEY_Page_Up:
			hub_scroll_by(w, -w->rect.width * 0.8, true);
			return true;
		case XKB_KEY_Home:
			hub_scroll_by(w, -h->target, true);
			return true;
		case XKB_KEY_End:
			hub_scroll_by(w, hub_max(w) - h->target, true);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void hub_reveal(struct c8ui_widget *w, const struct c8ui_rect *r) {
	struct hub *h = w->data;
	if (hub_folded(h)) {
		return;
	}
	const double margin = 40;
	double left = r->x + (h->offset - h->target) - w->rect.x;
	double right = left + r->width;
	if (left < margin) {
		hub_scroll_by(w, left - margin, true);
	} else if (right > w->rect.width - margin) {
		/* Not past the left edge for something wider than the hub */
		double by = right - w->rect.width + margin;
		hub_scroll_by(w, by < left - margin ? by : left - margin, true);
	}
}

static void hub_destroy(struct c8ui_widget *w) {
	struct hub *h = w->data;
	c8ui_drag_finish(&h->drag);
	for (int i = 0; i < h->count; i++) {
		free(h->sections[i].header);
		free(h->sections[i].name);
	}
	free(h->sections);
	free(h->title);
	if (h->background) {
		cairo_surface_destroy(h->background);
	}
	free(h);
}

static const char *hub_name(struct hub *h, int i) {
	return h->sections[i].header ? h->sections[i].header :
		h->sections[i].name;
}

/* A section's place in the column: under its name, if it has one, at
 * the narrow margins; a full one (a hero) edge to edge */
static struct c8ui_widget *hub_column_holder(struct hub *h, int i) {
	struct hub_section *sec = &h->sections[i];
	struct c8ui_widget *holder = c8ui_box_new(C8UI_VERTICAL, 8);
	holder->fill = true;
	if (!sec->full) {
		c8ui_box_set_padding(holder, HUB_NARROW_PAD, 24, HUB_NARROW_PAD, 0);
	}
	if (hub_name(h, i)) {
		c8ui_widget_add(holder, c8ui_label_new(hub_name(h, i),
			C8UI_TEXT_SUBHEADER));
	}
	sec->was_fill = sec->content->fill;
	sec->content->fill = true;
	c8ui_widget_add(holder, sec->content);
	return holder;
}

/* Narrow as a column: every section, one under another, going down;
 * where the hub was along, the column starts at that section */
static void hub_to_column(struct c8ui_widget *w, int at) {
	struct hub *h = w->data;
	struct c8ui_widget *col = c8ui_box_new(C8UI_VERTICAL, 0);
	col->fill = true;
	c8ui_box_set_padding(col, 0, 0, 0, 40);
	h->column_title = NULL;
	if (h->title) {
		struct c8ui_widget *top = c8ui_box_new(C8UI_VERTICAL, 0);
		top->fill = true;
		c8ui_box_set_padding(top, HUB_NARROW_PAD, 20, HUB_NARROW_PAD, 0);
		h->column_title = c8ui_label_new(h->title, C8UI_TEXT_SUBHEADER);
		c8ui_widget_add(top, h->column_title);
		c8ui_widget_add(col, top);
	}
	for (int i = 0; i < h->count; i++) {
		c8ui_widget_add(col, hub_column_holder(h, i));
	}
	h->column = c8ui_scroll_new(col);
	h->column->fill = true;
	c8ui_widget_add(w, h->column);
	h->column_at = at > 0 ? at : -1;
}

/* Whether a section from `start` to `start + size` (relative to a view
 * `view` long) is what the view shows: half of it in view, or it fills
 * half the view. A sliver of the one before doesn't count. */
static bool hub_shows(double start, double size, double view) {
	double seen = fmin(start + size, view) - fmax(start, 0);
	return seen > 0 && (seen >= size / 2 || seen >= view / 2);
}

/* The section the wide hub shows: the first mostly in view, else the
 * one at the left edge */
static int hub_showing(struct c8ui_widget *w) {
	struct hub *h = w->data;
	int edge = 0;
	for (int i = 0; i < h->count; i++) {
		double x = hub_start(w) - h->offset + hub_section_pos(w, i);
		if (hub_shows(x, hub_width(w, i), w->rect.width)) {
			return i;
		}
		if (x <= 1) {
			edge = i;
		}
	}
	return edge;
}

/* Wide again from the column: the sections back in their places, the
 * hub showing the one the column was at (the same rule, downwards) */
static int hub_from_column(struct c8ui_widget *w) {
	struct hub *h = w->data;
	int show = -1, edge = 0;
	for (int i = 0; i < h->count && show < 0; i++) {
		struct c8ui_widget *holder = h->sections[i].content->parent;
		double y = holder->rect.y - h->column->rect.y;
		if (hub_shows(y, holder->rect.height, h->column->rect.height)) {
			show = i;
		} else if (y <= 1) {
			edge = i;
		}
	}
	if (show < 0) {
		show = edge;
	}
	for (int i = 0; i < h->count; i++) {
		struct c8ui_widget *c = h->sections[i].content;
		c8ui_widget_insert(w, i, c);
		c->fill = h->sections[i].was_fill;
	}
	c8ui_widget_destroy(h->column);
	h->column = h->column_title = NULL;
	return show;
}

/* Narrow: the named sections go into a pivot, the first one showing
 * being the one the hub showed (`hub_showing`); wide again, they come back
 * in their places and the hub shows the one the pivot had. Or, in
 * column mode, the same with the column. */
static void hub_narrow(struct c8ui_widget *w, bool narrow) {
	struct hub *h = w->data;
	if (narrow == hub_folded(h)) {
		return;
	}
	if (narrow && h->column_mode) {
		hub_to_column(w, hub_showing(w));
	} else if (!narrow && h->column) {
		int show = hub_from_column(w);
		h->wide_at = show;
	} else if (narrow) {
		int at = hub_showing(w);
		h->pivot = c8ui_pivot_new(NULL, NULL);
		c8ui_pivot_set_title(h->pivot, h->title);
		c8ui_pivot_set_wrap(h->pivot, true);
		int page = 0, n = 0;
		for (int i = 0; i < h->count; i++) {
			struct c8ui_widget *c = h->sections[i].content;
			if (hub_name(h, i) == NULL) {
				c8ui_widget_set_hidden(c, true);
				continue;
			}
			if (i <= at) {
				page = n;
			}
			n++;
			c8ui_pivot_add(h->pivot, hub_name(h, i), c);
		}
		c8ui_pivot_set(h->pivot, page);
		c8ui_widget_add(w, h->pivot);
	} else {
		int page = c8ui_pivot_get(h->pivot), n = 0, show = 0;
		for (int i = 0; i < h->count; i++) {
			struct c8ui_widget *c = h->sections[i].content;
			if (hub_name(h, i) && n++ == page) {
				show = i;
			}
			c8ui_widget_insert(w, i, c);
			c8ui_widget_set_hidden(c, false);
		}
		c8ui_widget_destroy(h->pivot);
		h->pivot = NULL;
		/* Its place along, once laid out wide; on the pivot's first
		 * page, the hub from its start, title and all (and what had no
		 * name, before it) */
		h->wide_at = page > 0 ? show : 0;
	}
	c8ui_widget_queue_layout(w);
}

static const struct c8ui_widget_impl hub_impl = {
	.name = "hub",
	.measure = hub_measure,
	.layout = hub_layout,
	.draw = hub_draw,
	.draw_over = hub_draw_over,
	.event = hub_event,
	.tick = hub_tick,
	.destroy = hub_destroy,
	.reveal = hub_reveal,
	.clips = true,
	.narrow = hub_narrow,
};

struct c8ui_widget *c8ui_hub_new(const char *title) {
	struct hub *h = calloc(1, sizeof(*h));
	h->title = c8ui_dup_or_null(title);
	h->drag.axis = C8UI_HORIZONTAL;
	h->edge = HUB_PAD;
	h->gap = HUB_GAP;
	h->top = HUB_TOP;
	h->bottom = HUB_BOTTOM;
	h->column_at = -1;
	h->wide_at = -1;
	struct c8ui_widget *w = c8ui_widget_new(&hub_impl, h);
	w->fill = true;
	return w;
}

void c8ui_hub_set_spacing(struct c8ui_widget *w, double edge, double gap,
		double top, double bottom) {
	struct hub *h = w->data;
	h->edge = edge;
	h->gap = gap;
	h->top = top;
	h->bottom = bottom;
	c8ui_widget_queue_layout(w);
}

static void hub_append(struct c8ui_widget *w, const char *header,
		struct c8ui_widget *content, double width, bool full) {
	struct hub *h = w->data;
	h->sections = realloc(h->sections,
		sizeof(*h->sections) * (h->count + 1));
	h->sections[h->count++] = (struct hub_section){
		.header = c8ui_dup_or_null(header), .width = width, .full = full,
		.content = content };
	if (h->column) {
		struct c8ui_widget *col = h->column->children[0];
		c8ui_widget_add(col, hub_column_holder(h, h->count - 1));
	} else if (h->pivot && header) {
		c8ui_pivot_add(h->pivot, header, content);
	} else {
		c8ui_widget_add(w, content);
		c8ui_widget_set_hidden(content, h->pivot != NULL);
	}
	c8ui_widget_queue_layout(w);
}

void c8ui_hub_set_width(struct c8ui_widget *w, int section, double width) {
	struct hub *h = w->data;
	if (section >= 0 && section < h->count &&
			h->sections[section].width != width) {
		h->sections[section].width = width;
		c8ui_widget_queue_layout(w);
	}
}

void c8ui_hub_set_narrow_column(struct c8ui_widget *w, bool column) {
	struct hub *h = w->data;
	h->column_mode = column;
}

void c8ui_hub_set_name(struct c8ui_widget *w, int section, const char *name) {
	struct hub *h = w->data;
	if (section >= 0 && section < h->count) {
		free(h->sections[section].name);
		h->sections[section].name = c8ui_dup_or_null(name);
	}
}

void c8ui_hub_add(struct c8ui_widget *w, const char *header,
		struct c8ui_widget *content, double width) {
	hub_append(w, header, content, width > 0 ? width : 400, false);
}

void c8ui_hub_add_full(struct c8ui_widget *w, struct c8ui_widget *content,
		double width) {
	hub_append(w, NULL, content, width > 0 ? width : 0, true);
}

void c8ui_hub_set_title(struct c8ui_widget *w, const char *title) {
	struct hub *h = w->data;
	free(h->title);
	h->title = c8ui_dup_or_null(title);
	if (h->pivot) {
		c8ui_pivot_set_title(h->pivot, title);
	}
	if (h->column_title) {
		c8ui_label_set_text(h->column_title, title ? title : "");
	}
	c8ui_widget_queue_layout(w);
}

void c8ui_hub_set_background(struct c8ui_widget *w, cairo_surface_t *surface) {
	struct hub *h = w->data;
	if (surface) {
		cairo_surface_reference(surface);
	}
	if (h->background) {
		cairo_surface_destroy(h->background);
	}
	h->background = surface;
	c8ui_widget_queue_draw(w);
}

void c8ui_hub_show(struct c8ui_widget *w, int section) {
	struct hub *h = w->data;
	if (section < 0 || section >= h->count) {
		return;
	}
	if (h->column) {
		h->column_at = section;
		c8ui_widget_queue_layout(w);
		return;
	}
	if (h->pivot) {
		int page = -1;
		for (int i = 0; i <= section; i++) {
			page += hub_name(h, i) != NULL;
		}
		if (hub_name(h, section)) {
			c8ui_pivot_set(h->pivot, page);
		}
		return;
	}
	struct c8ui_rect r = { hub_section_x(w, section), w->rect.y,
		hub_width(w, section), 1 };
	hub_reveal(w, &r);
}

/* Flyout */

#define FLYOUT_PAD 20
#define FLYOUT_MARGIN 12 // from the window's edges
#define FLYOUT_SPACE 4 // from what it hangs off
#define FLYOUT_WIDTH 420 // at most, unless the content says otherwise
#define FLYOUT_BORDER 2

struct flyout {
	struct c8ui_rect anchor, box;
	struct c8ui_widget *content;
	c8ui_flyout_fn fn;
	void *data;
	bool done;
};

static void flyout_layout(struct c8ui_widget *w) {
	struct flyout *f = w->data;
	double room = w->rect.width - 2 * FLYOUT_MARGIN - 2 * FLYOUT_PAD;
	double avail = f->content->fixed_width > 0 ? f->content->fixed_width :
		FLYOUT_WIDTH - 2 * FLYOUT_PAD;
	avail = avail > room ? room : avail;
	double cw, ch;
	c8ui_widget_measure(f->content, avail, &cw, &ch);
	if (cw > avail) {
		cw = avail;
	}
	double bw = cw + 2 * FLYOUT_PAD, bh = ch + 2 * FLYOUT_PAD;
	double maxh = w->rect.height - 2 * FLYOUT_MARGIN;
	bh = bh > maxh ? maxh : bh;

	double x = f->anchor.x;
	double right = w->rect.x + w->rect.width - FLYOUT_MARGIN;
	x = x + bw > right ? right - bw : x;
	x = x < w->rect.x + FLYOUT_MARGIN ? w->rect.x + FLYOUT_MARGIN : x;
	double below = f->anchor.y + f->anchor.height + FLYOUT_SPACE;
	double above = f->anchor.y - FLYOUT_SPACE - bh;
	double bottom = w->rect.y + w->rect.height - FLYOUT_MARGIN;
	double y = below + bh <= bottom || above < w->rect.y + FLYOUT_MARGIN ?
		below : above;
	y = y + bh > bottom ? bottom - bh : y;
	y = y < w->rect.y + FLYOUT_MARGIN ? w->rect.y + FLYOUT_MARGIN : y;

	f->box = (struct c8ui_rect){ x, y, bw, bh };
	c8ui_widget_layout(f->content, (struct c8ui_rect){ x + FLYOUT_PAD,
		y + FLYOUT_PAD, cw, bh - 2 * FLYOUT_PAD });
}

static void flyout_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct flyout *f = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	struct c8ui_rect b = f->box;
	c8ui_set_source(cr, c.bg, 1);
	cairo_rectangle(cr, b.x, b.y, b.width, b.height);
	cairo_fill(cr);
	c8ui_set_source(cr, c.fg, c.border * 0.6);
	cairo_set_line_width(cr, FLYOUT_BORDER);
	cairo_rectangle(cr, b.x + 1, b.y + 1, b.width - 2, b.height - 2);
	cairo_stroke(cr);
	cairo_rectangle(cr, b.x, b.y, b.width, b.height);
	cairo_clip(cr);
}

static void flyout_finish(struct c8ui_widget *w) {
	struct flyout *f = w->data;
	if (f->done) {
		return;
	}
	f->done = true;
	c8ui_flyout_fn fn = f->fn;
	void *data = f->data;
	c8ui_widget_destroy(w);
	if (fn) {
		fn(data);
	}
}

static bool flyout_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct flyout *f = w->data;
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		/* Light dismiss: a click elsewhere only closes it */
		if (!c8ui_rect_contains(&f->box, ev->x, ev->y)) {
			flyout_finish(w);
		}
		return true;
	case C8UI_EVENT_TOUCH_DOWN:
		if (!c8ui_rect_contains(&f->box, ev->x, ev->y)) {
			flyout_finish(w);
			return true;
		}
		return false; // a finger on the content acts as the mouse
	case C8UI_EVENT_RELEASE:
	case C8UI_EVENT_MOTION:
	case C8UI_EVENT_SCROLL:
		return true;
	case C8UI_EVENT_KEY:
		if (ev->sym == XKB_KEY_Escape) {
			flyout_finish(w);
			return true;
		}
		return false;
	default:
		return false;
	}
}

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

static const struct c8ui_widget_impl flyout_impl = {
	.name = "flyout",
	.layout = flyout_layout,
	.draw = flyout_draw,
	.event = flyout_event,
	.destroy = flyout_destroy,
};

struct c8ui_widget *c8ui_flyout_show(struct c8ui_root *root,
		const struct c8ui_rect *anchor, struct c8ui_widget *content,
		c8ui_flyout_fn fn, void *data) {
	struct flyout *f = calloc(1, sizeof(*f));
	f->anchor = *anchor;
	f->content = content;
	f->fn = fn;
	f->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&flyout_impl, f);
	w->scheme = C8UI_SCHEME_LIGHT;
	c8ui_widget_add(w, content);
	c8ui_root_push_overlay(root, w);
	struct c8ui_widget *focus = c8ui_first_focusable(content);
	if (focus) {
		c8ui_widget_grab_focus(focus);
	}
	return w;
}

void c8ui_flyout_close(struct c8ui_widget *w) {
	flyout_finish(w);
}
