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

/* Pickers: number box, rating, date, time and the month calendar */

#define CONTROL_HEIGHT 32
#define BORDER 2

/* Number box */

#define NUMBER_WIDTH 160
#define NUMBER_PAD 8
#define NUMBER_BUTTON 32 // − and + are squares at the end of the box
#define REPEAT_FIRST_MS 400 // held, a button repeats after this
#define REPEAT_MS 60

struct number {
	char *header;
	double min, max, step, value;
	int digits;
	struct c8ui_textedit *te;
	double scroll; // the text, sideways
	bool dirty; // typed into since the value was shown
	bool selecting;
	int pressed; // 0 none, -1 the − button, 1 the +
	void *repeat;
	struct c8ui_root *repeat_root;
	double wheel;
	c8ui_action_fn fn;
	void *data;
};

static struct c8ui_rect number_box(struct c8ui_widget *w) {
	struct number *n = w->data;
	double hh = c8ui_header_height(w, n->header, w->rect.width, NULL);
	return (struct c8ui_rect){ w->rect.x, w->rect.y + hh, w->rect.width,
		CONTROL_HEIGHT };
}

/* -1 over −, 1 over +, 0 over the text or outside */
static int number_button_at(struct c8ui_widget *w, double x, double y) {
	struct c8ui_rect box = number_box(w);
	if (!c8ui_rect_contains(&box, x, y)) {
		return 0;
	}
	double right = box.x + box.width;
	if (x >= right - NUMBER_BUTTON) {
		return 1;
	}
	if (x >= right - 2 * NUMBER_BUTTON) {
		return -1;
	}
	return 0;
}

static void number_show(struct c8ui_widget *w) {
	struct number *n = w->data;
	char buf[64];
	snprintf(buf, sizeof(buf), "%.*f", n->digits, n->value);
	c8ui_textedit_set(n->te, buf);
	n->dirty = false;
	c8ui_widget_queue_draw(w);
}

static double number_fit(struct number *n, double v) {
	if (n->step > 0) {
		v = n->min + round((v - n->min) / n->step) * n->step;
	}
	v = v > n->max ? n->max : v;
	v = v < n->min ? n->min : v;
	/* No -0 or 0.30000000000000004 */
	double scale = pow(10, n->digits);
	v = round(v * scale) / scale;
	return v == 0 ? 0 : v;
}

static void number_change(struct c8ui_widget *w, double v) {
	struct number *n = w->data;
	v = number_fit(n, v);
	bool changed = v != n->value;
	n->value = v;
	number_show(w);
	if (changed && n->fn) {
		n->fn(w, n->data);
	}
}

/* What was typed becomes the value, or goes back to it if it isn't one */
static void number_commit(struct c8ui_widget *w) {
	struct number *n = w->data;
	if (!n->dirty) {
		return;
	}
	char *text = g_strdup(c8ui_textedit_get(n->te));
	g_strdelimit(text, ",", '.');
	char *end;
	double v = g_ascii_strtod(text, &end);
	bool ok = end != text && *g_strchug(end) == '\0';
	g_free(text);
	if (ok) {
		number_change(w, v);
	} else {
		number_show(w);
	}
}

static void number_step(struct c8ui_widget *w, double steps) {
	struct number *n = w->data;
	number_commit(w);
	double step = n->step > 0 ? n->step : pow(10, -n->digits);
	number_change(w, n->value + steps * step);
}

static int number_repeat(void *data) {
	struct c8ui_widget *w = data;
	struct number *n = w->data;
	if (n->pressed == 0) {
		n->repeat = NULL;
		return 0;
	}
	number_step(w, n->pressed);
	return REPEAT_MS;
}

static void number_stop_repeat(struct number *n) {
	if (n->repeat) {
		c8ui_root_timer_remove(n->repeat_root, n->repeat);
		n->repeat = NULL;
	}
}

static void number_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct number *n = w->data;
	*width = avail < NUMBER_WIDTH ? avail : NUMBER_WIDTH;
	*height = c8ui_header_height(w, n->header, avail, NULL) + CONTROL_HEIGHT;
}

static double number_text_width(struct c8ui_rect box) {
	return box.width - 2 * NUMBER_BUTTON - 2 * NUMBER_PAD;
}

static void number_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct number *n = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	c8ui_header_draw(w, cr, n->header, w->disabled ? 0.4 : 1);
	struct c8ui_rect box = number_box(w);
	bool active = w->focused;
	/* A white box like an entry's, whatever the scheme */
	c8ui_set_source(cr, 0xffffff, w->disabled ? 0.5 : active || w->hovered ?
		1 : 0.85);
	cairo_rectangle(cr, box.x, box.y, box.width, box.height);
	cairo_fill(cr);
	c8ui_set_source(cr, active ? c.accent : c.fg, w->disabled ? c.border :
		active ? 1 : w->hovered ? c.border_hover : c.border);
	c8ui_stroke_rect(cr, box.x, box.y, box.width, box.height, BORDER);

	const char *family = c8ui_widget_font(w);
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY);
	double inner = number_text_width(box);
	double tw, th;
	c8ui_text_size(family, font, "0", 0, 0, &tw, &th);
	cairo_save(cr);
	cairo_rectangle(cr, box.x + NUMBER_PAD, box.y, inner, box.height);
	cairo_clip(cr);
	c8ui_textedit_draw(n->te, cr, family, font,
		box.x + NUMBER_PAD - n->scroll, box.y + (box.height - th) / 2,
		box.y + 6, box.height - 12, c.accent, active, active,
		w->disabled ? 0.5 : 1);
	cairo_restore(cr);

	/* − and + */
	struct c8ui_root *root = w->root;
	for (int b = -1; b <= 1; b += 2) {
		double bx = box.x + box.width - (b < 0 ? 2 : 1) * NUMBER_BUTTON;
		bool limit = b < 0 ? n->value <= n->min : n->value >= n->max;
		bool over = root && w->hovered &&
			number_button_at(w, root->px, root->py) == b;
		if (n->pressed == b && over) {
			c8ui_set_source(cr, c.accent, 1);
			cairo_rectangle(cr, bx, box.y + BORDER, NUMBER_BUTTON - BORDER,
				box.height - 2 * BORDER);
			cairo_fill(cr);
		} else if (over && !limit) {
			c8ui_set_source(cr, 0x000000, 0.1);
			cairo_rectangle(cr, bx, box.y + BORDER, NUMBER_BUTTON - BORDER,
				box.height - 2 * BORDER);
			cairo_fill(cr);
		}
		double cx = bx + NUMBER_BUTTON / 2.0 - 1, cy = box.y + box.height / 2;
		c8ui_set_source(cr, n->pressed == b && over ? 0xffffff : 0x000000,
			limit || w->disabled ? 0.3 : 0.8);
		cairo_rectangle(cr, cx - 5, cy - 0.75, 10, 1.5);
		if (b > 0) {
			cairo_rectangle(cr, cx - 0.75, cy - 5, 1.5, 10);
		}
		cairo_fill(cr);
	}
}

static double number_text_x(struct c8ui_widget *w, double x) {
	struct number *n = w->data;
	return x - number_box(w).x - NUMBER_PAD + n->scroll;
}

static void number_scroll_to_caret(struct c8ui_widget *w) {
	struct number *n = w->data;
	c8ui_textedit_scroll_to_caret(n->te, c8ui_widget_font(w),
		c8ui_text_font(C8UI_TEXT_BODY), number_text_width(number_box(w)),
		&n->scroll);
}

static bool number_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct number *n = w->data;
	const char *family = c8ui_widget_font(w);
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY);
	switch (ev->type) {
	case C8UI_EVENT_PRESS: {
		if (ev->button != C8UI_BUTTON_LEFT) {
			return false;
		}
		int b = number_button_at(w, ev->x, ev->y);
		if (b != 0) {
			n->pressed = b;
			number_step(w, b);
			number_stop_repeat(n);
			n->repeat_root = w->root;
			n->repeat = c8ui_root_timer_add(w->root, REPEAT_FIRST_MS,
				number_repeat, w);
			c8ui_widget_queue_draw(w);
			return true;
		}
		struct c8ui_rect box = number_box(w);
		if (!c8ui_rect_contains(&box, ev->x, ev->y)) {
			return false;
		}
		c8ui_textedit_press(n->te, family, font, number_text_x(w, ev->x),
			ev->mods & C8UI_MOD_SHIFT);
		n->selecting = true;
		c8ui_widget_queue_draw(w);
		return true;
	}
	case C8UI_EVENT_MOTION:
		if (n->selecting) {
			c8ui_textedit_drag(n->te, family, font, number_text_x(w, ev->x));
			number_scroll_to_caret(w);
		}
		w->cursor = number_button_at(w, ev->x, ev->y) != 0 ?
			C8UI_CURSOR_DEFAULT : C8UI_CURSOR_TEXT;
		c8ui_widget_queue_draw(w);
		return n->selecting;
	case C8UI_EVENT_RELEASE:
		n->selecting = false;
		n->pressed = 0;
		number_stop_repeat(n);
		c8ui_widget_queue_draw(w);
		return true;
	case C8UI_EVENT_FOCUS_IN:
		c8ui_textedit_select_all(n->te);
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_FOCUS_OUT:
		number_commit(w);
		c8ui_textedit_deselect(n->te);
		n->scroll = 0;
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_SCROLL: {
		/* Only while it has the keyboard, or it steals the page's
		 * scrolling */
		if (!w->focused || ev->dy == 0) {
			return false;
		}
		n->wheel += ev->precise ? ev->dy / 20 : (ev->dy > 0 ? 1 : -1);
		int steps = (int)n->wheel;
		if (steps != 0) {
			n->wheel -= steps;
			number_step(w, -steps);
		}
		return true;
	}
	case C8UI_EVENT_KEY:
		if (ev->mods & (C8UI_MOD_CTRL | C8UI_MOD_ALT)) {
			goto edit;
		}
		switch (ev->sym) {
		case XKB_KEY_Up:
			number_step(w, 1);
			c8ui_textedit_select_all(n->te);
			return true;
		case XKB_KEY_Down:
			number_step(w, -1);
			c8ui_textedit_select_all(n->te);
			return true;
		case XKB_KEY_Page_Up:
			number_step(w, 10);
			return true;
		case XKB_KEY_Page_Down:
			number_step(w, -10);
			return true;
		case XKB_KEY_Return:
		case XKB_KEY_KP_Enter:
			number_commit(w);
			c8ui_textedit_select_all(n->te);
			c8ui_widget_queue_draw(w);
			return true;
		case XKB_KEY_Escape:
			if (n->dirty) {
				number_show(w);
				return true;
			}
			return false;
		}
	edit:
		switch (c8ui_textedit_key(n->te, w->root, ev)) {
		case C8UI_EDIT_IGNORED:
			return false;
		case C8UI_EDIT_CHANGED:
			n->dirty = true;
			/* fall through */
		case C8UI_EDIT_MOVED:
			number_scroll_to_caret(w);
			c8ui_widget_queue_draw(w);
			return true;
		}
		return true;
	default:
		return false;
	}
}

static void number_pasted(struct c8ui_textedit *te, void *data) {
	struct c8ui_widget *w = data;
	((struct number *)w->data)->dirty = true;
	number_scroll_to_caret(w);
	c8ui_widget_queue_draw(w);
}

static void number_destroy(struct c8ui_widget *w) {
	struct number *n = w->data;
	number_stop_repeat(n);
	c8ui_textedit_free(n->te);
	free(n->header);
	free(n);
}

static const struct c8ui_widget_impl number_impl = {
	.name = "number",
	.measure = number_measure,
	.draw = number_draw,
	.event = number_event,
	.destroy = number_destroy,
};

struct c8ui_widget *c8ui_number_new(const char *header, double min,
		double max, double step, double value, int digits, c8ui_action_fn fn,
		void *data) {
	struct number *n = calloc(1, sizeof(*n));
	n->header = c8ui_dup_or_null(header);
	n->min = min < max ? min : max;
	n->max = min < max ? max : min;
	n->step = step;
	n->digits = digits < 0 ? 0 : digits > 10 ? 10 : digits;
	n->fn = fn;
	n->data = data;
	n->te = c8ui_textedit_new("");
	struct c8ui_widget *w = c8ui_widget_new(&number_impl, n);
	w->focusable = true;
	w->cursor = C8UI_CURSOR_TEXT;
	c8ui_textedit_on_change(n->te, number_pasted, w);
	n->value = number_fit(n, value);
	number_show(w);
	return w;
}

double c8ui_number_get(struct c8ui_widget *w) {
	return ((struct number *)w->data)->value;
}

void c8ui_number_set(struct c8ui_widget *w, double value) {
	struct number *n = w->data;
	n->value = number_fit(n, value);
	number_show(w);
}

void c8ui_number_set_range(struct c8ui_widget *w, double min, double max) {
	struct number *n = w->data;
	n->min = min < max ? min : max;
	n->max = min < max ? max : min;
	c8ui_number_set(w, n->value);
}

/* Rating */

#define STAR 24
#define STAR_GAP 4

struct rating {
	int max;
	double value;
	int hover; // stars the pointer would give, 0: none
	bool readonly;
	c8ui_action_fn fn;
	void *data;
};

static void star_path(cairo_t *cr, double cx, double cy, double r) {
	cairo_new_path(cr);
	for (int i = 0; i < 10; i++) {
		double a = -M_PI / 2 + i * M_PI / 5;
		double rr = i % 2 ? r * 0.45 : r;
		double x = cx + rr * cos(a), y = cy + rr * sin(a);
		if (i == 0) {
			cairo_move_to(cr, x, y);
		} else {
			cairo_line_to(cr, x, y);
		}
	}
	cairo_close_path(cr);
}

static void rating_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct rating *r = w->data;
	*width = r->max * STAR + (r->max - 1) * STAR_GAP;
	*height = STAR + 8;
}

/* How many stars a click at x gives */
static int rating_at(struct c8ui_widget *w, double x) {
	struct rating *r = w->data;
	int i = (int)((x - w->rect.x + STAR_GAP / 2.0) / (STAR + STAR_GAP)) + 1;
	return i < 1 ? 1 : i > r->max ? r->max : i;
}

static void rating_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct rating *r = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	double shown = r->hover > 0 ? r->hover : r->value;
	double cy = w->rect.y + w->rect.height / 2;
	for (int i = 0; i < r->max; i++) {
		double x = w->rect.x + i * (STAR + STAR_GAP);
		double cx = x + STAR / 2.0;
		star_path(cr, cx, cy + 1, STAR / 2.0);
		c8ui_set_source(cr, c.fg, w->disabled ? 0.1 : 0.2);
		cairo_fill(cr);
		double part = shown - i;
		if (part <= 0) {
			continue;
		}
		part = part > 1 ? 1 : part;
		cairo_save(cr);
		cairo_rectangle(cr, x, w->rect.y, STAR * part, w->rect.height);
		cairo_clip(cr);
		star_path(cr, cx, cy + 1, STAR / 2.0);
		/* The pointer's stars a little lighter than what is set */
		c8ui_set_source(cr, c.accent, w->disabled ? 0.4 :
			r->hover > 0 ? 0.75 : 1);
		cairo_fill(cr);
		cairo_restore(cr);
	}
}

static void rating_change(struct c8ui_widget *w, double value) {
	struct rating *r = w->data;
	value = value < 0 ? 0 : value > r->max ? r->max : value;
	if (value == r->value) {
		return;
	}
	r->value = value;
	c8ui_widget_queue_draw(w);
	if (r->fn) {
		r->fn(w, r->data);
	}
}

static bool rating_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct rating *r = w->data;
	if (r->readonly) {
		return false;
	}
	switch (ev->type) {
	case C8UI_EVENT_ENTER:
	case C8UI_EVENT_MOTION:
		r->hover = rating_at(w, ev->x);
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_LEAVE:
		r->hover = 0;
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_PRESS:
		return ev->button == C8UI_BUTTON_LEFT;
	case C8UI_EVENT_RELEASE:
		if (c8ui_rect_contains(&w->rect, ev->x, ev->y)) {
			int n = rating_at(w, ev->x);
			/* The star it already is takes it away */
			rating_change(w, n == r->value ? 0 : n);
			r->hover = r->value > 0 ? n : 0;
		}
		return true;
	case C8UI_EVENT_KEY: {
		if (ev->mods & (C8UI_MOD_CTRL | C8UI_MOD_ALT)) {
			return false;
		}
		double v = round(r->value);
		switch (ev->sym) {
		case XKB_KEY_Left:
		case XKB_KEY_Down:
			rating_change(w, v - 1);
			return true;
		case XKB_KEY_Right:
		case XKB_KEY_Up:
			rating_change(w, v + 1);
			return true;
		case XKB_KEY_Home:
			rating_change(w, 0);
			return true;
		case XKB_KEY_End:
			rating_change(w, r->max);
			return true;
		}
		if (ev->text && ev->text[0] >= '0' && ev->text[0] <= '9' &&
				ev->text[1] == '\0') {
			rating_change(w, ev->text[0] - '0');
			return true;
		}
		return false;
	}
	default:
		return false;
	}
}

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

static const struct c8ui_widget_impl rating_impl = {
	.name = "rating",
	.measure = rating_measure,
	.draw = rating_draw,
	.event = rating_event,
	.destroy = rating_destroy,
};

struct c8ui_widget *c8ui_rating_new(int max, double value, c8ui_action_fn fn,
		void *data) {
	struct rating *r = calloc(1, sizeof(*r));
	r->max = max > 0 ? max : 5;
	r->value = value < 0 ? 0 : value > r->max ? r->max : value;
	r->fn = fn;
	r->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&rating_impl, r);
	w->focusable = true;
	w->cursor = C8UI_CURSOR_POINTER;
	return w;
}

double c8ui_rating_get(struct c8ui_widget *w) {
	return ((struct rating *)w->data)->value;
}

void c8ui_rating_set(struct c8ui_widget *w, double value) {
	struct rating *r = w->data;
	r->value = value < 0 ? 0 : value > r->max ? r->max : value;
	c8ui_widget_queue_draw(w);
}

void c8ui_rating_set_readonly(struct c8ui_widget *w, bool readonly) {
	struct rating *r = w->data;
	r->readonly = readonly;
	r->hover = 0;
	w->focusable = !readonly;
	w->cursor = readonly ? C8UI_CURSOR_DEFAULT : C8UI_CURSOR_POINTER;
	c8ui_widget_queue_draw(w);
}

/* Date and time: drop-downs side by side under a header. The combos are
 * the children; parts[] says what each one is. */

#define PART_GAP 8

enum part {
	PART_MONTH,
	PART_DAY,
	PART_YEAR,
	PART_HOUR,
	PART_MINUTE,
	PART_PERIOD, // AM/PM
};

struct parts {
	char *header;
	enum part kind[3];
	int count;
	/* Date */
	int year, month, day;
	int first_year, last_year;
	/* Time */
	int hour, minute, minute_step;
	bool clock24;
	c8ui_action_fn fn;
	void *data;
};

static double part_width(enum part p) {
	switch (p) {
	case PART_MONTH:
		return 140;
	case PART_YEAR:
		return 88;
	default:
		return 72;
	}
}

static void parts_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct parts *p = w->data;
	*width = 0;
	double tallest = CONTROL_HEIGHT;
	for (int i = 0; i < w->child_count; i++) {
		if (w->children[i]->hidden) {
			continue; // AM/PM on a 24 hour clock
		}
		double cw, ch;
		c8ui_widget_measure(w->children[i], avail, &cw, &ch);
		*width += cw + (*width > 0 ? PART_GAP : 0);
		tallest = ch > tallest ? ch : tallest;
	}
	*height = c8ui_header_height(w, p->header, avail, NULL) + tallest;
}

static void parts_layout(struct c8ui_widget *w) {
	struct parts *p = w->data;
	double x = w->rect.x;
	double y = w->rect.y + c8ui_header_height(w, p->header, w->rect.width, NULL);
	for (int i = 0; i < w->child_count; i++) {
		struct c8ui_widget *c = w->children[i];
		if (c->hidden) {
			continue;
		}
		double cw, ch;
		c8ui_widget_measure(c, w->rect.width, &cw, &ch);
		c8ui_widget_layout(c, (struct c8ui_rect){ x, y, cw, ch });
		x += cw + PART_GAP;
	}
}

static void parts_draw(struct c8ui_widget *w, cairo_t *cr) {
	c8ui_header_draw(w, cr, ((struct parts *)w->data)->header, w->disabled ? 0.4 : 1);
}

static void parts_destroy(struct c8ui_widget *w) {
	struct parts *p = w->data;
	free(p->header);
	free(p);
}

static const struct c8ui_widget_impl parts_impl = {
	.name = "date-time",
	.measure = parts_measure,
	.layout = parts_layout,
	.draw = parts_draw,
	.destroy = parts_destroy,
};

static struct c8ui_widget *parts_combo(struct c8ui_widget *w, enum part kind) {
	struct parts *p = w->data;
	for (int i = 0; i < p->count; i++) {
		if (p->kind[i] == kind) {
			return w->children[i];
		}
	}
	return NULL;
}

/* Gives a combo its items (it copies them) and frees the array */
static void set_items(struct c8ui_widget *combo, GPtrArray *items,
		int selected) {
	c8ui_combo_set_items(combo, (const char *const *)items->pdata,
		items->len, selected);
	g_ptr_array_free(items, true);
}

static void date_fill(struct c8ui_widget *w) {
	struct parts *p = w->data;
	int days = g_date_get_days_in_month(p->month, p->year);
	p->day = p->day > days ? days : p->day;
	GPtrArray *items = g_ptr_array_new_with_free_func(g_free);
	for (int d = 1; d <= days; d++) {
		g_ptr_array_add(items, g_strdup_printf("%d", d));
	}
	set_items(parts_combo(w, PART_DAY), items, p->day - 1);

	items = g_ptr_array_new_with_free_func(g_free);
	int first = p->year < p->first_year ? p->year : p->first_year;
	int last = p->year > p->last_year ? p->year : p->last_year;
	for (int y = first; y <= last; y++) {
		g_ptr_array_add(items, g_strdup_printf("%d", y));
	}
	set_items(parts_combo(w, PART_YEAR), items, p->year - first);
	c8ui_combo_set(parts_combo(w, PART_MONTH), p->month - 1);
}

static void date_changed(struct c8ui_widget *combo, void *data) {
	struct c8ui_widget *w = data;
	struct parts *p = w->data;
	int i = c8ui_combo_get(combo);
	if (combo == parts_combo(w, PART_MONTH)) {
		p->month = i + 1;
	} else if (combo == parts_combo(w, PART_DAY)) {
		p->day = i + 1;
	} else {
		int first = p->year < p->first_year ? p->year : p->first_year;
		p->year = first + i;
	}
	date_fill(w); // the days in the month may have changed
	if (p->fn) {
		p->fn(w, p->data);
	}
}

/* The locale's order of day, month and year, from its date format */
static void date_order(enum part order[3]) {
	const char *fmt = nl_langinfo(D_FMT);
	int at[3] = { 100, 101, 102 }; // month, day, year if none found
	for (int i = 0; fmt && fmt[i]; i++) {
		if (fmt[i] != '%' || fmt[i + 1] == '\0') {
			continue;
		}
		char c = fmt[i + 1];
		if (c == 'm' || c == 'b' || c == 'B') {
			at[0] = i;
		} else if (c == 'd' || c == 'e') {
			at[1] = i;
		} else if (c == 'y' || c == 'Y') {
			at[2] = i;
		}
	}
	enum part kinds[3] = { PART_MONTH, PART_DAY, PART_YEAR };
	for (int i = 0; i < 3; i++) {
		order[i] = kinds[i];
	}
	/* Sort the three by where they are */
	for (int i = 0; i < 3; i++) {
		for (int j = i + 1; j < 3; j++) {
			if (at[j] < at[i]) {
				int t = at[i];
				at[i] = at[j];
				at[j] = t;
				enum part k = order[i];
				order[i] = order[j];
				order[j] = k;
			}
		}
	}
}

static struct c8ui_widget *parts_new(const char *header) {
	struct parts *p = calloc(1, sizeof(*p));
	p->header = c8ui_dup_or_null(header);
	struct c8ui_widget *w = c8ui_widget_new(&parts_impl, p);
	return w;
}

static void parts_add(struct c8ui_widget *w, enum part kind,
		c8ui_action_fn fn) {
	struct parts *p = w->data;
	struct c8ui_widget *combo = c8ui_combo_new(NULL, NULL, 0, -1, fn, w);
	combo->fixed_width = part_width(kind);
	p->kind[p->count++] = kind;
	c8ui_widget_add(w, combo);
}

struct c8ui_widget *c8ui_date_new(const char *header, int year, int month,
		int day, c8ui_action_fn fn, void *data) {
	struct c8ui_widget *w = parts_new(header);
	struct parts *p = w->data;
	p->fn = fn;
	p->data = data;
	enum part order[3];
	date_order(order);
	for (int i = 0; i < 3; i++) {
		parts_add(w, order[i], date_changed);
	}
	/* Month names in the locale's words */
	GPtrArray *months = g_ptr_array_new_with_free_func(g_free);
	for (int m = 1; m <= 12; m++) {
		GDateTime *dt = g_date_time_new_local(2001, m, 1, 0, 0, 0);
		g_ptr_array_add(months, g_date_time_format(dt, "%B"));
		g_date_time_unref(dt);
	}
	set_items(parts_combo(w, PART_MONTH), months, 0);
	GDateTime *now = g_date_time_new_now_local();
	int this_year = g_date_time_get_year(now);
	g_date_time_unref(now);
	p->first_year = this_year - 100;
	p->last_year = this_year + 100;
	c8ui_date_set(w, year, month, day);
	return w;
}

void c8ui_date_get(struct c8ui_widget *w, int *year, int *month, int *day) {
	struct parts *p = w->data;
	*year = p->year;
	*month = p->month;
	*day = p->day;
}

void c8ui_date_set(struct c8ui_widget *w, int year, int month, int day) {
	struct parts *p = w->data;
	p->year = year < 1 ? 1 : year > 9999 ? 9999 : year;
	p->month = month < 1 ? 1 : month > 12 ? 12 : month;
	p->day = day < 1 ? 1 : day;
	date_fill(w);
}

void c8ui_date_set_years(struct c8ui_widget *w, int first, int last) {
	struct parts *p = w->data;
	p->first_year = first < last ? first : last;
	p->last_year = first < last ? last : first;
	date_fill(w);
}

/* Whether the locale's clock is 12 hour */
static bool locale_12h(void) {
	const char *fmt = nl_langinfo(T_FMT);
	return fmt && (strstr(fmt, "%I") || strstr(fmt, "%l") ||
		strstr(fmt, "%r") || strstr(fmt, "%p"));
}

static void time_fill(struct c8ui_widget *w) {
	struct parts *p = w->data;
	GPtrArray *items = g_ptr_array_new_with_free_func(g_free);
	for (int h = 0; h < (p->clock24 ? 24 : 12); h++) {
		int shown = p->clock24 ? h : h == 0 ? 12 : h;
		g_ptr_array_add(items, g_strdup_printf(p->clock24 ? "%02d" : "%d",
			shown));
	}
	set_items(parts_combo(w, PART_HOUR), items,
		p->clock24 ? p->hour : p->hour % 12);

	items = g_ptr_array_new_with_free_func(g_free);
	int step = p->minute_step;
	for (int m = 0; m < 60; m += step) {
		g_ptr_array_add(items, g_strdup_printf("%02d", m));
	}
	set_items(parts_combo(w, PART_MINUTE), items, p->minute / step);

	struct c8ui_widget *period = parts_combo(w, PART_PERIOD);
	c8ui_widget_set_hidden(period, p->clock24);
	items = g_ptr_array_new_with_free_func(g_free);
	for (int h = 0; h < 24; h += 12) {
		GDateTime *dt = g_date_time_new_local(2001, 1, 1, h, 0, 0);
		char *s = g_date_time_format(dt, "%p");
		g_date_time_unref(dt);
		if (s == NULL || s[0] == '\0') {
			g_free(s);
			s = g_strdup(h == 0 ? "AM" : "PM");
		}
		g_ptr_array_add(items, s);
	}
	set_items(period, items, p->hour >= 12);
}

static void time_changed(struct c8ui_widget *combo, void *data) {
	struct c8ui_widget *w = data;
	struct parts *p = w->data;
	int i = c8ui_combo_get(combo);
	if (combo == parts_combo(w, PART_HOUR)) {
		p->hour = p->clock24 ? i : i + (p->hour >= 12 ? 12 : 0);
	} else if (combo == parts_combo(w, PART_MINUTE)) {
		p->minute = i * p->minute_step;
	} else {
		p->hour = p->hour % 12 + (i == 1 ? 12 : 0);
	}
	if (p->fn) {
		p->fn(w, p->data);
	}
}

struct c8ui_widget *c8ui_time_new(const char *header, int hour, int minute,
		c8ui_action_fn fn, void *data) {
	struct c8ui_widget *w = parts_new(header);
	struct parts *p = w->data;
	p->fn = fn;
	p->data = data;
	p->minute_step = 1;
	p->clock24 = !locale_12h();
	parts_add(w, PART_HOUR, time_changed);
	parts_add(w, PART_MINUTE, time_changed);
	parts_add(w, PART_PERIOD, time_changed);
	c8ui_time_set(w, hour, minute);
	return w;
}

void c8ui_time_get(struct c8ui_widget *w, int *hour, int *minute) {
	struct parts *p = w->data;
	*hour = p->hour;
	*minute = p->minute;
}

void c8ui_time_set(struct c8ui_widget *w, int hour, int minute) {
	struct parts *p = w->data;
	p->hour = hour < 0 ? 0 : hour > 23 ? 23 : hour;
	minute = minute < 0 ? 0 : minute > 59 ? 59 : minute;
	p->minute = minute / p->minute_step * p->minute_step;
	time_fill(w);
}

void c8ui_time_set_24h(struct c8ui_widget *w, bool clock24) {
	struct parts *p = w->data;
	p->clock24 = clock24;
	time_fill(w);
}

void c8ui_time_set_minute_step(struct c8ui_widget *w, int step) {
	struct parts *p = w->data;
	p->minute_step = step < 1 ? 1 : step > 30 ? 30 : step;
	c8ui_time_set(w, p->hour, p->minute);
}

/* Calendar */

#define CAL_TITLE 48
#define CAL_WEEKDAYS 28
#define CAL_ARROW 32
#define CAL_CELL_MIN 36
#define CAL_CELL_MAX 64
#define CAL_CELL 44 // natural size
#define CAL_WHEEL 60 // touchpad pixels per month

struct calendar {
	GDate selected;
	int view_year, view_month;
	int week_start; // 0 Sunday, 1 Monday...
	int hover, pressed; // cells 0 to 41, or -1 (-2, -3: the arrows)
	double wheel;
	c8ui_calendar_mark_fn mark_fn;
	void *mark_data;
	c8ui_action_fn fn, month_fn;
	void *data, *month_data;
};

#define CAL_PREV -2
#define CAL_NEXT -3

static int locale_week_start(void) {
#ifdef __GLIBC__
	/* As GTK does it: the first weekday counts from the week's origin */
	union {
		unsigned int word;
		char *string;
	} info;
	info.string = nl_langinfo(_NL_TIME_FIRST_WEEKDAY);
	int first = info.string[0];
	info.string = nl_langinfo(_NL_TIME_WEEK_1STDAY);
	int origin = info.word == 19971201 ? 1 : 0;
	int start = (origin + first - 1) % 7;
	return start < 0 ? 0 : start;
#else
	return 0;
#endif
}

static double cal_cell(struct c8ui_widget *w) {
	double cell = floor(w->rect.width / 7);
	return cell < CAL_CELL_MIN ? CAL_CELL_MIN : cell > CAL_CELL_MAX ?
		CAL_CELL_MAX : cell;
}

/* The date in cell i (0 to 41) */
static GDate cal_date_at(struct calendar *cal, int i) {
	GDate d;
	g_date_clear(&d, 1);
	g_date_set_dmy(&d, 1, cal->view_month, cal->view_year);
	/* GDate weekdays: Monday 1 to Sunday 7 */
	int wd = g_date_get_weekday(&d) % 7; // Sunday 0
	int lead = (wd - cal->week_start + 7) % 7;
	if (i >= lead) {
		g_date_add_days(&d, i - lead);
	} else {
		g_date_subtract_days(&d, lead - i);
	}
	return d;
}

static struct c8ui_rect cal_arrow(struct c8ui_widget *w, int which) {
	double x = w->rect.x + 7 * cal_cell(w) - CAL_ARROW;
	if (which == CAL_PREV) {
		x -= CAL_ARROW + 4;
	}
	return (struct c8ui_rect){ x, w->rect.y + (CAL_TITLE - CAL_ARROW) / 2,
		CAL_ARROW, CAL_ARROW };
}

static int cal_hit(struct c8ui_widget *w, double x, double y) {
	struct c8ui_rect prev = cal_arrow(w, CAL_PREV);
	struct c8ui_rect next = cal_arrow(w, CAL_NEXT);
	if (c8ui_rect_contains(&prev, x, y)) {
		return CAL_PREV;
	}
	if (c8ui_rect_contains(&next, x, y)) {
		return CAL_NEXT;
	}
	double cell = cal_cell(w);
	double top = w->rect.y + CAL_TITLE + CAL_WEEKDAYS;
	int col = (int)floor((x - w->rect.x) / cell);
	int row = (int)floor((y - top) / cell);
	if (col < 0 || col > 6 || row < 0 || row > 5) {
		return -1;
	}
	return row * 7 + col;
}

static void cal_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	double cell = floor(avail / 7);
	cell = cell > CAL_CELL ? CAL_CELL : cell < CAL_CELL_MIN ? CAL_CELL_MIN :
		cell;
	*width = 7 * cell;
	*height = CAL_TITLE + CAL_WEEKDAYS + 6 * cell;
}

static void cal_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct calendar *cal = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	const char *family = c8ui_widget_font(w);
	double cell = cal_cell(w);
	double alpha = w->disabled ? 0.4 : 1;

	/* Title: the month and year, and the arrows */
	GDateTime *dt = g_date_time_new_local(cal->view_year, cal->view_month,
		1, 0, 0, 0);
	char *title = g_date_time_format(dt, "%B %Y");
	g_date_time_unref(dt);
	struct c8ui_font tf = c8ui_text_font(C8UI_TEXT_TITLE);
	double tw, th;
	c8ui_text_size(family, tf, title, 0, 0, &tw, &th);
	c8ui_set_source(cr, c.fg, alpha);
	c8ui_text_draw(cr, family, tf, title, w->rect.x + 4,
		w->rect.y + (CAL_TITLE - th) / 2, 7 * cell - 2 * CAL_ARROW - 12, 1);
	g_free(title);
	for (int which = CAL_PREV; which >= CAL_NEXT; which--) {
		struct c8ui_rect r = cal_arrow(w, which);
		bool over = cal->hover == which;
		if (over) {
			c8ui_set_source(cr, c.fg, cal->pressed == which ? c.fill * 2.5 :
				c.fill * 1.5);
			cairo_rectangle(cr, r.x, r.y, r.width, r.height);
			cairo_fill(cr);
		}
		double cx = r.x + r.width / 2, cy = r.y + r.height / 2;
		double d = which == CAL_PREV ? 1 : -1;
		c8ui_set_source(cr, c.fg, alpha);
		cairo_set_line_width(cr, 1.5);
		cairo_move_to(cr, cx + 2.5 * d, cy - 6);
		cairo_line_to(cr, cx - 3.5 * d, cy);
		cairo_line_to(cr, cx + 2.5 * d, cy + 6);
		cairo_stroke(cr);
	}

	/* Weekday names */
	struct c8ui_font cf = c8ui_text_font(C8UI_TEXT_CAPTION);
	for (int i = 0; i < 7; i++) {
		/* 7 January 2001 was a Sunday */
		GDateTime *day = g_date_time_new_local(2001, 1,
			7 + (cal->week_start + i) % 7, 0, 0, 0);
		char *name = g_date_time_format(day, "%a");
		g_date_time_unref(day);
		c8ui_text_size(family, cf, name, 0, 0, &tw, &th);
		c8ui_set_source(cr, c.fg, c.fg_secondary * alpha);
		c8ui_text_draw(cr, family, cf, name,
			w->rect.x + i * cell + (cell - tw) / 2,
			w->rect.y + CAL_TITLE + (CAL_WEEKDAYS - th) / 2, cell, 1);
		g_free(name);
	}

	/* Days */
	GDate today;
	g_date_clear(&today, 1);
	g_date_set_time_t(&today, time(NULL));
	double top = w->rect.y + CAL_TITLE + CAL_WEEKDAYS;
	struct c8ui_font df = c8ui_text_font(C8UI_TEXT_BODY);
	for (int i = 0; i < 42; i++) {
		GDate d = cal_date_at(cal, i);
		double x = w->rect.x + (i % 7) * cell, y = top + (i / 7) * cell;
		bool in_month = g_date_get_month(&d) == (GDateMonth)cal->view_month;
		bool is_today = g_date_compare(&d, &today) == 0;
		bool is_selected = g_date_compare(&d, &cal->selected) == 0;
		uint32_t text = c.fg;
		double text_alpha = in_month ? alpha : 0.35 * alpha;
		if (is_today) {
			c8ui_set_source(cr, c.accent, alpha);
			cairo_rectangle(cr, x + 1, y + 1, cell - 2, cell - 2);
			cairo_fill(cr);
			text = 0xffffff;
			text_alpha = alpha;
		} else if (cal->hover == i) {
			c8ui_set_source(cr, c.fg, cal->pressed == i ? c.fill * 2.5 :
				c.fill * 1.5);
			cairo_rectangle(cr, x + 1, y + 1, cell - 2, cell - 2);
			cairo_fill(cr);
		}
		if (is_selected) {
			c8ui_set_source(cr, is_today ? 0xffffff : c.fg, alpha);
			c8ui_stroke_rect(cr, x + (is_today ? 3 : 1), y + (is_today ? 3 : 1),
				cell - (is_today ? 6 : 2), cell - (is_today ? 6 : 2), 2);
			if (w->focused && w->root && w->root->focus_visible) {
				c8ui_dotted_rect(cr, x - 1.5, y - 1.5, cell + 3, cell + 3);
			}
		}
		char num[4];
		snprintf(num, sizeof(num), "%d", g_date_get_day(&d));
		c8ui_text_size(family, df, num, 0, 0, &tw, &th);
		c8ui_set_source(cr, text, text_alpha);
		c8ui_text_draw(cr, family, df, num, x + (cell - tw) / 2,
			y + (cell - th) / 2, cell, 1);
		if (cal->mark_fn && cal->mark_fn(g_date_get_year(&d),
				g_date_get_month(&d), g_date_get_day(&d), cal->mark_data)) {
			cairo_new_path(cr);
			cairo_arc(cr, x + cell / 2, y + cell / 2 + th / 2 + 4, 2, 0,
				2 * M_PI);
			c8ui_set_source(cr, is_today ? 0xffffff : c.accent, text_alpha);
			cairo_fill(cr);
		}
	}
}

static void cal_show_month(struct c8ui_widget *w, int year, int month) {
	struct calendar *cal = w->data;
	while (month < 1) {
		month += 12;
		year--;
	}
	while (month > 12) {
		month -= 12;
		year++;
	}
	if (year < 1 || year > 9999 ||
			(year == cal->view_year && month == cal->view_month)) {
		return;
	}
	cal->view_year = year;
	cal->view_month = month;
	c8ui_widget_queue_draw(w);
	if (cal->month_fn) {
		cal->month_fn(w, cal->month_data);
	}
}

static void cal_pick(struct c8ui_widget *w, GDate d) {
	struct calendar *cal = w->data;
	if (!g_date_valid(&d)) {
		return;
	}
	cal_show_month(w, g_date_get_year(&d), g_date_get_month(&d));
	if (g_date_compare(&d, &cal->selected) == 0) {
		return;
	}
	cal->selected = d;
	c8ui_widget_queue_draw(w);
	if (cal->fn) {
		cal->fn(w, cal->data);
	}
}

static bool cal_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct calendar *cal = w->data;
	switch (ev->type) {
	case C8UI_EVENT_ENTER:
	case C8UI_EVENT_MOTION: {
		int h = cal_hit(w, ev->x, ev->y);
		if (h != cal->hover) {
			cal->hover = h;
			c8ui_widget_queue_draw(w);
		}
		w->cursor = h == -1 ? C8UI_CURSOR_DEFAULT : C8UI_CURSOR_POINTER;
		return false;
	}
	case C8UI_EVENT_LEAVE:
		cal->hover = -1;
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_PRESS:
		if (ev->button != C8UI_BUTTON_LEFT) {
			return false;
		}
		cal->pressed = cal_hit(w, ev->x, ev->y);
		c8ui_widget_queue_draw(w);
		return cal->pressed != -1;
	case C8UI_EVENT_RELEASE: {
		int h = cal_hit(w, ev->x, ev->y);
		int pressed = cal->pressed;
		cal->pressed = -1;
		c8ui_widget_queue_draw(w);
		if (h != pressed) {
			return true;
		}
		if (h == CAL_PREV || h == CAL_NEXT) {
			cal_show_month(w, cal->view_year,
				cal->view_month + (h == CAL_PREV ? -1 : 1));
		} else if (h >= 0) {
			cal_pick(w, cal_date_at(cal, h));
		}
		return true;
	}
	case C8UI_EVENT_SCROLL: {
		if (ev->dy == 0 || (ev->mods & C8UI_MOD_CTRL)) {
			return false;
		}
		cal->wheel += ev->precise ? ev->dy / CAL_WHEEL :
			(ev->dy > 0 ? 1 : -1);
		int months = (int)cal->wheel;
		if (months != 0) {
			cal->wheel -= months;
			cal_show_month(w, cal->view_year, cal->view_month + months);
		}
		return true;
	}
	case C8UI_EVENT_SCROLL_STOP:
		cal->wheel = 0;
		return false;
	case C8UI_EVENT_KEY: {
		if (ev->mods & (C8UI_MOD_CTRL | C8UI_MOD_ALT)) {
			return false;
		}
		GDate d = cal->selected;
		switch (ev->sym) {
		case XKB_KEY_Left:
			g_date_subtract_days(&d, 1);
			break;
		case XKB_KEY_Right:
			g_date_add_days(&d, 1);
			break;
		case XKB_KEY_Up:
			g_date_subtract_days(&d, 7);
			break;
		case XKB_KEY_Down:
			g_date_add_days(&d, 7);
			break;
		case XKB_KEY_Page_Up:
			g_date_subtract_months(&d, 1);
			break;
		case XKB_KEY_Page_Down:
			g_date_add_months(&d, 1);
			break;
		case XKB_KEY_Home:
			g_date_set_day(&d, 1);
			break;
		case XKB_KEY_End:
			g_date_set_day(&d, g_date_get_days_in_month(
				g_date_get_month(&d), g_date_get_year(&d)));
			break;
		default:
			return c8ui_activates(ev);
		}
		cal_pick(w, d);
		return true;
	}
	default:
		return false;
	}
}

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

static const struct c8ui_widget_impl calendar_impl = {
	.name = "calendar",
	.measure = cal_measure,
	.draw = cal_draw,
	.event = cal_event,
	.destroy = cal_destroy,
};

struct c8ui_widget *c8ui_calendar_new(int year, int month, int day,
		c8ui_action_fn fn, void *data) {
	struct calendar *cal = calloc(1, sizeof(*cal));
	g_date_clear(&cal->selected, 1);
	cal->week_start = locale_week_start();
	cal->hover = cal->pressed = -1;
	struct c8ui_widget *w = c8ui_widget_new(&calendar_impl, cal);
	w->focusable = true;
	c8ui_calendar_set(w, year, month, day);
	cal->fn = fn;
	cal->data = data;
	return w;
}

void c8ui_calendar_get(struct c8ui_widget *w, int *year, int *month,
		int *day) {
	struct calendar *cal = w->data;
	*year = g_date_get_year(&cal->selected);
	*month = g_date_get_month(&cal->selected);
	*day = g_date_get_day(&cal->selected);
}

void c8ui_calendar_set(struct c8ui_widget *w, int year, int month, int day) {
	struct calendar *cal = w->data;
	year = year < 1 ? 1 : year > 9999 ? 9999 : year;
	month = month < 1 ? 1 : month > 12 ? 12 : month;
	int days = g_date_get_days_in_month(month, year);
	day = day < 1 ? 1 : day > days ? days : day;
	g_date_set_dmy(&cal->selected, day, month, year);
	cal->view_year = year;
	cal->view_month = month;
	c8ui_widget_queue_draw(w);
}

void c8ui_calendar_set_marks(struct c8ui_widget *w, c8ui_calendar_mark_fn fn,
		void *data) {
	struct calendar *cal = w->data;
	cal->mark_fn = fn;
	cal->mark_data = data;
	c8ui_widget_queue_draw(w);
}

void c8ui_calendar_on_month(struct c8ui_widget *w, c8ui_action_fn fn,
		void *data) {
	struct calendar *cal = w->data;
	cal->month_fn = fn;
	cal->month_data = data;
}

void c8ui_calendar_get_month(struct c8ui_widget *w, int *year, int *month) {
	struct calendar *cal = w->data;
	*year = cal->view_year;
	*month = cal->view_month;
}
