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

#define CONTROL_HEIGHT 32
#define BORDER 2
#define DEFAULT_WIDTH 360

/* Helpers */

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

static bool is_left(const struct c8ui_event *ev) {
	return ev->button == C8UI_BUTTON_LEFT;
}

static char **copy_items(const char *const *items, int count) {
	char **out = calloc(count + 1, sizeof(char *));
	for (int i = 0; i < count; i++) {
		out[i] = strdup(items[i] ? items[i] : "");
	}
	return out;
}

static void free_items(char **items, int count) {
	for (int i = 0; i < count; i++) {
		free(items[i]);
	}
	free(items);
}

static double text_width(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;
}

/* Text vertically centred in a control box */
static void draw_box_text(struct c8ui_widget *w, cairo_t *cr, const char *text,
		enum c8ui_text_style style, double x, double y, double width,
		double height) {
	struct c8ui_font font = c8ui_text_font(style);
	double tw, th;
	c8ui_text_size(c8ui_widget_font(w), font, text, 0, 0, &tw, &th);
	c8ui_text_draw(cr, c8ui_widget_font(w), font, text, x,
		y + (height - th) / 2, width, 1);
}

static void chevron(cairo_t *cr, double cx, double cy, double size) {
	cairo_set_line_width(cr, 1.5);
	cairo_move_to(cr, cx - size, cy - size / 2);
	cairo_line_to(cr, cx, cy + size / 2);
	cairo_line_to(cr, cx + size, cy - size / 2);
	cairo_stroke(cr);
}

/* Button */

struct button {
	char *label;
	c8ui_action_fn fn;
	void *data;
	bool primary;
};

static void button_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct button *b = w->data;
	double tw = text_width(w, C8UI_TEXT_BODY_STRONG, b->label);
	*width = tw + 32 < 96 ? 96 : tw + 32;
	*height = CONTROL_HEIGHT + 4;
}

static void button_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct button *b = w->data;
	struct c8ui_rect r = w->rect;
	uint32_t text = c8ui_button_face(w, cr, b->primary);
	double tw = text_width(w, C8UI_TEXT_BODY_STRONG, b->label);
	c8ui_set_source(cr, text, w->disabled ? 0.4 : 1);
	draw_box_text(w, cr, b->label, C8UI_TEXT_BODY_STRONG,
		r.x + (r.width - tw) / 2, r.y, r.width, r.height);
}

static void button_activate(struct c8ui_widget *w) {
	struct button *b = w->data;
	if (b->fn) {
		b->fn(w, b->data);
	}
}

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

static void button_destroy(struct c8ui_widget *w) {
	struct button *b = w->data;
	free(b->label);
	free(b);
}

static const struct c8ui_widget_impl button_impl = {
	.name = "button",
	.measure = button_measure,
	.draw = button_draw,
	.event = button_event,
	.destroy = button_destroy,
};

struct c8ui_widget *c8ui_button_new(const char *label, c8ui_action_fn fn,
		void *data) {
	struct button *b = calloc(1, sizeof(*b));
	b->label = strdup(label ? label : "");
	b->fn = fn;
	b->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&button_impl, b);
	w->focusable = true;
	return w;
}

void c8ui_button_set_label(struct c8ui_widget *w, const char *label) {
	struct button *b = w->data;
	free(b->label);
	b->label = strdup(label ? label : "");
	c8ui_widget_queue_layout(w);
}

void c8ui_button_set_primary(struct c8ui_widget *w, bool primary) {
	struct button *b = w->data;
	b->primary = primary;
	c8ui_widget_queue_draw(w);
}

/* Link */

static void link_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct button *b = w->data;
	c8ui_text_size(c8ui_widget_font(w), c8ui_text_font(C8UI_TEXT_BODY),
		b->label, 0, 0, width, height);
}

static void link_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct button *b = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	uint32_t color = c.dark ? c8ui_shade(c.accent, 1.4) : c.accent;
	c8ui_set_source(cr, color, w->pressed ? 0.6 : 1);
	c8ui_text_draw(cr, c8ui_widget_font(w), c8ui_text_font(C8UI_TEXT_BODY),
		b->label, w->rect.x, w->rect.y, 0, 0);
	if (w->hovered) {
		cairo_rectangle(cr, w->rect.x, w->rect.y + w->rect.height - 2,
			w->rect.width, 1);
		cairo_fill(cr);
	}
}

static const struct c8ui_widget_impl link_impl = {
	.name = "link",
	.measure = link_measure,
	.draw = link_draw,
	.event = button_event,
	.destroy = button_destroy,
};

struct c8ui_widget *c8ui_link_new(const char *label, c8ui_action_fn fn,
		void *data) {
	struct c8ui_widget *w = c8ui_button_new(label, fn, data);
	w->impl = &link_impl;
	w->cursor = C8UI_CURSOR_POINTER;
	return w;
}

/* Toggle switch */

#define TRACK_W 50
#define TRACK_H 20

struct toggle {
	char *header, *caption;
	bool on;
	c8ui_action_fn fn;
	void *data;
};

static void toggle_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct toggle *t = w->data;
	double hw;
	double h = c8ui_header_height(w, t->header, avail, &hw);
	double mw = TRACK_W + 14 + text_width(w, C8UI_TEXT_BODY, "Off");
	h += TRACK_H + 6;
	if (t->caption) {
		double cw, ch;
		c8ui_text_size(c8ui_widget_font(w), c8ui_text_font(C8UI_TEXT_CAPTION),
			t->caption, avail, 0, &cw, &ch);
		h += 6 + ch;
		mw = cw > mw ? cw : mw;
	}
	*width = hw > mw ? hw : mw;
	*height = h;
}

static void toggle_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct toggle *t = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	c8ui_header_draw(w, cr, t->header, 1);
	double hw;
	double x = w->rect.x;
	double y = w->rect.y + c8ui_header_height(w, t->header, w->rect.width, &hw) + 3;

	c8ui_set_source(cr, c.fg, w->hovered ? c.border_hover : c.border);
	c8ui_stroke_rect(cr, x, y, TRACK_W, TRACK_H, BORDER);
	if (t->on) {
		c8ui_set_source(cr, c.accent, w->disabled ? 0.5 : 1);
		cairo_rectangle(cr, x + 4, y + 4, TRACK_W - 8, TRACK_H - 8);
		cairo_fill(cr);
	}
	c8ui_set_source(cr, c.fg, w->disabled ? 0.4 : 1);
	cairo_rectangle(cr, t->on ? x + TRACK_W - 12 : x, y - 3, 12, TRACK_H + 6);
	cairo_fill(cr);

	c8ui_set_source(cr, c.fg, w->disabled ? 0.4 : 1);
	draw_box_text(w, cr, t->on ? "On" : "Off", C8UI_TEXT_BODY,
		x + TRACK_W + 14, y, 0, TRACK_H);
	if (t->caption) {
		c8ui_set_source(cr, c.fg, c.fg_secondary);
		c8ui_text_draw(cr, c8ui_widget_font(w),
			c8ui_text_font(C8UI_TEXT_CAPTION), t->caption, x,
			y + TRACK_H + 9, w->rect.width + 1, 0);
	}
}

static void toggle_flip(struct c8ui_widget *w) {
	struct toggle *t = w->data;
	t->on = !t->on;
	c8ui_widget_queue_draw(w);
	if (t->fn) {
		t->fn(w, t->data);
	}
}

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

static void toggle_destroy(struct c8ui_widget *w) {
	struct toggle *t = w->data;
	free(t->header);
	free(t->caption);
	free(t);
}

static const struct c8ui_widget_impl toggle_impl = {
	.name = "toggle",
	.measure = toggle_measure,
	.draw = toggle_draw,
	.event = toggle_event,
	.destroy = toggle_destroy,
};

struct c8ui_widget *c8ui_toggle_new(const char *header, const char *caption,
		bool on, c8ui_action_fn fn, void *data) {
	struct toggle *t = calloc(1, sizeof(*t));
	t->header = c8ui_dup_or_null(header);
	t->caption = c8ui_dup_or_null(caption);
	t->on = on;
	t->fn = fn;
	t->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&toggle_impl, t);
	w->focusable = true;
	return w;
}

bool c8ui_toggle_get(struct c8ui_widget *w) {
	return ((struct toggle *)w->data)->on;
}

void c8ui_toggle_set(struct c8ui_widget *w, bool on) {
	struct toggle *t = w->data;
	if (t->on != on) {
		t->on = on;
		c8ui_widget_queue_draw(w);
	}
}

/* Slider */

#define SLIDER_TRACK 10
#define THUMB_W 10
#define THUMB_H 24

struct slider {
	char *header, *low, *high;
	char *format; // the value beside the header, or NULL
	double min, max, step, value;
	bool live;
	c8ui_action_fn fn;
	void *data;
};

/* The value as text, and the room it takes at the header's right */
static double slider_value_text(struct c8ui_widget *w, char *buf,
		size_t size) {
	struct slider *s = w->data;
	buf[0] = '\0';
	if (s->format == NULL) {
		return 0;
	}
	snprintf(buf, size, s->format, s->value);
	return text_width(w, C8UI_TEXT_BODY, buf) + 12;
}

/* The header wraps short of the value */
static double slider_header_height(struct c8ui_widget *w, double avail) {
	struct slider *s = w->data;
	char buf[64];
	double vw = slider_value_text(w, buf, sizeof(buf)), hw;
	double h = c8ui_header_height(w, s->header, avail - vw, &hw);
	if (h == 0 && buf[0]) {
		double th;
		c8ui_text_size(c8ui_widget_font(w), c8ui_text_font(C8UI_TEXT_BODY),
			buf, 0, 0, &hw, &th);
		h = th + C8UI_HEADER_GAP;
	}
	return h;
}

static double slider_track_y(struct c8ui_widget *w) {
	return w->rect.y + slider_header_height(w, w->rect.width) +
		THUMB_H / 2.0;
}

static void slider_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct slider *s = w->data;
	double room = avail < DEFAULT_WIDTH ? avail : DEFAULT_WIDTH;
	double h = slider_header_height(w, room) + THUMB_H;
	if (s->low || s->high) {
		double tw, th;
		c8ui_text_size(c8ui_widget_font(w), c8ui_text_font(C8UI_TEXT_CAPTION),
			"Ag", 0, 0, &tw, &th);
		h += 4 + th;
	}
	*width = room;
	*height = h;
}

static double slider_fraction(struct slider *s) {
	return s->max > s->min ? (s->value - s->min) / (s->max - s->min) : 0;
}

static void slider_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct slider *s = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	char value[64];
	double vw = slider_value_text(w, value, sizeof(value));
	if (s->header && s->header[0]) {
		c8ui_set_source(cr, c.fg, 1);
		c8ui_text_draw(cr, c8ui_widget_font(w),
			c8ui_text_font(C8UI_TEXT_BODY), s->header, w->rect.x, w->rect.y,
			w->rect.width - vw + 1, 0);
	}
	if (value[0]) {
		c8ui_set_source(cr, c.fg, c.fg_secondary);
		c8ui_text_draw(cr, c8ui_widget_font(w),
			c8ui_text_font(C8UI_TEXT_BODY), value,
			w->rect.x + w->rect.width - (vw - 12), w->rect.y, 0, 0);
	}
	double x = w->rect.x + THUMB_W / 2.0;
	double width = w->rect.width - THUMB_W;
	double cy = slider_track_y(w);
	double f = slider_fraction(s);

	c8ui_set_source(cr, c.fg, w->hovered ? 0.3 : 0.2);
	cairo_rectangle(cr, x, cy - SLIDER_TRACK / 2.0, width, SLIDER_TRACK);
	cairo_fill(cr);
	c8ui_set_source(cr, c.accent, w->disabled ? 0.5 : 1);
	cairo_rectangle(cr, x, cy - SLIDER_TRACK / 2.0, width * f, SLIDER_TRACK);
	cairo_fill(cr);
	c8ui_set_source(cr, c.fg, w->disabled ? 0.4 : 1);
	cairo_rectangle(cr, x + width * f - THUMB_W / 2.0, cy - THUMB_H / 2.0,
		THUMB_W, THUMB_H);
	cairo_fill(cr);

	struct c8ui_font cap = c8ui_text_font(C8UI_TEXT_CAPTION);
	c8ui_set_source(cr, c.fg, c.fg_secondary);
	if (s->low) {
		c8ui_text_draw(cr, c8ui_widget_font(w), cap, s->low, w->rect.x,
			cy + THUMB_H / 2.0 + 4, 0, 0);
	}
	if (s->high) {
		double tw = text_width(w, C8UI_TEXT_CAPTION, s->high);
		c8ui_text_draw(cr, c8ui_widget_font(w), cap, s->high,
			w->rect.x + w->rect.width - tw, cy + THUMB_H / 2.0 + 4, 0, 0);
	}
}

static double slider_snap(struct slider *s, double v) {
	if (s->step > 0) {
		v = s->min + round((v - s->min) / s->step) * s->step;
	}
	return v < s->min ? s->min : v > s->max ? s->max : v;
}

static void slider_change(struct c8ui_widget *w, double v, bool live) {
	struct slider *s = w->data;
	v = slider_snap(s, v);
	bool changed = v != s->value || s->live != live;
	s->value = v;
	s->live = live;
	c8ui_widget_queue_draw(w);
	if (changed && s->fn) {
		s->fn(w, s->data);
	}
}

static double slider_value_at(struct c8ui_widget *w, double x) {
	struct slider *s = w->data;
	double width = w->rect.width - THUMB_W;
	double t = width > 0 ? (x - w->rect.x - THUMB_W / 2.0) / width : 0;
	t = t < 0 ? 0 : t > 1 ? 1 : t;
	return s->min + t * (s->max - s->min);
}

static bool slider_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct slider *s = w->data;
	double step = s->step > 0 ? s->step : (s->max - s->min) / 20;
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		if (!is_left(ev)) {
			return false;
		}
		slider_change(w, slider_value_at(w, ev->x), true);
		return true;
	case C8UI_EVENT_MOTION:
		if (w->pressed) {
			slider_change(w, slider_value_at(w, ev->x), true);
		}
		return true;
	case C8UI_EVENT_RELEASE:
		slider_change(w, s->value, false);
		return true;
	case C8UI_EVENT_KEY:
		switch (ev->sym) {
		case XKB_KEY_Left:
		case XKB_KEY_Down:
			slider_change(w, s->value - step, false);
			return true;
		case XKB_KEY_Right:
		case XKB_KEY_Up:
			slider_change(w, s->value + step, false);
			return true;
		case XKB_KEY_Home:
			slider_change(w, s->min, false);
			return true;
		case XKB_KEY_End:
			slider_change(w, s->max, false);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void slider_destroy(struct c8ui_widget *w) {
	struct slider *s = w->data;
	free(s->header);
	free(s->low);
	free(s->high);
	free(s->format);
	free(s);
}

static const struct c8ui_widget_impl slider_impl = {
	.name = "slider",
	.measure = slider_measure,
	.draw = slider_draw,
	.event = slider_event,
	.destroy = slider_destroy,
};

struct c8ui_widget *c8ui_slider_new(const char *header, double min, double max,
		double step, double value, c8ui_action_fn fn, void *data) {
	struct slider *s = calloc(1, sizeof(*s));
	s->header = c8ui_dup_or_null(header);
	s->min = min;
	s->max = max;
	s->step = step;
	s->value = slider_snap(s, value);
	s->fn = fn;
	s->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&slider_impl, s);
	w->focusable = true;
	return w;
}

double c8ui_slider_get(struct c8ui_widget *w) {
	return ((struct slider *)w->data)->value;
}

bool c8ui_slider_is_live(struct c8ui_widget *w) {
	return ((struct slider *)w->data)->live;
}

void c8ui_slider_set(struct c8ui_widget *w, double value) {
	struct slider *s = w->data;
	if (w->pressed) {
		return; /* the user is holding it */
	}
	s->value = slider_snap(s, value);
	c8ui_widget_queue_draw(w);
}

void c8ui_slider_set_labels(struct c8ui_widget *w, const char *low,
		const char *high) {
	struct slider *s = w->data;
	free(s->low);
	free(s->high);
	s->low = c8ui_dup_or_null(low);
	s->high = c8ui_dup_or_null(high);
	c8ui_widget_queue_layout(w);
}

void c8ui_slider_set_format(struct c8ui_widget *w, const char *format) {
	struct slider *s = w->data;
	free(s->format);
	s->format = c8ui_dup_or_null(format);
	c8ui_widget_queue_layout(w);
}

/* Text entry */

#define ENTRY_PAD 8
#define BLINK_MS 530

struct entry {
	char *header, *placeholder;
	struct c8ui_textedit *te;
	char *original; // the text when focus came in
	double scroll;
	bool caret_on, password;
	bool search, button_hover, button_down; // the magnifier at the end
	void *blink;
	struct c8ui_root *blink_root;
	c8ui_action_fn fn, change_fn;
	void *data, *change_data;
	bool enter_only; // fn not run when focus leaves
	/* Suggestions under it while typing, and their popup when shown */
	char **suggestions;
	int suggestion_count;
	struct c8ui_widget *suggest;
};

static void suggest_close(struct c8ui_widget *entry);

static struct c8ui_font entry_font(void) {
	return c8ui_text_font(C8UI_TEXT_BODY);
}

/* The box of a control that has a header over it */
static struct c8ui_rect box_under(struct c8ui_widget *w, const char *header) {
	double hh = c8ui_header_height(w, header, w->rect.width, NULL);
	return (struct c8ui_rect){ w->rect.x, w->rect.y + hh, w->rect.width,
		CONTROL_HEIGHT };
}

static struct c8ui_rect entry_box(struct c8ui_widget *w) {
	return box_under(w, ((struct entry *)w->data)->header);
}

static void entry_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct entry *e = w->data;
	double hw;
	*height = c8ui_header_height(w, e->header, avail, &hw) + CONTROL_HEIGHT;
	*width = avail < DEFAULT_WIDTH ? avail : DEFAULT_WIDTH;
}

/* How much of the end the search button takes */
static double entry_button_width(struct entry *e) {
	return e->search ? CONTROL_HEIGHT : 0;
}

static struct c8ui_rect entry_button(struct c8ui_widget *w) {
	struct entry *e = w->data;
	struct c8ui_rect r = entry_box(w);
	double bw = entry_button_width(e);
	return (struct c8ui_rect){ r.x + r.width - bw, r.y, bw, r.height };
}

static void entry_keep_caret_visible(struct c8ui_widget *w) {
	struct entry *e = w->data;
	/* Not laid out yet (set_search right after new): against a width of
	 * nothing, the text given to new was scrolled out of sight */
	double room = w->rect.width - 2 * ENTRY_PAD - entry_button_width(e);
	if (room <= 0) {
		return;
	}
	c8ui_textedit_scroll_to_caret(e->te, c8ui_widget_font(w), entry_font(),
		room, &e->scroll);
}

/* A magnifier: a ring with a handle down to the left */
static void draw_magnifier(cairo_t *cr, double cx, double cy) {
	cairo_new_path(cr);
	cairo_set_line_width(cr, 1.6);
	cairo_arc(cr, cx + 2, cy - 2, 5, 0, 2 * M_PI);
	cairo_stroke(cr);
	cairo_set_line_width(cr, 2.2);
	cairo_move_to(cr, cx - 1.5, cy + 1.5);
	cairo_line_to(cr, cx - 6, cy + 6);
	cairo_stroke(cr);
}

static void entry_draw_button(struct c8ui_widget *w, cairo_t *cr) {
	struct entry *e = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	struct c8ui_rect b = entry_button(w);
	double inset = c.dark ? 0 : BORDER;
	bool down = e->button_down && e->button_hover;
	if (down || e->button_hover) {
		if (down) {
			c8ui_set_source(cr, c.accent, 1);
		} else {
			cairo_set_source_rgba(cr, 0, 0, 0, 0.1);
		}
		cairo_rectangle(cr, b.x, b.y + inset, b.width - inset,
			b.height - 2 * inset);
		cairo_fill(cr);
	}
	if (down) {
		cairo_set_source_rgb(cr, 1, 1, 1);
	} else {
		cairo_set_source_rgba(cr, 0, 0, 0, w->disabled ? 0.4 : 0.8);
	}
	draw_magnifier(cr, b.x + b.width / 2, b.y + b.height / 2);
}

static void entry_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct entry *e = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	c8ui_header_draw(w, cr, e->header, 1);
	struct c8ui_rect r = entry_box(w);
	const char *font = c8ui_widget_font(w);
	struct c8ui_font f = entry_font();

	/* Metro text boxes are white, darker scheme or not */
	double bg_alpha = c.dark && !w->focused ? 0.8 : 1;
	cairo_set_source_rgba(cr, 1, 1, 1, w->disabled ? 0.4 : bg_alpha);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_fill(cr);
	if (!c.dark) {
		double a = w->focused ? 1 : w->hovered ? c.border_hover : c.border;
		cairo_set_source_rgba(cr, 0, 0, 0, a);
		c8ui_stroke_rect(cr, r.x, r.y, r.width, r.height, BORDER);
	}

	if (e->search) {
		entry_draw_button(w, cr);
	}

	cairo_save(cr);
	cairo_rectangle(cr, r.x + BORDER, r.y,
		r.width - 2 * BORDER - entry_button_width(e), r.height);
	cairo_clip(cr);
	double tw, th;
	c8ui_text_size(font, f, "Ag", 0, 0, &tw, &th);
	double ty = r.y + (r.height - th) / 2;
	if (c8ui_textedit_get(e->te)[0] == '\0' && e->placeholder &&
			!w->focused) {
		cairo_set_source_rgba(cr, 0, 0, 0, 0.45);
		c8ui_text_draw(cr, font, f, e->placeholder, r.x + ENTRY_PAD, ty, 0, 0);
	} else {
		bool active = w->root && w->root->keyboard_focused;
		c8ui_textedit_draw(e->te, cr, font, f, r.x + ENTRY_PAD - e->scroll,
			ty, r.y + 5, r.height - 10, c.accent, w->focused,
			w->focused && active && e->caret_on, w->disabled ? 0.5 : 1);
	}
	cairo_restore(cr);
}

static int entry_blink(void *data) {
	struct c8ui_widget *w = data;
	struct entry *e = w->data;
	/* No caret is drawn in a window without the keyboard, so nothing
	 * to repaint it for */
	if (w->root && !w->root->keyboard_focused) {
		return BLINK_MS;
	}
	e->caret_on = !e->caret_on;
	c8ui_widget_queue_draw(w);
	return BLINK_MS;
}

static void entry_restart_blink(struct c8ui_widget *w) {
	struct entry *e = w->data;
	e->caret_on = true;
	if (e->blink) {
		c8ui_root_timer_remove(e->blink_root, e->blink);
		e->blink = NULL;
	}
	if (w->focused && w->root) {
		e->blink_root = w->root;
		e->blink = c8ui_root_timer_add(w->root, BLINK_MS, entry_blink, w);
	}
}

static void entry_moved(struct c8ui_widget *w) {
	entry_keep_caret_visible(w);
	entry_restart_blink(w);
	c8ui_widget_queue_draw(w);
}

static void entry_changed(struct c8ui_widget *w) {
	struct entry *e = w->data;
	entry_moved(w);
	if (e->change_fn) {
		e->change_fn(w, e->change_data);
	}
}

static void entry_pasted(struct c8ui_textedit *te, void *data) {
	entry_changed(data);
}

/* What it says now: leaving it with something else is a change */
static void entry_remember(struct entry *e) {
	free(e->original);
	e->original = strdup(c8ui_textedit_get(e->te));
}

static void entry_activate(struct c8ui_widget *w) {
	struct entry *e = w->data;
	suggest_close(w);
	entry_remember(e);
	if (e->fn) {
		e->fn(w, e->data);
	}
}

static bool entry_key(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct entry *e = w->data;
	if (ev->sym == XKB_KEY_Return || ev->sym == XKB_KEY_KP_Enter) {
		entry_activate(w);
		return true;
	}
	switch (c8ui_textedit_key(e->te, w->root, ev)) {
	case C8UI_EDIT_CHANGED:
		entry_changed(w);
		return true;
	case C8UI_EDIT_MOVED:
		entry_moved(w);
		return true;
	default:
		return false;
	}
}

static double entry_text_x(struct c8ui_widget *w, double x) {
	struct entry *e = w->data;
	return x - (w->rect.x + ENTRY_PAD - e->scroll);
}

static bool entry_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct entry *e = w->data;
	struct c8ui_rect button = entry_button(w);
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		if (!is_left(ev)) {
			return false;
		}
		if (e->search && c8ui_rect_contains(&button, ev->x, ev->y)) {
			e->button_down = true;
			c8ui_widget_queue_draw(w);
			return true;
		}
		c8ui_textedit_press(e->te, c8ui_widget_font(w), entry_font(),
			entry_text_x(w, ev->x), ev->mods & C8UI_MOD_SHIFT);
		entry_restart_blink(w);
		c8ui_widget_queue_draw(w);
		return true;
	case C8UI_EVENT_MOTION: {
		bool over = e->search && c8ui_rect_contains(&button, ev->x, ev->y);
		if (over != e->button_hover) {
			e->button_hover = over;
			w->cursor = over ? C8UI_CURSOR_DEFAULT : C8UI_CURSOR_TEXT;
			c8ui_widget_queue_draw(w);
		}
		if (e->button_down) {
			return true;
		}
		if (w->pressed) {
			c8ui_textedit_drag(e->te, c8ui_widget_font(w), entry_font(),
				entry_text_x(w, ev->x));
			entry_keep_caret_visible(w);
			c8ui_widget_queue_draw(w);
		}
		return true;
	}
	case C8UI_EVENT_RELEASE:
		if (e->button_down) {
			e->button_down = false;
			c8ui_widget_queue_draw(w);
			if (c8ui_rect_contains(&button, ev->x, ev->y)) {
				entry_activate(w);
			}
		}
		return true;
	case C8UI_EVENT_KEY:
		return entry_key(w, ev);
	case C8UI_EVENT_FOCUS_IN:
		entry_remember(e);
		if (w->root && w->root->focus_visible) {
			/* Tabbing in selects it all, ready to type over */
			c8ui_textedit_select_all(e->te);
		}
		entry_restart_blink(w);
		return false;
	case C8UI_EVENT_FOCUS_OUT:
		suggest_close(w);
		c8ui_textedit_deselect(e->te);
		entry_restart_blink(w);
		if (!e->enter_only && e->original &&
				strcmp(e->original, c8ui_textedit_get(e->te)) != 0) {
			entry_activate(w);
		}
		return false;
	case C8UI_EVENT_LEAVE:
		e->button_hover = false;
		return false;
	default:
		return false;
	}
}

static void entry_destroy(struct c8ui_widget *w) {
	struct entry *e = w->data;
	if (e->blink) {
		c8ui_root_timer_remove(e->blink_root, e->blink);
	}
	suggest_close(w);
	free_items(e->suggestions, e->suggestion_count);
	free(e->header);
	free(e->placeholder);
	if (e->password && e->original) {
		explicit_bzero(e->original, strlen(e->original));
	}
	free(e->original);
	c8ui_textedit_free(e->te);
	free(e);
}

static const struct c8ui_widget_impl entry_impl = {
	.name = "entry",
	.measure = entry_measure,
	.draw = entry_draw,
	.event = entry_event,
	.destroy = entry_destroy,
};

struct c8ui_widget *c8ui_entry_new(const char *header, const char *text,
		c8ui_action_fn fn, void *data) {
	struct entry *e = calloc(1, sizeof(*e));
	e->header = c8ui_dup_or_null(header);
	e->te = c8ui_textedit_new(text);
	e->fn = fn;
	e->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&entry_impl, e);
	c8ui_textedit_on_change(e->te, entry_pasted, w);
	w->focusable = true;
	w->cursor = C8UI_CURSOR_TEXT;
	return w;
}

void c8ui_entry_set_enter_only(struct c8ui_widget *w, bool enter_only) {
	((struct entry *)w->data)->enter_only = enter_only;
}

const char *c8ui_entry_get(struct c8ui_widget *w) {
	return c8ui_textedit_get(((struct entry *)w->data)->te);
}

void c8ui_entry_set(struct c8ui_widget *w, const char *text) {
	struct entry *e = w->data;
	c8ui_textedit_set(e->te, text);
	if (w->focused) {
		entry_remember(e);
	}
	e->scroll = 0;
	c8ui_widget_queue_draw(w);
}

void c8ui_entry_set_placeholder(struct c8ui_widget *w, const char *text) {
	struct entry *e = w->data;
	free(e->placeholder);
	e->placeholder = c8ui_dup_or_null(text);
	c8ui_widget_queue_draw(w);
}

void c8ui_entry_set_password(struct c8ui_widget *w, bool password) {
	struct entry *e = w->data;
	e->password = password;
	c8ui_textedit_set_password(e->te, password);
	entry_keep_caret_visible(w);
	c8ui_widget_queue_draw(w);
}

void c8ui_entry_set_search(struct c8ui_widget *w, bool search) {
	struct entry *e = w->data;
	e->search = search;
	entry_keep_caret_visible(w);
	c8ui_widget_queue_draw(w);
}

void c8ui_entry_on_change(struct c8ui_widget *w, c8ui_action_fn fn, void *data) {
	struct entry *e = w->data;
	e->change_fn = fn;
	e->change_data = data;
}

/* Suggestions: a list under an entry while typing in it. It is a popup
 * overlay, so the entry keeps the keyboard: keys come here first, and the
 * ones it doesn't use go on to the entry. */

#define SUGGEST_ITEM 36
#define SUGGEST_MAX 8

struct suggest {
	struct c8ui_widget *entry;
	struct c8ui_rect list;
	int hover; // -1: none, what was typed stands
	int pressed;
	bool to_entry; // a press on the entry: the rest of it goes there
};

static int suggest_shown(struct entry *e) {
	return e->suggestion_count < SUGGEST_MAX ? e->suggestion_count :
		SUGGEST_MAX;
}

static void suggest_layout(struct c8ui_widget *w) {
	struct suggest *s = w->data;
	if (s->entry == NULL) {
		return;
	}
	struct entry *e = s->entry->data;
	struct c8ui_rect box = entry_box(s->entry);
	double h = suggest_shown(e) * SUGGEST_ITEM + 2;
	double y = box.y + box.height;
	/* No room below: above it */
	if (y + h > w->rect.y + w->rect.height - 4 && box.y - h >= w->rect.y + 4) {
		y = box.y - h;
	}
	s->list = (struct c8ui_rect){ box.x, y, box.width, h };
}

static void suggest_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct suggest *s = w->data;
	if (s->entry == NULL) {
		return;
	}
	struct entry *e = s->entry->data;
	struct c8ui_colors c = c8ui_widget_colors(s->entry);
	struct c8ui_rect r = s->list;
	/* White like the box it hangs from */
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_fill(cr);
	cairo_set_source_rgba(cr, 0, 0, 0, 0.3);
	c8ui_stroke_rect(cr, r.x, r.y, r.width, r.height, 1);
	for (int i = 0; i < suggest_shown(e); i++) {
		double y = r.y + 1 + i * SUGGEST_ITEM;
		bool on = i == s->hover;
		if (on) {
			c8ui_set_source(cr, c.accent, 1);
			cairo_rectangle(cr, r.x + 1, y, r.width - 2, SUGGEST_ITEM);
			cairo_fill(cr);
		}
		if (on) {
			cairo_set_source_rgb(cr, 1, 1, 1);
		} else {
			cairo_set_source_rgb(cr, 0, 0, 0);
		}
		draw_box_text(s->entry, cr, e->suggestions[i], C8UI_TEXT_BODY,
			r.x + ENTRY_PAD + 2, y, r.width - 2 * ENTRY_PAD, SUGGEST_ITEM);
	}
}

static int suggest_at(struct suggest *s, double x, double y) {
	if (!c8ui_rect_contains(&s->list, x, y)) {
		return -1;
	}
	int i = (int)((y - s->list.y - 1) / SUGGEST_ITEM);
	return i >= 0 && i < suggest_shown(s->entry->data) ? i : -1;
}

static void suggest_choose(struct c8ui_widget *w, int i) {
	struct suggest *s = w->data;
	struct c8ui_widget *entry = s->entry;
	struct entry *e = entry->data;
	char *text = strdup(e->suggestions[i]);
	c8ui_entry_set(entry, text);
	free(text);
	entry_keep_caret_visible(entry);
	/* As Enter: closes the list and runs the entry's fn */
	entry_activate(entry);
}

static bool suggest_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct suggest *s = w->data;
	if (s->entry == NULL) {
		return true;
	}
	struct c8ui_widget *entry = s->entry;
	struct entry *e = entry->data;
	struct c8ui_rect box = entry_box(entry);
	switch (ev->type) {
	case C8UI_EVENT_MOTION: {
		if (s->to_entry) {
			return entry_event(entry, ev);
		}
		int i = suggest_at(s, ev->x, ev->y);
		if (i >= 0 && i != s->hover) {
			s->hover = i;
			c8ui_widget_queue_draw(w);
		}
		w->cursor = c8ui_rect_contains(&box, ev->x, ev->y) ?
			C8UI_CURSOR_TEXT : C8UI_CURSOR_DEFAULT;
		return true;
	}
	case C8UI_EVENT_PRESS:
		s->to_entry = false;
		s->pressed = suggest_at(s, ev->x, ev->y);
		if (s->pressed >= 0) {
			return true;
		}
		if (c8ui_rect_contains(&box, ev->x, ev->y)) {
			s->to_entry = true;
			entry->pressed = true;
			return entry_event(entry, ev);
		}
		/* Elsewhere: gone, and the press lands where it was meant */
		c8ui_root_repress(w->root);
		suggest_close(entry);
		return true;
	case C8UI_EVENT_RELEASE:
		if (s->to_entry) {
			s->to_entry = false;
			entry->pressed = false;
			return entry_event(entry, ev);
		}
		if (s->pressed >= 0 && suggest_at(s, ev->x, ev->y) == s->pressed) {
			suggest_choose(w, s->pressed);
		}
		return true;
	case C8UI_EVENT_KEY: {
		int n = suggest_shown(e);
		if (ev->mods & (C8UI_MOD_CTRL | C8UI_MOD_ALT)) {
			return entry_event(entry, ev);
		}
		switch (ev->sym) {
		case XKB_KEY_Down:
			s->hover = s->hover + 1 < n ? s->hover + 1 : -1;
			c8ui_widget_queue_draw(w);
			return true;
		case XKB_KEY_Up:
			s->hover = s->hover < 0 ? n - 1 : s->hover - 1;
			c8ui_widget_queue_draw(w);
			return true;
		case XKB_KEY_Return:
		case XKB_KEY_KP_Enter:
			if (s->hover >= 0) {
				suggest_choose(w, s->hover);
				return true;
			}
			return entry_event(entry, ev);
		case XKB_KEY_Escape:
		case XKB_KEY_Tab:
		case XKB_KEY_ISO_Left_Tab:
			suggest_close(entry);
			return true;
		}
		/* Typing: what the list shows is the app's to change */
		s->hover = -1;
		return entry_event(entry, ev);
	}
	case C8UI_EVENT_SCROLL:
		return true;
	default:
		return false;
	}
}

static const struct c8ui_widget_impl suggest_impl = {
	.name = "suggestions",
	.layout = suggest_layout,
	.draw = suggest_draw,
	.event = suggest_event,
	.destroy = free_data_fn,
};

static void suggest_close(struct c8ui_widget *entry) {
	struct entry *e = entry->data;
	struct c8ui_widget *popup = e->suggest;
	if (popup == NULL) {
		return;
	}
	e->suggest = NULL;
	((struct suggest *)popup->data)->entry = NULL;
	c8ui_widget_destroy(popup);
}

void c8ui_entry_set_suggestions(struct c8ui_widget *w,
		const char *const *items, int count) {
	struct entry *e = w->data;
	free_items(e->suggestions, e->suggestion_count);
	e->suggestions = copy_items(items, count > 0 ? count : 0);
	e->suggestion_count = count > 0 ? count : 0;
	/* Only while it is being typed in */
	if (e->suggestion_count == 0 || !w->focused || w->root == NULL) {
		suggest_close(w);
		return;
	}
	if (e->suggest) {
		struct suggest *s = e->suggest->data;
		s->hover = -1;
		c8ui_widget_queue_layout(e->suggest);
		return;
	}
	struct suggest *s = calloc(1, sizeof(*s));
	s->entry = w;
	s->hover = s->pressed = -1;
	e->suggest = c8ui_widget_new(&suggest_impl, s);
	c8ui_root_push_popup(w->root, e->suggest);
}

/* Combo box and its drop-down */

#define ITEM_HEIGHT 40
#define POPUP_MAX_ITEMS 9

struct combo {
	char *header;
	char **items;
	int count, selected;
	c8ui_action_fn fn;
	void *data;
	struct c8ui_widget *popup;
};

struct popup {
	struct c8ui_widget *combo;
	struct c8ui_rect list;
	int hover; // highlighted item
	int first; // first item shown
	int visible;
	double wheel;
};

static struct c8ui_rect combo_box(struct c8ui_widget *w) {
	return box_under(w, ((struct combo *)w->data)->header);
}

static void combo_select(struct c8ui_widget *w, int index) {
	struct combo *cb = w->data;
	if (index < 0 || index >= cb->count || index == cb->selected) {
		return;
	}
	cb->selected = index;
	c8ui_widget_queue_draw(w);
	if (cb->fn) {
		cb->fn(w, cb->data);
	}
}

static void popup_close(struct c8ui_widget *popup) {
	struct popup *p = popup->data;
	if (p->combo) {
		struct combo *cb = p->combo->data;
		cb->popup = NULL;
		p->combo = NULL;
	}
	c8ui_widget_destroy(popup);
}

/* The list never scrolls past either end */
static void popup_clamp(struct popup *p, struct combo *cb) {
	if (p->first > cb->count - p->visible) {
		p->first = cb->count - p->visible;
	}
	if (p->first < 0) {
		p->first = 0;
	}
}

static void popup_layout(struct c8ui_widget *w) {
	struct popup *p = w->data;
	struct c8ui_widget *combo = p->combo;
	if (combo == NULL) {
		return;
	}
	struct combo *cb = combo->data;
	struct c8ui_rect box = combo_box(combo);
	double root_h = w->rect.height;
	int fit = (int)((root_h - 16) / ITEM_HEIGHT);
	p->visible = cb->count < POPUP_MAX_ITEMS ? cb->count : POPUP_MAX_ITEMS;
	if (p->visible > fit) {
		p->visible = fit > 1 ? fit : 1;
	}
	popup_clamp(p, cb);
	double h = p->visible * ITEM_HEIGHT + 2 * BORDER;
	/* The chosen entry sits over the box, as in Metro */
	double y = box.y + box.height / 2 - BORDER - ITEM_HEIGHT / 2.0 -
		(p->hover - p->first) * ITEM_HEIGHT;
	if (y + h > root_h - 8) {
		y = root_h - 8 - h;
	}
	if (y < 8) {
		y = 8;
	}
	p->list = (struct c8ui_rect){ box.x, y, box.width, h };
}

static void popup_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct popup *p = w->data;
	if (p->combo == NULL) {
		return;
	}
	struct combo *cb = p->combo->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	struct c8ui_rect r = p->list;
	c8ui_set_source(cr, c.bg, 1);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_fill(cr);
	c8ui_set_source(cr, c.fg, c.border);
	c8ui_stroke_rect(cr, r.x, r.y, r.width, r.height, BORDER);
	for (int i = 0; i < p->visible; i++) {
		int index = p->first + i;
		double y = r.y + BORDER + i * ITEM_HEIGHT;
		uint32_t text = c.fg;
		if (index == cb->selected) {
			c8ui_set_source(cr, c.accent, 1);
			cairo_rectangle(cr, r.x + BORDER, y, r.width - 2 * BORDER,
				ITEM_HEIGHT);
			cairo_fill(cr);
			text = 0xffffff;
		}
		if (index == p->hover) {
			c8ui_set_source(cr, index == cb->selected ? 0xffffff : c.fg, c.fill);
			cairo_rectangle(cr, r.x + BORDER, y, r.width - 2 * BORDER,
				ITEM_HEIGHT);
			cairo_fill(cr);
		}
		c8ui_set_source(cr, text, 1);
		draw_box_text(w, cr, cb->items[index], C8UI_TEXT_BODY, r.x + 12, y,
			r.width - 24, ITEM_HEIGHT);
	}
	if (cb->count > p->visible) {
		double th = (r.height - 2 * BORDER) * p->visible / cb->count;
		double ty = r.y + BORDER + (r.height - 2 * BORDER - th) * p->first /
			(cb->count - p->visible);
		c8ui_set_source(cr, c.fg, 0.3);
		cairo_rectangle(cr, r.x + r.width - BORDER - 4, ty, 3, th);
		cairo_fill(cr);
	}
}

static int popup_item_at(struct popup *p, double x, double y) {
	if (!c8ui_rect_contains(&p->list, x, y)) {
		return -1;
	}
	int i = (int)((y - p->list.y - BORDER) / ITEM_HEIGHT);
	if (i < 0 || i >= p->visible) {
		return -1;
	}
	return p->first + i;
}

static void popup_reveal(struct c8ui_widget *w) {
	struct popup *p = w->data;
	if (p->hover < p->first) {
		p->first = p->hover;
	} else if (p->hover >= p->first + p->visible) {
		p->first = p->hover - p->visible + 1;
	}
	c8ui_widget_queue_draw(w);
}

static void popup_choose(struct c8ui_widget *w, int index) {
	struct popup *p = w->data;
	struct c8ui_widget *combo = p->combo;
	popup_close(w);
	combo_select(combo, index);
}

static bool popup_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct popup *p = w->data;
	if (p->combo == NULL) {
		return true;
	}
	struct combo *cb = p->combo->data;
	switch (ev->type) {
	case C8UI_EVENT_MOTION: {
		int i = popup_item_at(p, ev->x, ev->y);
		if (i >= 0 && i != p->hover) {
			p->hover = i;
			c8ui_widget_queue_draw(w);
		}
		return true;
	}
	case C8UI_EVENT_PRESS:
		if (!c8ui_rect_contains(&p->list, ev->x, ev->y)) {
			popup_close(w);
		}
		return true;
	case C8UI_EVENT_RELEASE: {
		int i = popup_item_at(p, ev->x, ev->y);
		if (i >= 0) {
			popup_choose(w, i);
		}
		return true;
	}
	case C8UI_EVENT_SCROLL: {
		p->wheel += ev->dy;
		int steps = (int)(p->wheel / ITEM_HEIGHT);
		if (steps != 0) {
			p->wheel -= steps * ITEM_HEIGHT;
			p->first += steps;
			popup_clamp(p, cb);
			c8ui_widget_queue_draw(w);
		}
		return true;
	}
	case C8UI_EVENT_KEY: {
		int to = -1; // where a key that moves takes the highlight
		switch (ev->sym) {
		case XKB_KEY_Escape:
			popup_close(w);
			return true;
		case XKB_KEY_Return:
		case XKB_KEY_KP_Enter:
		case XKB_KEY_space:
			popup_choose(w, p->hover);
			return true;
		case XKB_KEY_Up:
			to = p->hover > 0 ? p->hover - 1 : 0;
			break;
		case XKB_KEY_Down:
			to = p->hover < cb->count - 1 ? p->hover + 1 : p->hover;
			break;
		case XKB_KEY_Page_Up:
			to = p->hover - p->visible > 0 ? p->hover - p->visible : 0;
			break;
		case XKB_KEY_Page_Down:
			to = p->hover + p->visible < cb->count ?
				p->hover + p->visible : cb->count - 1;
			break;
		case XKB_KEY_Home:
			to = 0;
			break;
		case XKB_KEY_End:
			to = cb->count - 1;
			break;
		}
		if (to >= 0) {
			p->hover = to;
			popup_reveal(w);
			return true;
		}
		/* Typing jumps to the next entry starting with that letter */
		if (ev->text && g_unichar_isprint(g_utf8_get_char(ev->text))) {
			gunichar want = g_unichar_tolower(g_utf8_get_char(ev->text));
			for (int n = 1; n <= cb->count; n++) {
				int i = (p->hover + n) % cb->count;
				if (g_unichar_tolower(g_utf8_get_char(cb->items[i])) == want) {
					p->hover = i;
					popup_reveal(w);
					break;
				}
			}
			return true;
		}
		return true;
	}
	default:
		return false;
	}
}

static const struct c8ui_widget_impl popup_impl = {
	.name = "popup",
	.layout = popup_layout,
	.draw = popup_draw,
	.event = popup_event,
	.destroy = free_data_fn,
};

static void combo_open(struct c8ui_widget *w) {
	struct combo *cb = w->data;
	if (w->root == NULL || cb->count == 0 || cb->popup) {
		return;
	}
	struct popup *p = calloc(1, sizeof(*p));
	p->combo = w;
	p->hover = cb->selected >= 0 ? cb->selected : 0;
	p->first = p->hover - POPUP_MAX_ITEMS / 2;
	struct c8ui_widget *popup = c8ui_widget_new(&popup_impl, p);
	struct c8ui_colors c = c8ui_widget_colors(w);
	popup->scheme = c.dark ? C8UI_SCHEME_DARK : C8UI_SCHEME_LIGHT;
	cb->popup = popup;
	c8ui_root_push_overlay(w->root, popup);
}

static void combo_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct combo *cb = w->data;
	double hw;
	*height = c8ui_header_height(w, cb->header, avail, &hw) + CONTROL_HEIGHT;
	*width = avail < DEFAULT_WIDTH ? avail : DEFAULT_WIDTH;
}

static void combo_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct combo *cb = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	c8ui_header_draw(w, cr, cb->header, 1);
	struct c8ui_rect r = combo_box(w);
	bool down = w->pressed && w->hovered;
	c8ui_set_source(cr, c.fg, down ? c.fill * 2.5 : w->hovered ? c.fill * 1.6 :
		c.fill);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_fill(cr);
	c8ui_set_source(cr, c.fg, w->hovered ? c.border_hover : c.border);
	c8ui_stroke_rect(cr, r.x, r.y, r.width, r.height, BORDER);
	c8ui_set_source(cr, c.fg, w->disabled ? 0.4 : 1);
	if (cb->selected >= 0 && cb->selected < cb->count) {
		draw_box_text(w, cr, cb->items[cb->selected], C8UI_TEXT_BODY,
			r.x + ENTRY_PAD + 2, r.y, r.width - 44, r.height);
	}
	chevron(cr, r.x + r.width - 18, r.y + r.height / 2, 5);
}

static bool combo_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct combo *cb = w->data;
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		return is_left(ev);
	case C8UI_EVENT_RELEASE:
		if (c8ui_rect_contains(&w->rect, ev->x, ev->y)) {
			combo_open(w);
		}
		return true;
	case C8UI_EVENT_KEY:
		if (c8ui_activates(ev) || ev->sym == XKB_KEY_F4 ||
				(ev->sym == XKB_KEY_Down && (ev->mods & C8UI_MOD_ALT))) {
			combo_open(w);
			return true;
		}
		if (ev->sym == XKB_KEY_Up) {
			combo_select(w, cb->selected - 1);
			return true;
		}
		if (ev->sym == XKB_KEY_Down) {
			combo_select(w, cb->selected + 1);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void combo_destroy(struct c8ui_widget *w) {
	struct combo *cb = w->data;
	if (cb->popup) {
		popup_close(cb->popup);
	}
	free(cb->header);
	free_items(cb->items, cb->count);
	free(cb);
}

static const struct c8ui_widget_impl combo_impl = {
	.name = "combo",
	.measure = combo_measure,
	.draw = combo_draw,
	.event = combo_event,
	.destroy = combo_destroy,
};

struct c8ui_widget *c8ui_combo_new(const char *header, const char *const *items,
		int count, int selected, c8ui_action_fn fn, void *data) {
	struct combo *cb = calloc(1, sizeof(*cb));
	cb->header = c8ui_dup_or_null(header);
	cb->items = copy_items(items, count);
	cb->count = count;
	cb->selected = selected < count ? selected : -1;
	cb->fn = fn;
	cb->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&combo_impl, cb);
	w->focusable = true;
	return w;
}

void c8ui_combo_set_items(struct c8ui_widget *w, const char *const *items,
		int count, int selected) {
	struct combo *cb = w->data;
	if (cb->popup) {
		popup_close(cb->popup);
	}
	free_items(cb->items, cb->count);
	cb->items = copy_items(items, count);
	cb->count = count;
	cb->selected = selected < count ? selected : -1;
	c8ui_widget_queue_draw(w);
}

int c8ui_combo_get(struct c8ui_widget *w) {
	return ((struct combo *)w->data)->selected;
}

void c8ui_combo_set(struct c8ui_widget *w, int selected) {
	struct combo *cb = w->data;
	cb->selected = selected < cb->count ? selected : -1;
	c8ui_widget_queue_draw(w);
}

/* Choice: segments side by side */

#define SEGMENT_GAP 6

struct choice {
	char *header;
	char **items;
	int count, selected, hover;
	c8ui_action_fn fn;
	void *data;
};

static double segment_width(struct c8ui_widget *w, const char *text) {
	double tw = text_width(w, C8UI_TEXT_BODY, text) + 28;
	return tw < 72 ? 72 : tw;
}

static void choice_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct choice *ch = w->data;
	double hw;
	*height = c8ui_header_height(w, ch->header, avail, &hw) + CONTROL_HEIGHT;
	double total = 0;
	for (int i = 0; i < ch->count; i++) {
		total += segment_width(w, ch->items[i]) + (i ? SEGMENT_GAP : 0);
	}
	*width = total > hw ? total : hw;
}

static int choice_at(struct c8ui_widget *w, double x, double y) {
	struct choice *ch = w->data;
	double hw;
	double top = w->rect.y + c8ui_header_height(w, ch->header, w->rect.width, &hw);
	if (y < top) {
		return -1;
	}
	double sx = w->rect.x;
	for (int i = 0; i < ch->count; i++) {
		double sw = segment_width(w, ch->items[i]);
		if (x >= sx && x < sx + sw) {
			return i;
		}
		sx += sw + SEGMENT_GAP;
	}
	return -1;
}

static void choice_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct choice *ch = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	c8ui_header_draw(w, cr, ch->header, 1);
	double hw;
	double y = w->rect.y + c8ui_header_height(w, ch->header, w->rect.width, &hw);
	double x = w->rect.x;
	for (int i = 0; i < ch->count; i++) {
		double sw = segment_width(w, ch->items[i]);
		uint32_t text = c.fg;
		if (i == ch->selected) {
			c8ui_set_source(cr, c.fg, 1);
			cairo_rectangle(cr, x, y, sw, CONTROL_HEIGHT);
			cairo_fill(cr);
			text = c.bg;
		} else {
			c8ui_set_source(cr, c.fg, i == ch->hover ? c.border_hover : c.border);
			c8ui_stroke_rect(cr, x, y, sw, CONTROL_HEIGHT, BORDER);
		}
		double tw = text_width(w, C8UI_TEXT_BODY, ch->items[i]);
		c8ui_set_source(cr, text, w->disabled ? 0.4 : 1);
		draw_box_text(w, cr, ch->items[i], C8UI_TEXT_BODY, x + (sw - tw) / 2, y,
			0, CONTROL_HEIGHT);
		x += sw + SEGMENT_GAP;
	}
}

static void choice_select(struct c8ui_widget *w, int i) {
	struct choice *ch = w->data;
	if (i < 0 || i >= ch->count || i == ch->selected) {
		return;
	}
	ch->selected = i;
	c8ui_widget_queue_draw(w);
	if (ch->fn) {
		ch->fn(w, ch->data);
	}
}

static bool choice_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct choice *ch = w->data;
	switch (ev->type) {
	case C8UI_EVENT_MOTION:
		c8ui_hover_item(w, &ch->hover, choice_at(w, ev->x, ev->y));
		return false;
	case C8UI_EVENT_LEAVE:
		c8ui_hover_item(w, &ch->hover, -1);
		return false;
	case C8UI_EVENT_PRESS:
		return is_left(ev) && choice_at(w, ev->x, ev->y) >= 0;
	case C8UI_EVENT_RELEASE:
		choice_select(w, choice_at(w, ev->x, ev->y));
		return true;
	case C8UI_EVENT_KEY:
		if (ev->sym == XKB_KEY_Left) {
			choice_select(w, ch->selected - 1);
			return true;
		}
		if (ev->sym == XKB_KEY_Right) {
			choice_select(w, ch->selected + 1);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void choice_destroy(struct c8ui_widget *w) {
	struct choice *ch = w->data;
	free(ch->header);
	free_items(ch->items, ch->count);
	free(ch);
}

static const struct c8ui_widget_impl choice_impl = {
	.name = "choice",
	.measure = choice_measure,
	.draw = choice_draw,
	.event = choice_event,
	.destroy = choice_destroy,
};

struct c8ui_widget *c8ui_choice_new(const char *header,
		const char *const *items, int count, int selected, c8ui_action_fn fn,
		void *data) {
	struct choice *ch = calloc(1, sizeof(*ch));
	ch->header = c8ui_dup_or_null(header);
	ch->items = copy_items(items, count);
	ch->count = count;
	ch->selected = selected;
	ch->hover = -1;
	ch->fn = fn;
	ch->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&choice_impl, ch);
	w->focusable = true;
	return w;
}

int c8ui_choice_get(struct c8ui_widget *w) {
	return ((struct choice *)w->data)->selected;
}

void c8ui_choice_set(struct c8ui_widget *w, int selected) {
	struct choice *ch = w->data;
	ch->selected = selected;
	c8ui_widget_queue_draw(w);
}

/* Colour swatches */

struct swatches {
	uint32_t *colors;
	int count, hover;
	double size, gap; // of a square, and between them
	uint32_t selected;
	c8ui_action_fn fn;
	void *data;
};

#define SWATCH (s->size)
#define SWATCH_GAP (s->gap)

static int swatch_columns(struct c8ui_widget *w, double width) {
	struct swatches *s = w->data;
	int cols = (int)((width + SWATCH_GAP) / (SWATCH + SWATCH_GAP));
	cols = cols < 1 ? 1 : cols;
	return cols > s->count ? (s->count > 0 ? s->count : 1) : cols;
}

static void swatches_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct swatches *s = w->data;
	int cols = swatch_columns(w, avail < 10 * (SWATCH + SWATCH_GAP) ? avail :
		10 * (SWATCH + SWATCH_GAP));
	int rows = (s->count + cols - 1) / cols;
	*width = cols * (SWATCH + SWATCH_GAP) - SWATCH_GAP + 4;
	*height = rows * (SWATCH + SWATCH_GAP) - SWATCH_GAP + 4;
}

static struct c8ui_rect swatch_rect(struct c8ui_widget *w, int i) {
	struct swatches *s = w->data;
	int cols = swatch_columns(w, w->rect.width - 4);
	return (struct c8ui_rect){
		w->rect.x + 2 + (i % cols) * (SWATCH + SWATCH_GAP),
		w->rect.y + 2 + (i / cols) * (SWATCH + SWATCH_GAP), SWATCH, SWATCH,
	};
}

static void swatches_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct swatches *s = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	for (int i = 0; i < s->count; i++) {
		struct c8ui_rect r = swatch_rect(w, i);
		c8ui_set_source(cr, s->colors[i], 1);
		cairo_rectangle(cr, r.x, r.y, r.width, r.height);
		cairo_fill(cr);
		bool sel = s->colors[i] == s->selected;
		if (sel || i == s->hover) {
			c8ui_set_source(cr, c.fg, sel ? 1 : 0.5);
			c8ui_stroke_rect(cr, r.x - 2, r.y - 2, r.width + 4, r.height + 4, 2);
		}
	}
}

static int swatch_at(struct c8ui_widget *w, double x, double y) {
	struct swatches *s = w->data;
	for (int i = 0; i < s->count; i++) {
		struct c8ui_rect r = swatch_rect(w, i);
		if (c8ui_rect_contains(&r, x, y)) {
			return i;
		}
	}
	return -1;
}

static void swatch_select(struct c8ui_widget *w, int i) {
	struct swatches *s = w->data;
	if (i < 0 || i >= s->count || s->colors[i] == s->selected) {
		return;
	}
	s->selected = s->colors[i];
	c8ui_widget_queue_draw(w);
	if (s->fn) {
		s->fn(w, s->data);
	}
}

static bool swatches_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct swatches *s = w->data;
	int current = -1;
	for (int i = 0; i < s->count; i++) {
		if (s->colors[i] == s->selected) {
			current = i;
		}
	}
	int cols = swatch_columns(w, w->rect.width - 4);
	switch (ev->type) {
	case C8UI_EVENT_MOTION:
		c8ui_hover_item(w, &s->hover, swatch_at(w, ev->x, ev->y));
		return false;
	case C8UI_EVENT_LEAVE:
		c8ui_hover_item(w, &s->hover, -1);
		return false;
	case C8UI_EVENT_PRESS:
		return is_left(ev) && swatch_at(w, ev->x, ev->y) >= 0;
	case C8UI_EVENT_RELEASE:
		swatch_select(w, swatch_at(w, ev->x, ev->y));
		return true;
	case C8UI_EVENT_KEY:
		switch (ev->sym) {
		case XKB_KEY_Left:
			swatch_select(w, current - 1);
			return true;
		case XKB_KEY_Right:
			swatch_select(w, current + 1);
			return true;
		case XKB_KEY_Up:
			swatch_select(w, current - cols);
			return true;
		case XKB_KEY_Down:
			swatch_select(w, current < 0 ? 0 : current + cols);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void swatches_destroy(struct c8ui_widget *w) {
	struct swatches *s = w->data;
	free(s->colors);
	free(s);
}

static const struct c8ui_widget_impl swatches_impl = {
	.name = "swatches",
	.measure = swatches_measure,
	.draw = swatches_draw,
	.event = swatches_event,
	.destroy = swatches_destroy,
};

struct c8ui_widget *c8ui_swatches_new(const uint32_t *colors, int count,
		uint32_t selected, c8ui_action_fn fn, void *data) {
	struct swatches *s = calloc(1, sizeof(*s));
	s->selected = selected;
	s->hover = -1;
	s->size = 36;
	s->gap = 6;
	s->fn = fn;
	s->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&swatches_impl, s);
	w->focusable = true;
	c8ui_swatches_set_colors(w, colors, count);
	return w;
}

void c8ui_swatches_set_colors(struct c8ui_widget *w, const uint32_t *colors,
		int count) {
	struct swatches *s = w->data;
	free(s->colors);
	s->colors = calloc(count + 1, sizeof(uint32_t));
	memcpy(s->colors, colors, sizeof(uint32_t) * count);
	s->count = count;
	c8ui_widget_queue_layout(w);
}

void c8ui_swatches_set_size(struct c8ui_widget *w, double size) {
	struct swatches *s = w->data;
	s->size = size;
	s->gap = size / 6;
	c8ui_widget_queue_layout(w);
}

#undef SWATCH
#undef SWATCH_GAP

uint32_t c8ui_swatches_get(struct c8ui_widget *w) {
	return ((struct swatches *)w->data)->selected;
}

void c8ui_swatches_set(struct c8ui_widget *w, uint32_t color) {
	struct swatches *s = w->data;
	s->selected = color;
	c8ui_widget_queue_draw(w);
}

/* Shortcut recorder */

struct shortcut {
	char *combo;
	bool recording;
	struct c8ui_root *inhibit_root;
	c8ui_action_fn fn;
	void *data;
};

void c8ui_format_combo(uint32_t mods, uint32_t sym, char *buf, size_t len) {
	char name[64];
	if (xkb_keysym_get_name(xkb_keysym_to_lower(sym), name, sizeof(name)) < 0) {
		snprintf(name, sizeof(name), "0x%x", sym);
	}
	snprintf(buf, len, "%s%s%s%s%s",
		(mods & C8UI_MOD_SUPER) ? "Super+" : "",
		(mods & C8UI_MOD_CTRL) ? "Ctrl+" : "",
		(mods & C8UI_MOD_ALT) ? "Alt+" : "",
		(mods & C8UI_MOD_SHIFT) ? "Shift+" : "", name);
}

static void shortcut_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	*width = avail < 220 ? avail : 220;
	*height = CONTROL_HEIGHT;
}

static void shortcut_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct shortcut *s = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	struct c8ui_rect r = w->rect;
	if (s->recording) {
		c8ui_set_source(cr, c.accent, 1);
		cairo_rectangle(cr, r.x, r.y, r.width, r.height);
		cairo_fill(cr);
		cairo_set_source_rgb(cr, 1, 1, 1);
		draw_box_text(w, cr, "Press keys…", C8UI_TEXT_BODY, r.x + ENTRY_PAD,
			r.y, r.width - 2 * ENTRY_PAD, r.height);
		return;
	}
	c8ui_set_source(cr, c.fg, w->hovered ? c.fill * 1.6 : c.fill);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_fill(cr);
	c8ui_set_source(cr, c.fg, w->hovered ? c.border_hover : c.border);
	c8ui_stroke_rect(cr, r.x, r.y, r.width, r.height, BORDER);
	bool empty = s->combo == NULL || s->combo[0] == '\0';
	c8ui_set_source(cr, c.fg, empty ? c.fg_secondary : 1);
	draw_box_text(w, cr, empty ? "Not set" : s->combo, C8UI_TEXT_BODY,
		r.x + ENTRY_PAD, r.y, r.width - 2 * ENTRY_PAD, r.height);
}

static void shortcut_record(struct c8ui_widget *w, bool on) {
	struct shortcut *s = w->data;
	if (s->recording == on) {
		return;
	}
	s->recording = on;
	if (on && w->root) {
		s->inhibit_root = w->root;
		c8ui_root_inhibit_shortcuts(w->root, true);
	} else if (!on && s->inhibit_root) {
		c8ui_root_inhibit_shortcuts(s->inhibit_root, false);
		s->inhibit_root = NULL;
	}
	c8ui_widget_queue_draw(w);
}

static bool is_modifier(uint32_t sym) {
	return (sym >= XKB_KEY_Shift_L && sym <= XKB_KEY_Hyper_R) ||
		sym == XKB_KEY_ISO_Level3_Shift || sym == XKB_KEY_ISO_Level5_Shift;
}

static bool shortcut_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct shortcut *s = w->data;
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		return is_left(ev);
	case C8UI_EVENT_RELEASE:
		if (c8ui_rect_contains(&w->rect, ev->x, ev->y)) {
			shortcut_record(w, !s->recording);
		}
		return true;
	case C8UI_EVENT_KEY:
		if (!s->recording) {
			if (c8ui_activates(ev)) {
				shortcut_record(w, true);
				return true;
			}
			return false;
		}
		if (is_modifier(ev->sym)) {
			return true;
		}
		if (ev->sym == XKB_KEY_Escape && ev->mods == 0) {
			shortcut_record(w, false);
			return true;
		}
		char combo[128];
		c8ui_format_combo(ev->mods, ev->base_sym, combo, sizeof(combo));
		free(s->combo);
		s->combo = strdup(combo);
		shortcut_record(w, false);
		if (s->fn) {
			s->fn(w, s->data);
		}
		return true;
	case C8UI_EVENT_FOCUS_OUT:
		shortcut_record(w, false);
		return false;
	default:
		return false;
	}
}

static void shortcut_destroy(struct c8ui_widget *w) {
	struct shortcut *s = w->data;
	if (s->inhibit_root) {
		c8ui_root_inhibit_shortcuts(s->inhibit_root, false);
	}
	free(s->combo);
	free(s);
}

static const struct c8ui_widget_impl shortcut_impl = {
	.name = "shortcut",
	.measure = shortcut_measure,
	.draw = shortcut_draw,
	.event = shortcut_event,
	.destroy = shortcut_destroy,
};

struct c8ui_widget *c8ui_shortcut_new(const char *combo, c8ui_action_fn fn,
		void *data) {
	struct shortcut *s = calloc(1, sizeof(*s));
	s->combo = c8ui_dup_or_null(combo);
	s->fn = fn;
	s->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&shortcut_impl, s);
	w->focusable = true;
	return w;
}

const char *c8ui_shortcut_get(struct c8ui_widget *w) {
	struct shortcut *s = w->data;
	return s->combo ? s->combo : "";
}

void c8ui_shortcut_set(struct c8ui_widget *w, const char *combo) {
	struct shortcut *s = w->data;
	free(s->combo);
	s->combo = c8ui_dup_or_null(combo);
	c8ui_widget_queue_draw(w);
}

/* Navigation list */

#define NAV_ITEM 46
#define NAV_PAD 40 // lines up with a page title in a 40px margin

struct nav {
	char **labels;
	int count, selected, hover;
	double inset;
	/* As a menu (a narrow app's page list): the arrows move a cursor and
	 * only Enter or a click opens, the current item too */
	bool menu;
	int cursor;
	c8ui_action_fn fn;
	void *data;
};

static void nav_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct nav *n = w->data;
	*width = avail;
	*height = n->count * NAV_ITEM;
}

static void nav_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct nav *n = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	for (int i = 0; i < n->count; i++) {
		double y = w->rect.y + i * NAV_ITEM;
		if (i == n->selected) {
			c8ui_set_source(cr, c.accent, 1);
			cairo_rectangle(cr, w->rect.x, y, w->rect.width, NAV_ITEM);
			cairo_fill(cr);
		} else if (i == n->hover || (n->menu && i == n->cursor &&
				c8ui_widget_shows_focus(w))) {
			c8ui_set_source(cr, c.fg, c.fill);
			cairo_rectangle(cr, w->rect.x, y, w->rect.width, NAV_ITEM);
			cairo_fill(cr);
		}
		c8ui_set_source(cr, i == n->selected ? 0xffffff : c.fg, 1);
		draw_box_text(w, cr, n->labels[i], C8UI_TEXT_ITEM, w->rect.x + n->inset,
			y, w->rect.width - 2 * n->inset, NAV_ITEM);
	}
}

static void nav_select(struct c8ui_widget *w, int i) {
	struct nav *n = w->data;
	if (i < 0 || i >= n->count || (i == n->selected && !n->menu)) {
		return;
	}
	n->selected = n->cursor = i;
	c8ui_widget_queue_draw(w);
	if (n->fn) {
		n->fn(w, n->data);
	}
}

static int nav_at(struct c8ui_widget *w, double y) {
	struct nav *n = w->data;
	int i = (int)((y - w->rect.y) / NAV_ITEM);
	return i >= 0 && i < n->count ? i : -1;
}

static bool nav_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct nav *n = w->data;
	switch (ev->type) {
	case C8UI_EVENT_MOTION:
		c8ui_hover_item(w, &n->hover, nav_at(w, ev->y));
		return false;
	case C8UI_EVENT_LEAVE:
		c8ui_hover_item(w, &n->hover, -1);
		return false;
	case C8UI_EVENT_PRESS:
		return is_left(ev);
	case C8UI_EVENT_RELEASE:
		if (c8ui_rect_contains(&w->rect, ev->x, ev->y)) {
			nav_select(w, nav_at(w, ev->y));
		}
		return true;
	case C8UI_EVENT_KEY:
		if (n->menu) {
			int to = n->cursor < 0 ? 0 : n->cursor;
			if (ev->sym == XKB_KEY_Up || ev->sym == XKB_KEY_Down) {
				to += n->cursor < 0 ? 0 : ev->sym == XKB_KEY_Up ? -1 : 1;
				c8ui_root_show_focus(w->root, true); // so the cursor shows
				if (to >= 0 && to < n->count) {
					n->cursor = to;
					c8ui_widget_reveal(w, &(struct c8ui_rect){ w->rect.x,
						w->rect.y + to * NAV_ITEM, w->rect.width, NAV_ITEM });
					c8ui_widget_queue_draw(w);
				}
				return true;
			}
			if (ev->sym == XKB_KEY_Return || ev->sym == XKB_KEY_KP_Enter ||
					ev->sym == XKB_KEY_space) {
				nav_select(w, to);
				return true;
			}
			return false;
		}
		if (ev->sym == XKB_KEY_Up) {
			nav_select(w, n->selected - 1);
			return true;
		}
		if (ev->sym == XKB_KEY_Down) {
			nav_select(w, n->selected + 1);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void nav_destroy(struct c8ui_widget *w) {
	struct nav *n = w->data;
	free_items(n->labels, n->count);
	free(n);
}

static const struct c8ui_widget_impl nav_impl = {
	.name = "nav",
	.measure = nav_measure,
	.draw = nav_draw,
	.event = nav_event,
	.destroy = nav_destroy,
};

struct c8ui_widget *c8ui_nav_new(c8ui_action_fn fn, void *data) {
	struct nav *n = calloc(1, sizeof(*n));
	n->hover = -1;
	n->inset = NAV_PAD;
	n->fn = fn;
	n->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&nav_impl, n);
	w->focusable = true;
	w->fill = true;
	return w;
}

void c8ui_nav_add(struct c8ui_widget *w, const char *label) {
	struct nav *n = w->data;
	n->labels = realloc(n->labels, sizeof(char *) * (n->count + 1));
	n->labels[n->count++] = strdup(label);
	c8ui_widget_queue_layout(w);
}

void c8ui_nav_set_inset(struct c8ui_widget *w, double inset) {
	((struct nav *)w->data)->inset = inset;
	c8ui_widget_queue_draw(w);
}

int c8ui_nav_get(struct c8ui_widget *w) {
	return ((struct nav *)w->data)->selected;
}

void c8ui_nav_set(struct c8ui_widget *w, int selected) {
	struct nav *n = w->data;
	n->selected = selected;
	n->cursor = selected;
	c8ui_widget_queue_draw(w);
}

void c8ui_nav_set_menu(struct c8ui_widget *w, bool menu) {
	struct nav *n = w->data;
	n->menu = menu;
	n->cursor = n->selected;
	c8ui_widget_queue_draw(w);
}

/* Message dialog */

struct dialog {
	struct c8ui_widget *content, *message, *buttons;
	struct c8ui_rect band;
	c8ui_dialog_fn fn;
	void *data;
	bool done;
};

static void dialog_layout(struct c8ui_widget *w) {
	struct dialog *d = w->data;
	double width = w->rect.width * 0.5;
	width = width < 320 ? (w->rect.width - 48 < 320 ? w->rect.width - 48 : 320) :
		width > 680 ? 680 : width;
	double cw, ch;
	c8ui_widget_measure(d->content, width, &cw, &ch);
	double pad = 28;
	double band_h = ch + 2 * pad;
	d->band = (struct c8ui_rect){ w->rect.x, w->rect.y +
		(w->rect.height - band_h) / 2, w->rect.width, band_h };
	c8ui_widget_layout(d->content, (struct c8ui_rect){
		w->rect.x + (w->rect.width - width) / 2, d->band.y + pad, width, ch });
}

static void dialog_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct dialog *d = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	cairo_set_source_rgba(cr, 0, 0, 0, 0.6);
	cairo_rectangle(cr, w->rect.x, w->rect.y, w->rect.width, w->rect.height);
	cairo_fill(cr);
	c8ui_set_source(cr, c.bg, 1);
	cairo_rectangle(cr, d->band.x, d->band.y, d->band.width, d->band.height);
	cairo_fill(cr);
}

static void dialog_finish(struct c8ui_widget *w, int choice) {
	struct dialog *d = w->data;
	if (d->done) {
		return;
	}
	d->done = true;
	c8ui_dialog_fn fn = d->fn;
	void *data = d->data;
	c8ui_widget_destroy(w);
	if (fn) {
		fn(choice, data);
	}
}

static bool dialog_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct dialog *d = w->data;
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
	case C8UI_EVENT_RELEASE:
	case C8UI_EVENT_MOTION:
	case C8UI_EVENT_SCROLL:
		return true; /* nothing gets past */
	case C8UI_EVENT_KEY:
		if (ev->sym == XKB_KEY_Escape) {
			dialog_finish(w, -1);
			return true;
		}
		if (ev->sym == XKB_KEY_Left || ev->sym == XKB_KEY_Right) {
			struct c8ui_widget *focus = w->root ? c8ui_root_focus(w->root) : NULL;
			int n = d->buttons->child_count, at = 0;
			for (int i = 0; i < n; i++) {
				if (d->buttons->children[i] == focus) {
					at = i;
				}
			}
			at = (at + (ev->sym == XKB_KEY_Right ? 1 : n - 1)) % n;
			if (w->root) {
				c8ui_root_show_focus(w->root, true);
			}
			c8ui_widget_grab_focus(d->buttons->children[at]);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void dialog_button(struct c8ui_widget *button, void *data) {
	struct c8ui_widget *w = data;
	struct dialog *d = w->data;
	for (int i = 0; i < d->buttons->child_count; i++) {
		if (d->buttons->children[i] == button) {
			dialog_finish(w, i);
			return;
		}
	}
}

static const struct c8ui_widget_impl dialog_impl = {
	.name = "dialog",
	.layout = dialog_layout,
	.draw = dialog_draw,
	.event = dialog_event,
	.destroy = free_data_fn,
};

struct c8ui_widget *c8ui_dialog_show(struct c8ui_root *root, const char *title,
		const char *message, const char *const *buttons, int count,
		c8ui_dialog_fn fn, void *data) {
	struct dialog *d = calloc(1, sizeof(*d));
	d->fn = fn;
	d->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&dialog_impl, d);
	w->scheme = C8UI_SCHEME_LIGHT;

	d->content = c8ui_box_new(C8UI_VERTICAL, 16);
	d->content->fill = true;
	if (title && title[0]) {
		c8ui_widget_add(d->content, c8ui_label_new(title, C8UI_TEXT_SUBHEADER));
	}
	d->message = c8ui_label_new(message, C8UI_TEXT_BODY);
	c8ui_widget_add(d->content, d->message);
	d->buttons = c8ui_box_new(C8UI_HORIZONTAL, 10);
	d->buttons->align = C8UI_ALIGN_END;
	for (int i = 0; i < count; i++) {
		struct c8ui_widget *b = c8ui_button_new(buttons[i], dialog_button, w);
		c8ui_button_set_primary(b, i == 0);
		c8ui_widget_add(d->buttons, b);
	}
	c8ui_widget_add(d->content, c8ui_spacer_new(1, 4));
	c8ui_widget_add(d->content, d->buttons);
	c8ui_widget_add(w, d->content);

	c8ui_root_push_overlay(root, w);
	if (count > 0) {
		c8ui_widget_grab_focus(d->buttons->children[0]);
	}
	return w;
}

void c8ui_dialog_message(struct c8ui_root *root, const char *title,
		const char *message) {
	if (root == NULL) {
		const char *name = g_get_prgname();
		fprintf(stderr, "%s: %s: %s\n", name ? name : "c8ui", title, message);
		return;
	}
	static const char *const buttons[] = { "Close" };
	c8ui_dialog_show(root, title, message, buttons, 1, NULL, NULL);
}

void c8ui_dialog_set_message(struct c8ui_widget *w, const char *message) {
	struct dialog *d = w->data;
	c8ui_label_set_text(d->message, message);
}

void c8ui_dialog_close(struct c8ui_widget *w) {
	dialog_finish(w, -1);
}

void c8ui_dialog_choose(struct c8ui_widget *w, int choice) {
	dialog_finish(w, choice);
}

void c8ui_dialog_add(struct c8ui_widget *w, struct c8ui_widget *child) {
	struct dialog *d = w->data;
	/* Under the message: before the spacer and the buttons */
	c8ui_widget_insert(d->content, d->content->child_count - 2, child);
}

/* Context menu */

#define MENU_PAD 6
#define MENU_ITEM_H 36
#define MENU_SEP_H 9
#define MENU_MIN_W 160
#define MENU_MARK_W 28 // the tick or dot column, when any item has one
#define MENU_ARROW_W 24 // the submenu arrow
#define MENU_LEVELS 8
#define MENU_OPEN_MS 300 // resting on an item with a submenu opens it

struct menu_list;

struct menu_entry {
	char *label, *shortcut;
	int id;
	enum c8ui_menu_kind kind;
	bool checked, disabled;
	struct menu_list *sub;
};

struct menu_list {
	struct menu_entry *items;
	int count;
	bool marks, arrows; // any item has a tick or dot, a submenu
};

/* An open menu: the top one, and the submenus open from it */
struct menu_level {
	struct menu_list *list;
	struct c8ui_rect box;
	int hover;
	int parent; // the item in the level before that opened it
};

struct menu {
	struct menu_list *top;
	struct menu_level levels[MENU_LEVELS];
	int depth; // levels open, 1 or more
	double x, y; // where it was asked for
	bool above;
	void *timer;
	struct c8ui_root *timer_root;
	c8ui_menu_fn fn;
	void *data;
	bool done;
};

static struct menu_list *menu_list_copy(const struct c8ui_menu_item *items,
		int count, int nesting) {
	struct menu_list *l = calloc(1, sizeof(*l));
	l->items = calloc(count > 0 ? count : 1, sizeof(*l->items));
	l->count = count;
	for (int i = 0; i < count; i++) {
		const struct c8ui_menu_item *it = &items[i];
		struct menu_entry *e = &l->items[i];
		e->label = strdup(it->label ? it->label : "");
		e->shortcut = c8ui_dup_or_null(it->shortcut);
		e->id = it->id;
		e->kind = it->kind;
		e->checked = it->checked;
		e->disabled = it->disabled;
		if (it->submenu && it->submenu_count > 0 &&
				nesting < MENU_LEVELS - 1 &&
				it->kind != C8UI_MENU_SEPARATOR) {
			e->sub = menu_list_copy(it->submenu, it->submenu_count,
				nesting + 1);
			l->arrows = true;
		}
		l->marks |= it->kind == C8UI_MENU_CHECK ||
			it->kind == C8UI_MENU_RADIO;
	}
	return l;
}

static void menu_list_free(struct menu_list *l) {
	if (l == NULL) {
		return;
	}
	for (int i = 0; i < l->count; i++) {
		free(l->items[i].label);
		free(l->items[i].shortcut);
		menu_list_free(l->items[i].sub);
	}
	free(l->items);
	free(l);
}

static double menu_item_h(struct menu_entry *e) {
	return e->kind == C8UI_MENU_SEPARATOR ? MENU_SEP_H : MENU_ITEM_H;
}

static double menu_item_y(struct menu_level *lv, int index) {
	double y = lv->box.y + MENU_PAD;
	for (int i = 0; i < index; i++) {
		y += menu_item_h(&lv->list->items[i]);
	}
	return y;
}

static bool menu_can_pick(struct menu_entry *e) {
	return e->kind != C8UI_MENU_SEPARATOR && !e->disabled;
}

static double menu_text_left(struct menu_list *l) {
	return 20 + (l->marks ? MENU_MARK_W - 8 : 0);
}

static void menu_size(struct c8ui_widget *w, struct menu_list *l,
		double *width, double *height) {
	const char *family = c8ui_widget_font(w);
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY);
	double label_w = 0, key_w = 0;
	*height = 2 * MENU_PAD;
	for (int i = 0; i < l->count; i++) {
		struct menu_entry *e = &l->items[i];
		*height += menu_item_h(e);
		double tw, th;
		c8ui_text_size(family, font, e->label, 0, 0, &tw, &th);
		label_w = tw > label_w ? tw : label_w;
		if (e->shortcut) {
			c8ui_text_size(family, font, e->shortcut, 0, 0, &tw, &th);
			key_w = tw > key_w ? tw : key_w;
		}
	}
	double width_needed = menu_text_left(l) + label_w + 20 +
		(key_w > 0 ? key_w + 32 : 0) + (l->arrows ? MENU_ARROW_W : 0);
	*width = ceil(width_needed > MENU_MIN_W ? width_needed : MENU_MIN_W);
}

/* Places level i: the top one where asked, a submenu beside its item */
static void menu_place(struct c8ui_widget *w, int i) {
	struct menu *m = w->data;
	struct menu_level *lv = &m->levels[i];
	double width, height;
	menu_size(w, lv->list, &width, &height);
	double x, y;
	double right = w->rect.x + w->rect.width - 8;
	if (i == 0) {
		x = m->x;
		y = m->above ? m->y - height : m->y;
	} else {
		struct menu_level *up = &m->levels[i - 1];
		x = up->box.x + up->box.width - 4;
		y = menu_item_y(up, lv->parent) - MENU_PAD;
		/* No room on the right: on the left of it instead */
		if (x + width > right) {
			x = up->box.x - width + 4;
		}
	}
	double max_x = right - width;
	double max_y = w->rect.y + w->rect.height - 8 - height;
	x = x > max_x ? max_x : x;
	y = y > max_y ? max_y : y;
	x = x < w->rect.x + 8 ? w->rect.x + 8 : x;
	y = y < w->rect.y + 8 ? w->rect.y + 8 : y;
	lv->box = (struct c8ui_rect){ round(x), round(y), width, height };
}

static void menu_layout(struct c8ui_widget *w) {
	struct menu *m = w->data;
	for (int i = 0; i < m->depth; i++) {
		menu_place(w, i);
	}
}

static void menu_draw_level(struct c8ui_widget *w, cairo_t *cr,
		struct menu_level *lv) {
	struct c8ui_rect r = lv->box;
	struct menu_list *l = lv->list;
	const char *family = c8ui_widget_font(w);
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY);
	/* White with a hairline, whatever the scheme, as Metro menus are */
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_fill(cr);
	cairo_set_source_rgba(cr, 0, 0, 0, 0.25);
	c8ui_stroke_rect(cr, r.x, r.y, r.width, r.height, 1);
	double y = r.y + MENU_PAD;
	for (int i = 0; i < l->count; i++) {
		struct menu_entry *e = &l->items[i];
		double h = menu_item_h(e);
		if (e->kind == C8UI_MENU_SEPARATOR) {
			cairo_set_source_rgba(cr, 0, 0, 0, 0.15);
			cairo_rectangle(cr, r.x + 12, y + h / 2, r.width - 24, 1);
			cairo_fill(cr);
			y += h;
			continue;
		}
		if (i == lv->hover && !e->disabled) {
			cairo_set_source_rgb(cr, 0.87, 0.87, 0.87);
			cairo_rectangle(cr, r.x + 1, y, r.width - 2, h);
			cairo_fill(cr);
		}
		double alpha = e->disabled ? 0.4 : 1;
		double cy = y + h / 2;
		cairo_set_source_rgba(cr, 0, 0, 0, alpha);
		if (e->checked && e->kind == C8UI_MENU_CHECK) {
			double cx = r.x + 20;
			cairo_set_line_width(cr, 1.6);
			cairo_move_to(cr, cx - 5, cy);
			cairo_line_to(cr, cx - 1.5, cy + 3.5);
			cairo_line_to(cr, cx + 5, cy - 4);
			cairo_stroke(cr);
		} else if (e->checked && e->kind == C8UI_MENU_RADIO) {
			cairo_new_path(cr);
			cairo_arc(cr, r.x + 20, cy, 3.5, 0, 2 * M_PI);
			cairo_fill(cr);
		}
		double left = menu_text_left(l);
		draw_box_text(w, cr, e->label, C8UI_TEXT_BODY, r.x + left, y,
			r.width - left - 20, h);
		double end = r.x + r.width - 20 - (l->arrows ? MENU_ARROW_W - 8 : 0);
		if (e->shortcut) {
			double tw, th;
			c8ui_text_size(family, font, e->shortcut, 0, 0, &tw, &th);
			cairo_set_source_rgba(cr, 0, 0, 0, 0.55 * alpha);
			c8ui_text_draw(cr, family, font, e->shortcut, end - tw,
				cy - th / 2, 0, 1);
		}
		if (e->sub) {
			double ax = r.x + r.width - 16;
			cairo_set_source_rgba(cr, 0, 0, 0, alpha);
			cairo_set_line_width(cr, 1.5);
			cairo_move_to(cr, ax - 2.5, cy - 5);
			cairo_line_to(cr, ax + 2.5, cy);
			cairo_line_to(cr, ax - 2.5, cy + 5);
			cairo_stroke(cr);
		}
		y += h;
	}
}

static void menu_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct menu *m = w->data;
	for (int i = 0; i < m->depth; i++) {
		menu_draw_level(w, cr, &m->levels[i]);
	}
}

static void menu_stop_timer(struct menu *m) {
	if (m->timer) {
		c8ui_root_timer_remove(m->timer_root, m->timer);
		m->timer = NULL;
	}
}

static void menu_finish(struct c8ui_widget *w, int choice) {
	struct menu *m = w->data;
	if (m->done) {
		return;
	}
	m->done = true;
	menu_stop_timer(m);
	c8ui_menu_fn fn = m->fn;
	void *data = m->data;
	c8ui_widget_destroy(w);
	if (fn) {
		fn(choice, data);
	}
}

/* Opens the submenu of item i in level at (closing any deeper) */
static void menu_open_sub(struct c8ui_widget *w, int at, int i,
		bool keyboard) {
	struct menu *m = w->data;
	struct menu_entry *e = &m->levels[at].list->items[i];
	if (e->sub == NULL || e->disabled || at + 1 >= MENU_LEVELS) {
		return;
	}
	m->depth = at + 2;
	struct menu_level *lv = &m->levels[at + 1];
	lv->list = e->sub;
	lv->parent = i;
	lv->hover = -1;
	if (keyboard) {
		for (int k = 0; k < e->sub->count; k++) {
			if (menu_can_pick(&e->sub->items[k])) {
				lv->hover = k;
				break;
			}
		}
	}
	menu_place(w, at + 1);
	c8ui_widget_queue_draw(w);
}

/* After resting: the levels past the one the pointer is in follow it */
static int menu_settle(void *data) {
	struct c8ui_widget *w = data;
	struct menu *m = w->data;
	m->timer = NULL;
	/* The deepest level whose hover isn't what opened the next */
	for (int at = 0; at < m->depth; at++) {
		int hover = m->levels[at].hover;
		bool opened = at + 1 < m->depth &&
			m->levels[at + 1].parent == hover;
		if (opened) {
			continue;
		}
		m->depth = at + 1;
		if (hover >= 0) {
			menu_open_sub(w, at, hover, false);
		}
		break;
	}
	c8ui_widget_queue_draw(w);
	return 0;
}

static void menu_settle_later(struct c8ui_widget *w) {
	struct menu *m = w->data;
	menu_stop_timer(m);
	m->timer_root = w->root;
	m->timer = c8ui_root_timer_add(w->root, MENU_OPEN_MS, menu_settle, w);
}

/* The level and item at a point, the deepest first; false if outside */
static bool menu_hit(struct menu *m, double x, double y, int *level,
		int *item) {
	for (int at = m->depth - 1; at >= 0; at--) {
		struct menu_level *lv = &m->levels[at];
		if (!c8ui_rect_contains(&lv->box, x, y)) {
			continue;
		}
		*level = at;
		*item = -1;
		double top = lv->box.y + MENU_PAD;
		for (int i = 0; i < lv->list->count; i++) {
			double h = menu_item_h(&lv->list->items[i]);
			if (y >= top && y < top + h) {
				*item = i;
				break;
			}
			top += h;
		}
		return true;
	}
	return false;
}

static void menu_pick(struct c8ui_widget *w, int at, int i) {
	struct menu *m = w->data;
	struct menu_entry *e = &m->levels[at].list->items[i];
	if (!menu_can_pick(e)) {
		return;
	}
	if (e->sub) {
		menu_stop_timer(m);
		menu_open_sub(w, at, i, false);
		return;
	}
	menu_finish(w, e->id);
}

/* The next item the keyboard can land on, going dir from i */
static int menu_step(struct menu_list *l, int i, int dir) {
	for (int n = 0; n < l->count; n++) {
		i = i < 0 && dir < 0 ? l->count - 1 :
			((i + dir) % l->count + l->count) % l->count;
		if (menu_can_pick(&l->items[i])) {
			return i;
		}
	}
	return -1;
}

static bool menu_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct menu *m = w->data;
	switch (ev->type) {
	case C8UI_EVENT_MOTION: {
		int at, i;
		if (!menu_hit(m, ev->x, ev->y, &at, &i)) {
			return true;
		}
		/* The levels above lead to this one */
		for (int k = 0; k < at; k++) {
			m->levels[k].hover = m->levels[k + 1].parent;
		}
		if (i != m->levels[at].hover) {
			m->levels[at].hover = i;
			c8ui_widget_queue_draw(w);
			bool opened = at + 1 < m->depth && m->levels[at + 1].parent == i;
			if (!opened && (at + 1 < m->depth ||
					(i >= 0 && m->levels[at].list->items[i].sub))) {
				menu_settle_later(w);
			} else if (opened) {
				menu_stop_timer(m);
			}
		}
		return true;
	}
	case C8UI_EVENT_LEAVE:
		m->levels[m->depth - 1].hover = -1;
		c8ui_widget_queue_draw(w);
		return true;
	case C8UI_EVENT_PRESS: {
		int at, i;
		if (!menu_hit(m, ev->x, ev->y, &at, &i)) {
			menu_finish(w, -1);
		}
		return true;
	}
	case C8UI_EVENT_RELEASE: {
		int at, i;
		if (ev->button == C8UI_BUTTON_LEFT &&
				menu_hit(m, ev->x, ev->y, &at, &i) && i >= 0) {
			menu_pick(w, at, i);
		}
		return true;
	}
	case C8UI_EVENT_KEY: {
		menu_stop_timer(m);
		int at = m->depth - 1;
		struct menu_level *lv = &m->levels[at];
		switch (ev->sym) {
		case XKB_KEY_Escape:
		case XKB_KEY_Left:
			if (at > 0) {
				m->depth--;
				c8ui_widget_queue_draw(w);
			} else if (ev->sym == XKB_KEY_Escape) {
				menu_finish(w, -1);
			}
			break;
		case XKB_KEY_Return:
		case XKB_KEY_KP_Enter:
		case XKB_KEY_space:
			if (lv->hover >= 0) {
				struct menu_entry *e = &lv->list->items[lv->hover];
				if (e->sub) {
					menu_open_sub(w, at, lv->hover, true);
				} else {
					menu_pick(w, at, lv->hover);
				}
			}
			break;
		case XKB_KEY_Right:
			if (lv->hover >= 0 && lv->list->items[lv->hover].sub) {
				menu_open_sub(w, at, lv->hover, true);
			}
			break;
		case XKB_KEY_Up:
		case XKB_KEY_Down:
			lv->hover = menu_step(lv->list, lv->hover,
				ev->sym == XKB_KEY_Up ? -1 : 1);
			c8ui_widget_queue_draw(w);
			break;
		}
		return true;
	}
	case C8UI_EVENT_SCROLL:
		return true;
	default:
		return false;
	}
}

static void menu_destroy(struct c8ui_widget *w) {
	struct menu *m = w->data;
	menu_stop_timer(m);
	menu_list_free(m->top);
	free(m);
}

static const struct c8ui_widget_impl menu_impl = {
	.name = "menu",
	.layout = menu_layout,
	.draw = menu_draw,
	.event = menu_event,
	.destroy = menu_destroy,
};

struct c8ui_widget *c8ui_menu_show_items(struct c8ui_root *root, double x,
		double y, bool above, const struct c8ui_menu_item *items, int count,
		c8ui_menu_fn fn, void *data) {
	struct menu *m = calloc(1, sizeof(*m));
	m->top = menu_list_copy(items, count, 0);
	m->levels[0].list = m->top;
	m->levels[0].hover = -1;
	m->levels[0].parent = -1;
	m->depth = 1;
	m->x = x;
	m->y = y;
	m->above = above;
	m->fn = fn;
	m->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&menu_impl, m);
	w->scheme = C8UI_SCHEME_LIGHT;
	c8ui_root_push_overlay(root, w);
	return w;
}

struct c8ui_widget *c8ui_menu_show(struct c8ui_root *root, double x, double y,
		bool above, const char *const *items, int count, c8ui_menu_fn fn,
		void *data) {
	struct c8ui_menu_item *list = calloc(count > 0 ? count : 1,
		sizeof(*list));
	for (int i = 0; i < count; i++) {
		list[i] = (struct c8ui_menu_item){ .label = items[i], .id = i };
	}
	struct c8ui_widget *w = c8ui_menu_show_items(root, x, y, above, list,
		count, fn, data);
	free(list);
	return w;
}

void c8ui_menu_close(struct c8ui_widget *w) {
	menu_finish(w, -1);
}

/* Progress bar */

#define PROGRESS_HEIGHT 6
#define DOTS 5
#define DOTS_MS 3000 // one run of the dots across

struct progress {
	double value;
	int64_t start;
};

static void progress_measure(struct c8ui_widget *w, double avail,
		double *width, double *height) {
	*width = avail < DEFAULT_WIDTH ? avail : DEFAULT_WIDTH;
	*height = PROGRESS_HEIGHT;
}

/* Where a dot is, 0 to 1 across, t (0 to 1) into the run: it rushes in,
 * drifts through the middle and rushes out, the ones behind it
 * following a little later */
static double dot_position(double t) {
	if (t < 0.25) {
		double u = t / 0.25;
		return 0.4 * (1 - (1 - u) * (1 - u));
	}
	if (t < 0.65) {
		return 0.4 + 0.2 * (t - 0.25) / 0.4;
	}
	double u = (t - 0.65) / 0.35;
	return 0.6 + 0.4 * u * u;
}

static void progress_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct progress *p = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	struct c8ui_rect r = w->rect;
	double y = r.y + (r.height - PROGRESS_HEIGHT) / 2;
	if (p->value >= 0) {
		c8ui_set_source(cr, c.fg, c.fill * 1.5);
		cairo_rectangle(cr, r.x, y, r.width, PROGRESS_HEIGHT);
		cairo_fill(cr);
		c8ui_set_source(cr, c.accent, 1);
		cairo_rectangle(cr, r.x, y, round(r.width * p->value), PROGRESS_HEIGHT);
		cairo_fill(cr);
		return;
	}
	/* Keeps the dots going; also starts them once it is in a window and
	 * again after it was hidden */
	c8ui_widget_animate(w);
	int64_t now = w->root ? w->root->now : 0;
	if (p->start == 0) {
		p->start = now;
	}
	double run = (double)((now - p->start) % DOTS_MS) / DOTS_MS;
	double dot = 4;
	c8ui_set_source(cr, c.accent, 1);
	for (int i = 0; i < DOTS; i++) {
		/* Each dot sets off a little after the one before */
		double t = run * 1.4 - i * 0.08;
		if (t < 0 || t > 1) {
			continue;
		}
		double x = r.x + dot_position(t) * (r.width - dot);
		cairo_rectangle(cr, round(x), round(y + 1), dot, dot);
		cairo_fill(cr);
	}
}

static bool progress_tick(struct c8ui_widget *w, int64_t now) {
	struct progress *p = w->data;
	c8ui_widget_queue_draw(w);
	return p->value < 0 && c8ui_widget_is_shown(w);
}

static const struct c8ui_widget_impl progress_impl = {
	.name = "progress",
	.measure = progress_measure,
	.draw = progress_draw,
	.tick = progress_tick,
	.destroy = free_data_fn,
};

struct c8ui_widget *c8ui_progress_new(double value) {
	struct progress *p = calloc(1, sizeof(*p));
	struct c8ui_widget *w = c8ui_widget_new(&progress_impl, p);
	c8ui_progress_set(w, value);
	return w;
}

void c8ui_progress_set(struct c8ui_widget *w, double value) {
	struct progress *p = w->data;
	p->value = value < 0 ? -1 : value > 1 ? 1 : value;
	if (p->value < 0) {
		p->start = 0;
		c8ui_widget_animate(w);
	}
	c8ui_widget_queue_draw(w);
}

double c8ui_progress_get(struct c8ui_widget *w) {
	return ((struct progress *)w->data)->value;
}
