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

/* Items the app draws, in rows or a grid. The list keeps only how many
 * there are and which are selected; drawing asks the app for the ones in
 * sight. */

#define GRID_GAP 10
#define DRAG_START 8 // how far a press moves before it is a drag
#define CHECK_SIZE 26 // the corner a selected grid cell shows its tick in

struct list {
	enum c8ui_list_mode mode;
	double item_w, item_h;
	int count;
	bool *selected;
	int cursor, anchor; // the keyboard's item, and where Shift ranges from
	int hover, pressed;
	bool multiple, click_opens;

	int64_t last_click;
	int last_click_index;

	c8ui_list_draw_fn draw;
	void *draw_data;
	c8ui_list_fn open_fn;
	void *open_data;
	c8ui_action_fn select_fn;
	void *select_data;
	c8ui_list_context_fn context_fn;
	void *context_data;
	c8ui_list_fn drag_fn;
	void *drag_data;
	double press_x, press_y;
	/* Pressed in a selection of several: picked alone on release, unless
	 * the press became a drag of them all */
	int deferred;
	/* c8ui_list_set_checks: a click on an item's box toggles it */
	bool checks;
	/* A press off the items dragged: a band that selects what it
	 * crosses. Its corners are from the list's own, as it may scroll. */
	bool band_armed, banding;
	double band_x0, band_y0, band_x1, band_y1;
	bool *band_base; // what was selected before it (Ctrl adds to that)

	/* C8UI_LIST_SPANS: where each item sits, in cells, first fit */
	c8ui_list_span_fn span_fn;
	void *span_data;
	struct cell {
		int col, row, cols, rows;
	} *cells;
	int pack_cols, pack_rows; // what the cells were packed for
	bool pack_dirty;
	struct c8ui_widget *self;

	/* c8ui_list_set_keep: an item's pixels, one slot each (count of
	 * them, NULL until one is drawn) */
	bool keep, not_final;
	struct c8ui_kept **kept;

	/* The pressed item sinks in (struct c8ui_tilt); tilt_item is the one
	 * it is on, still springing back after the release */
	struct c8ui_tilt tilt;
	int tilt_item;
};

static void drop_kept(struct list *l) {
	for (int i = 0; l->kept && i < l->count; i++) {
		c8ui_kept_drop(&l->kept[i]);
	}
	free(l->kept);
	l->kept = NULL;
}

struct keep_draw {
	struct c8ui_widget *w;
	struct c8ui_list_item item;
};

/* The app draws an item, kept to the item's rect */
static void draw_item(struct c8ui_widget *w, cairo_t *cr,
		const struct c8ui_list_item *item) {
	struct list *l = w->data;
	cairo_save(cr);
	cairo_rectangle(cr, item->rect.x, item->rect.y, item->rect.width,
		item->rect.height);
	cairo_clip(cr);
	l->draw(w, cr, item, l->draw_data);
	cairo_restore(cr);
}

static bool keep_draw(cairo_t *cr, struct c8ui_rect r, void *data) {
	struct keep_draw *k = data;
	struct list *l = k->w->data;
	k->item.rect = r;
	l->not_final = false;
	draw_item(k->w, cr, &k->item);
	return !l->not_final;
}

/* Geometry */

static int columns_for(struct list *l, double width) {
	if (l->mode == C8UI_LIST_ROWS) {
		return 1;
	}
	int n = (int)floor((width + GRID_GAP) / (l->item_w + GRID_GAP));
	return n < 1 ? 1 : n;
}

static int columns(struct c8ui_widget *w) {
	return columns_for(w->data, w->rect.width);
}

static double row_step(struct list *l) {
	return l->item_h + (l->mode != C8UI_LIST_ROWS ? GRID_GAP : 0);
}

/* Spans: puts each item in the first place in reading order where its
 * cells are free, so a small one fills the hole a big one left */
static void pack(struct list *l, int cols) {
	if (!l->pack_dirty && l->pack_cols == cols && l->cells) {
		return;
	}
	free(l->cells);
	l->cells = calloc(l->count ? l->count : 1, sizeof(struct cell));
	int cap = 8;
	bool *used = calloc((size_t)cap * cols, 1); // rows * cols
	int rows = 0;
	for (int i = 0; i < l->count; i++) {
		int sc = 1, sr = 1;
		if (l->span_fn) {
			l->span_fn(l->self, i, &sc, &sr, l->span_data);
		}
		sc = sc < 1 ? 1 : sc > cols ? cols : sc;
		sr = sr < 1 ? 1 : sr;
		for (int row = 0;; row++) {
			if (row + sr > cap) {
				int ncap = cap * 2 > row + sr ? cap * 2 : row + sr;
				used = realloc(used, (size_t)ncap * cols);
				memset(used + (size_t)cap * cols, 0, (size_t)(ncap - cap) * cols);
				cap = ncap;
			}
			bool placed = false;
			for (int col = 0; col + sc <= cols && !placed; col++) {
				bool free_ = true;
				for (int y = 0; y < sr && free_; y++) {
					for (int x = 0; x < sc; x++) {
						if (used[(size_t)(row + y) * cols + col + x]) {
							free_ = false;
							break;
						}
					}
				}
				if (!free_) {
					continue;
				}
				for (int y = 0; y < sr; y++) {
					memset(used + (size_t)(row + y) * cols + col, 1, sc);
				}
				l->cells[i] = (struct cell){ col, row, sc, sr };
				rows = row + sr > rows ? row + sr : rows;
				placed = true;
			}
			if (placed) {
				break;
			}
		}
	}
	free(used);
	l->pack_cols = cols;
	l->pack_rows = rows;
	l->pack_dirty = false;
}

static struct c8ui_rect item_rect(struct c8ui_widget *w, int i) {
	struct list *l = w->data;
	if (l->mode == C8UI_LIST_SPANS) {
		pack(l, columns_for(l, w->rect.width));
		struct cell *c = &l->cells[i];
		return (struct c8ui_rect){
			w->rect.x + c->col * (l->item_w + GRID_GAP),
			w->rect.y + c->row * row_step(l),
			c->cols * l->item_w + (c->cols - 1) * GRID_GAP,
			c->rows * l->item_h + (c->rows - 1) * GRID_GAP,
		};
	}
	if (l->mode == C8UI_LIST_ROWS) {
		return (struct c8ui_rect){ w->rect.x, w->rect.y + i * l->item_h,
			w->rect.width, l->item_h };
	}
	int cols = columns(w);
	return (struct c8ui_rect){
		w->rect.x + (i % cols) * (l->item_w + GRID_GAP),
		w->rect.y + (i / cols) * row_step(l),
		l->item_w, l->item_h,
	};
}

/* One item looks different: it alone is drawn again (its rect and a
 * hair around it; an item's draw fn keeps to its rect) */
static void damage_item(struct c8ui_widget *w, int i) {
	struct list *l = w->data;
	if (i < 0 || i >= l->count) {
		return;
	}
	struct c8ui_rect r = item_rect(w, i);
	c8ui_widget_queue_draw_rect(w, r.x - 2, r.y - 2, r.width + 4,
		r.height + 4);
}

int c8ui_list_item_at(struct c8ui_widget *w, double x, double y) {
	struct list *l = w->data;
	if (!c8ui_rect_contains(&w->rect, x, y)) {
		return -1;
	}
	if (l->mode == C8UI_LIST_SPANS) {
		for (int i = 0; i < l->count; i++) {
			struct c8ui_rect r = item_rect(w, i);
			if (c8ui_rect_contains(&r, x, y)) {
				return i;
			}
		}
		return -1;
	}
	int row = (int)floor((y - w->rect.y) / row_step(l));
	int col = 0;
	if (l->mode == C8UI_LIST_GRID) {
		col = (int)floor((x - w->rect.x) / (l->item_w + GRID_GAP));
		if (col >= columns(w)) {
			return -1;
		}
	}
	int i = row * columns(w) + col;
	if (row < 0 || col < 0 || i >= l->count) {
		return -1;
	}
	/* Not in the gaps between cells */
	struct c8ui_rect r = item_rect(w, i);
	return c8ui_rect_contains(&r, x, y) ? i : -1;
}

struct c8ui_rect c8ui_list_get_item_rect(struct c8ui_widget *w, int i) {
	struct list *l = w->data;
	if (i < 0 || i >= l->count) {
		return (struct c8ui_rect){ 0 };
	}
	return item_rect(w, i);
}

void c8ui_list_reveal(struct c8ui_widget *w, int i) {
	struct list *l = w->data;
	if (i < 0 || i >= l->count) {
		return;
	}
	struct c8ui_rect r = item_rect(w, i);
	c8ui_widget_reveal(w, &r);
}

/* Selection */

static void selection_changed(struct c8ui_widget *w) {
	struct list *l = w->data;
	c8ui_widget_queue_draw(w);
	if (l->select_fn) {
		l->select_fn(w, l->select_data);
	}
}

static void clear_selection(struct list *l) {
	if (l->count > 0) {
		memset(l->selected, 0, sizeof(bool) * l->count);
	}
}

static void select_range(struct list *l, int a, int b) {
	clear_selection(l);
	for (int i = MIN(a, b); i <= MAX(a, b); i++) {
		if (i >= 0 && i < l->count) {
			l->selected[i] = true;
		}
	}
}

/* Whether x, y is on item i's check box: the start of a row, the top
 * right corner of a cell (where a selected one has its tick) */
static bool on_check(struct c8ui_widget *w, int i, double x, double y) {
	struct list *l = w->data;
	if (!l->checks || !l->multiple || i < 0) {
		return false;
	}
	struct c8ui_rect r = item_rect(w, i);
	if (l->mode == C8UI_LIST_ROWS) {
		return x < r.x + C8UI_LIST_CHECK_WIDTH;
	}
	double s = CHECK_SIZE * 1.4;
	return x - (r.x + r.width - s) > y - r.y;
}

/* The band's rect in root coordinates */
static struct c8ui_rect band_rect(struct c8ui_widget *w) {
	struct list *l = w->data;
	return (struct c8ui_rect){
		w->rect.x + MIN(l->band_x0, l->band_x1),
		w->rect.y + MIN(l->band_y0, l->band_y1),
		fabs(l->band_x1 - l->band_x0), fabs(l->band_y1 - l->band_y0),
	};
}

static void band_select(struct c8ui_widget *w) {
	struct list *l = w->data;
	struct c8ui_rect b = band_rect(w);
	bool changed = false;
	for (int i = 0; i < l->count; i++) {
		struct c8ui_rect r = item_rect(w, i);
		bool in = r.x < b.x + b.width && r.x + r.width > b.x &&
			r.y < b.y + b.height && r.y + r.height > b.y;
		bool on = in || (l->band_base && l->band_base[i]);
		changed = changed || on != l->selected[i];
		l->selected[i] = on;
	}
	if (changed) {
		selection_changed(w);
	} else {
		c8ui_widget_queue_draw(w);
	}
}

static void band_end(struct list *l) {
	l->band_armed = l->banding = false;
	free(l->band_base);
	l->band_base = NULL;
}

/* What a click or a key does to the selection at i, by the modifiers */
static void pick(struct c8ui_widget *w, int i, uint32_t mods) {
	struct list *l = w->data;
	bool ctrl = l->multiple && (mods & C8UI_MOD_CTRL);
	bool shift = l->multiple && (mods & C8UI_MOD_SHIFT);
	if (shift) {
		select_range(l, l->anchor, i);
	} else if (ctrl) {
		l->selected[i] = !l->selected[i];
		l->anchor = i;
	} else {
		clear_selection(l);
		l->selected[i] = true;
		l->anchor = i;
	}
	l->cursor = i;
	selection_changed(w);
}

static void open_item(struct c8ui_widget *w, int i) {
	struct list *l = w->data;
	if (i >= 0 && i < l->count && l->open_fn) {
		l->open_fn(w, i, l->open_data);
	}
}

/* Opened by a click or a tap: where it was is known while the open fn
 * runs (c8ui_list_open_point), for items with parts of their own to press.
 * Not kept in the list: the fn may destroy it. */
static struct {
	struct c8ui_widget *list;
	double x, y;
} open_point;

static void open_item_at(struct c8ui_widget *w, int i, double x, double y) {
	open_point.list = w;
	open_point.x = x;
	open_point.y = y;
	open_item(w, i);
	open_point.list = NULL;
}

bool c8ui_list_open_point(struct c8ui_widget *w, double *x, double *y) {
	if (open_point.list != w) {
		return false;
	}
	*x = open_point.x;
	*y = open_point.y;
	return true;
}

static void context(struct c8ui_widget *w, int i, double x, double y) {
	struct list *l = w->data;
	if (l->context_fn) {
		l->context_fn(w, i, x, y, l->context_data);
	}
}

/* Drawing */

static void list_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct list *l = w->data;
	int cols = columns_for(l, avail);
	int rows = (l->count + cols - 1) / cols;
	if (l->mode == C8UI_LIST_SPANS) {
		pack(l, cols);
		rows = l->pack_rows;
	}
	*width = avail;
	*height = rows * row_step(l);
	if (l->mode != C8UI_LIST_ROWS && rows > 0) {
		*height -= GRID_GAP;
	}
}

/* The tick in the top right corner of a selected grid cell */
static void draw_check(cairo_t *cr, struct c8ui_rect r, uint32_t accent) {
	double x = r.x + r.width, y = r.y;
	c8ui_set_source(cr, accent, 1);
	cairo_move_to(cr, x - CHECK_SIZE * 1.4, y);
	cairo_line_to(cr, x, y);
	cairo_line_to(cr, x, y + CHECK_SIZE * 1.4);
	cairo_close_path(cr);
	cairo_fill(cr);
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_set_line_width(cr, 2);
	cairo_move_to(cr, x - 15, y + 9);
	cairo_line_to(cr, x - 11, y + 13);
	cairo_line_to(cr, x - 4, y + 5);
	cairo_stroke(cr);
}

static void list_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct list *l = w->data;
	if (l->count == 0) {
		return;
	}
	struct c8ui_colors c = c8ui_widget_colors(w);
	double cx0, cy0, cx1, cy1;
	cairo_clip_extents(cr, &cx0, &cy0, &cx1, &cy1);
	int cols = columns(w);
	int first_row = (int)floor((cy0 - w->rect.y) / row_step(l));
	int last_row = (int)floor((cy1 - w->rect.y) / row_step(l));
	int first = (first_row < 0 ? 0 : first_row) * cols;
	int last = (last_row + 1) * cols;
	if (l->mode == C8UI_LIST_SPANS) {
		/* Not in reading order down the screen: look at each */
		first = 0;
		last = l->count;
	}
	if (last > l->count) {
		last = l->count;
	}
	bool show_cursor = w->focused && w->root && w->root->focus_visible;
	bool grid = l->mode != C8UI_LIST_ROWS;

	for (int i = first; i < last; i++) {
		struct c8ui_rect r = item_rect(w, i);
		if (l->mode == C8UI_LIST_SPANS &&
				(r.y + r.height < cy0 || r.y > cy1)) {
			continue;
		}
		struct c8ui_list_item item = {
			.index = i,
			.rect = r,
			.selected = l->selected[i],
			.hovered = i == l->hover,
			.pressed = i == l->pressed && w->pressed,
			.cursor = i == l->cursor && w->focused,
			.fg = c.fg,
			.secondary = c.fg_secondary,
		};
		double depth = i == l->tilt_item ?
			c8ui_tilt_depth(&l->tilt, c8ui_now_ms()) : 0;
		bool tilted = depth > 0 && c8ui_tilt_begin(cr, &r, depth);
		/* Rows go accent when selected; cells keep their face and get a
		 * border and a tick, as Metro grids do */
		if (item.selected && !grid) {
			c8ui_set_source(cr, item.hovered ? c8ui_shade(c.accent, 1.12) :
				c.accent, 1);
			cairo_rectangle(cr, r.x, r.y, r.width, r.height);
			cairo_fill(cr);
			item.fg = 0xffffff;
			item.secondary = 0.8;
		} else if (item.hovered || item.pressed) {
			c8ui_set_source(cr, c.fg, item.pressed ? c.fill * 2 : c.fill);
			cairo_rectangle(cr, r.x, r.y, r.width, r.height);
			cairo_fill(cr);
		}
		bool check = l->checks && l->multiple;
		if (check && !grid && (item.selected || item.hovered)) {
			/* The row's box: ticked when selected, an outline to press
			 * while the pointer is on the row */
			double s = 18;
			double bx = round(r.x + (C8UI_LIST_CHECK_WIDTH - s) / 2 + 2);
			double by = round(r.y + (r.height - s) / 2);
			c8ui_set_source(cr, item.fg, item.selected ? 1 : 0.5);
			cairo_set_line_width(cr, 2);
			cairo_rectangle(cr, bx + 1, by + 1, s - 2, s - 2);
			cairo_stroke(cr);
			if (item.selected) {
				cairo_move_to(cr, bx + 4, by + 9);
				cairo_line_to(cr, bx + 8, by + 13);
				cairo_line_to(cr, bx + 14, by + 5);
				cairo_stroke(cr);
			}
		}
		if (l->draw && l->keep) {
			if (l->kept == NULL) {
				l->kept = calloc(l->count, sizeof(*l->kept));
			}
			struct keep_draw k = { w, item };
			/* All the fn is told, and the colours it may ask for */
			uint32_t state = item.selected | item.hovered << 1 |
				item.pressed << 2 | item.cursor << 3;
			state = (state * 31 + item.fg) * 31 + c.accent;
			state = (state * 31 + c.bg) * 31 + (uint32_t)(item.secondary * 255);
			c8ui_kept_draw(&l->kept[i], cr, r, state, keep_draw, &k);
		} else if (l->draw) {
			draw_item(w, cr, &item);
		}
		if (item.selected && grid) {
			c8ui_set_source(cr, c.accent, 1);
			cairo_set_line_width(cr, 3);
			cairo_rectangle(cr, r.x + 1.5, r.y + 1.5, r.width - 3,
				r.height - 3);
			cairo_stroke(cr);
			draw_check(cr, r, c.accent);
		} else if (check && grid && item.hovered) {
			/* Where a press ticks it */
			double s = CHECK_SIZE * 1.4;
			c8ui_set_source(cr, c.fg, 0.2);
			cairo_move_to(cr, r.x + r.width - s, r.y);
			cairo_line_to(cr, r.x + r.width, r.y);
			cairo_line_to(cr, r.x + r.width, r.y + s);
			cairo_close_path(cr);
			cairo_fill(cr);
		}
		if (item.cursor && show_cursor) {
			/* The keyboard's item: a dotted ring inside it */
			c8ui_set_source(cr, item.fg, 1);
			c8ui_dotted_rect(cr, r.x + 2.5, r.y + 2.5, r.width - 5,
				r.height - 5);
		}
		if (tilted) {
			c8ui_tilt_end(cr, &l->tilt, &r, depth);
		}
	}
	if (l->banding) {
		struct c8ui_rect b = band_rect(w);
		c8ui_set_source(cr, c.accent, 0.2);
		cairo_rectangle(cr, b.x, b.y, b.width, b.height);
		cairo_fill(cr);
		c8ui_set_source(cr, c.accent, 1);
		cairo_set_line_width(cr, 1);
		cairo_rectangle(cr, round(b.x) + 0.5, round(b.y) + 0.5,
			round(b.width), round(b.height));
		cairo_stroke(cr);
	}
}

/* Events */

static void move_cursor(struct c8ui_widget *w, int to, uint32_t mods) {
	struct list *l = w->data;
	if (l->count == 0) {
		return;
	}
	to = to < 0 ? 0 : to >= l->count ? l->count - 1 : to;
	if (l->multiple && (mods & C8UI_MOD_CTRL) &&
			!(mods & C8UI_MOD_SHIFT)) {
		/* Ctrl moves without selecting; Ctrl+Space picks */
		l->cursor = to;
		c8ui_widget_queue_draw(w);
	} else {
		pick(w, to, mods & C8UI_MOD_SHIFT);
	}
	c8ui_list_reveal(w, to);
}

static int page_items(struct c8ui_widget *w) {
	struct list *l = w->data;
	double h = 0;
	for (struct c8ui_widget *p = w->parent; p; p = p->parent) {
		if (p->impl->clips) {
			h = p->rect.height;
			break;
		}
	}
	int rows = h > 0 ? (int)floor(h / row_step(l)) - 1 : 5;
	return (rows < 1 ? 1 : rows) * columns(w);
}

/* The item above or below the cursor in a spanning grid: the nearest one
 * that overlaps its middle sideways */
static int span_neighbour(struct c8ui_widget *w, int from, int dir) {
	struct list *l = w->data;
	struct c8ui_rect r = item_rect(w, from);
	double mid = r.x + r.width / 2;
	int best = -1;
	double best_d = 0;
	for (int i = 0; i < l->count; i++) {
		struct c8ui_rect o = item_rect(w, i);
		double d = dir > 0 ? o.y - (r.y + r.height) : r.y - (o.y + o.height);
		if (d < -1 || mid < o.x || mid > o.x + o.width) {
			continue;
		}
		if (best < 0 || d < best_d) {
			best = i;
			best_d = d;
		}
	}
	return best;
}

static bool list_key(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct list *l = w->data;
	int cols = columns(w);
	int cur = l->cursor < 0 ? 0 : l->cursor;
	/* Alt and Super combinations are the app's (Alt+Enter: Properties) */
	if (ev->mods & (C8UI_MOD_ALT | C8UI_MOD_SUPER)) {
		return false;
	}
	if (l->mode == C8UI_LIST_SPANS && l->cursor >= 0 &&
			(ev->sym == XKB_KEY_Up || ev->sym == XKB_KEY_Down)) {
		int to = span_neighbour(w, cur, ev->sym == XKB_KEY_Down ? 1 : -1);
		if (to >= 0) {
			move_cursor(w, to, ev->mods);
		}
		return true;
	}
	bool ctrl = ev->mods & C8UI_MOD_CTRL;
	bool first_move = l->cursor < 0;
	switch (ev->sym) {
	case XKB_KEY_Up:
	case XKB_KEY_Down:
	case XKB_KEY_Left:
	case XKB_KEY_Right: {
		bool across = ev->sym == XKB_KEY_Left || ev->sym == XKB_KEY_Right;
		bool back = ev->sym == XKB_KEY_Up || ev->sym == XKB_KEY_Left;
		if (across && l->mode == C8UI_LIST_ROWS) {
			return false;
		}
		int step = (across ? 1 : cols) * (back ? -1 : 1);
		move_cursor(w, first_move ? 0 : cur + step, ev->mods);
		return true;
	}
	case XKB_KEY_Page_Up:
		move_cursor(w, cur - page_items(w), ev->mods);
		return true;
	case XKB_KEY_Page_Down:
		move_cursor(w, cur + page_items(w), ev->mods);
		return true;
	case XKB_KEY_Home:
		move_cursor(w, 0, ev->mods);
		return true;
	case XKB_KEY_End:
		move_cursor(w, l->count - 1, ev->mods);
		return true;
	case XKB_KEY_space:
		if (l->count == 0) {
			return false;
		}
		pick(w, cur, ctrl ? C8UI_MOD_CTRL : 0);
		return true;
	case XKB_KEY_Return:
	case XKB_KEY_KP_Enter:
		if (l->cursor < 0) {
			return false;
		}
		open_item(w, l->cursor);
		return true;
	case XKB_KEY_Menu:
	case XKB_KEY_F10:
		if (ev->sym == XKB_KEY_F10 && !(ev->mods & C8UI_MOD_SHIFT)) {
			return false;
		}
		if (l->context_fn) {
			struct c8ui_rect r = l->cursor >= 0 ? item_rect(w, l->cursor) :
				w->rect;
			context(w, l->cursor, r.x + r.width / 2, r.y + r.height / 2);
		}
		return true;
	case XKB_KEY_Escape:
		if (!l->multiple || c8ui_list_selected_count(w) == 0) {
			return false;
		}
		clear_selection(l);
		selection_changed(w);
		return true;
	default:
		if (ctrl && ev->base_sym == XKB_KEY_a && l->multiple) {
			c8ui_list_select_all(w, true);
			return true;
		}
		return false;
	}
}

/* The pressed item springs back */
static void tilt_up(struct c8ui_widget *w) {
	struct list *l = w->data;
	if (l->tilt.down) {
		c8ui_tilt_set(&l->tilt, false, 0, 0, c8ui_now_ms());
		c8ui_widget_animate(w);
	}
}

static bool list_tick(struct c8ui_widget *w, int64_t now) {
	struct list *l = w->data;
	/* A press the root took back (a drag out of the window, say) has no
	 * release to say so */
	if (l->tilt.down && !w->pressed) {
		tilt_up(w);
	}
	damage_item(w, l->tilt_item);
	return c8ui_tilt_moving(&l->tilt, c8ui_now_ms());
}

static bool list_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct list *l = w->data;
	switch (ev->type) {
	case C8UI_EVENT_MOTION: {
		if (l->pressed >= 0 && l->drag_fn &&
				hypot(ev->x - l->press_x, ev->y - l->press_y) > DRAG_START) {
			int p = l->pressed;
			l->pressed = -1;
			l->deferred = -1;
			tilt_up(w);
			if (!l->selected[p]) {
				pick(w, p, 0);
			}
			l->drag_fn(w, p, l->drag_data);
			return true;
		}
		if (l->band_armed) {
			l->band_x1 = ev->x - w->rect.x;
			l->band_y1 = ev->y - w->rect.y;
			if (!l->banding && hypot(l->band_x1 - l->band_x0,
					l->band_y1 - l->band_y0) > DRAG_START) {
				l->banding = true;
			}
			if (l->banding) {
				band_select(w);
				return true;
			}
		}
		int i = c8ui_list_item_at(w, ev->x, ev->y);
		if (i != l->hover) {
			damage_item(w, l->hover);
			l->hover = i;
			damage_item(w, i);
		}
		return false;
	}
	case C8UI_EVENT_LEAVE:
		damage_item(w, l->hover);
		l->hover = -1;
		return false;
	case C8UI_EVENT_PRESS: {
		int i = c8ui_list_item_at(w, ev->x, ev->y);
		if (ev->button == C8UI_BUTTON_RIGHT) {
			/* What is right-clicked is what the menu is for */
			if (i >= 0 && !l->selected[i]) {
				pick(w, i, 0);
			}
			context(w, i, ev->x, ev->y);
			return false;
		}
		if (ev->button != C8UI_BUTTON_LEFT) {
			return false;
		}
		l->pressed = i;
		if (i < 0) {
			if (!(ev->mods & C8UI_MOD_CTRL) && c8ui_list_selected_count(w)) {
				clear_selection(l);
				selection_changed(w);
			}
			band_end(l);
			if (l->multiple && l->count > 0) {
				l->band_armed = true;
				l->band_x0 = l->band_x1 = ev->x - w->rect.x;
				l->band_y0 = l->band_y1 = ev->y - w->rect.y;
				l->band_base = malloc(sizeof(bool) * l->count);
				memcpy(l->band_base, l->selected, sizeof(bool) * l->count);
			}
			return true;
		}
		if (on_check(w, i, ev->x, ev->y)) {
			/* The box: this one more or less, the rest as they are */
			l->pressed = -1;
			l->last_click = 0;
			pick(w, i, C8UI_MOD_CTRL);
			return true;
		}
		int64_t now = c8ui_now_ms();
		struct c8ui_rect ir = item_rect(w, i);
		if (l->tilt_item != i) {
			damage_item(w, l->tilt_item);
			l->tilt = (struct c8ui_tilt){ 0 };
			l->tilt_item = i;
		}
		c8ui_tilt_set(&l->tilt, true, ev->x - ir.x, ev->y - ir.y, now);
		c8ui_widget_animate(w);
		bool double_click = !l->click_opens && i == l->last_click_index &&
			now - l->last_click < C8UI_MULTI_CLICK_MS;
		l->last_click = double_click ? 0 : now;
		l->last_click_index = i;
		l->press_x = ev->x;
		l->press_y = ev->y;
		l->deferred = -1;
		if (l->drag_fn && l->selected[i] && c8ui_list_selected_count(w) > 1 &&
				!(ev->mods & (C8UI_MOD_CTRL | C8UI_MOD_SHIFT)) &&
				!double_click) {
			l->deferred = i;
			l->cursor = i;
			return true;
		}
		pick(w, i, ev->mods);
		if (double_click) {
			open_item_at(w, i, ev->x, ev->y);
		}
		return true;
	}
	case C8UI_EVENT_RELEASE: {
		int i = l->pressed;
		l->pressed = -1;
		tilt_up(w);
		band_end(l);
		if (l->deferred >= 0 && i == l->deferred &&
				c8ui_list_item_at(w, ev->x, ev->y) == i) {
			pick(w, i, 0);
		}
		l->deferred = -1;
		c8ui_widget_queue_draw(w);
		if (l->click_opens && i >= 0 &&
				c8ui_list_item_at(w, ev->x, ev->y) == i &&
				!(ev->mods & (C8UI_MOD_CTRL | C8UI_MOD_SHIFT))) {
			open_item_at(w, i, ev->x, ev->y);
		}
		return true;
	}
	case C8UI_EVENT_KEY:
		return list_key(w, ev);
	case C8UI_EVENT_FOCUS_IN:
	case C8UI_EVENT_FOCUS_OUT:
		c8ui_widget_queue_draw(w);
		return false;
	default:
		return false;
	}
}

static void list_destroy(struct c8ui_widget *w) {
	struct list *l = w->data;
	drop_kept(l);
	free(l->selected);
	free(l->band_base);
	free(l->cells);
	free(l);
}

static const struct c8ui_widget_impl list_impl = {
	.name = "list",
	.measure = list_measure,
	.draw = list_draw,
	.event = list_event,
	.tick = list_tick,
	.destroy = list_destroy,
	.tick_damages = true, // only the item that sinks in
};

struct c8ui_widget *c8ui_list_new(enum c8ui_list_mode mode, double item_width,
		double item_height, c8ui_list_draw_fn draw, void *data) {
	struct list *l = calloc(1, sizeof(*l));
	l->mode = mode;
	l->item_w = item_width > 0 ? item_width : 1;
	l->item_h = item_height > 0 ? item_height : 1;
	l->cursor = l->anchor = l->hover = l->pressed = l->deferred = -1;
	l->tilt_item = -1;
	l->last_click_index = -1;
	l->draw = draw;
	l->draw_data = data;
	l->pack_dirty = true;
	struct c8ui_widget *w = c8ui_widget_new(&list_impl, l);
	l->self = w;
	w->focusable = true;
	w->fill = true;
	return w;
}

void c8ui_list_set_mode(struct c8ui_widget *w, enum c8ui_list_mode mode,
		double item_width, double item_height) {
	struct list *l = w->data;
	l->mode = mode;
	l->item_w = item_width > 0 ? item_width : 1;
	l->item_h = item_height > 0 ? item_height : 1;
	l->pack_dirty = true;
	c8ui_widget_queue_layout(w);
}

void c8ui_list_set_spans(struct c8ui_widget *w, c8ui_list_span_fn fn,
		void *data) {
	struct list *l = w->data;
	l->span_fn = fn;
	l->span_data = data;
	l->pack_dirty = true;
	c8ui_widget_queue_layout(w);
}

void c8ui_list_set_count(struct c8ui_widget *w, int count) {
	struct list *l = w->data;
	count = count < 0 ? 0 : count;
	drop_kept(l); // while count is still how many there are
	band_end(l);
	l->selected = realloc(l->selected, sizeof(bool) * (count ? count : 1));
	if (count > l->count) {
		memset(l->selected + l->count, 0, sizeof(bool) * (count - l->count));
	}
	l->count = count;
	l->pack_dirty = true;
	if (l->cursor >= count) {
		l->cursor = count - 1;
	}
	if (l->anchor >= count) {
		l->anchor = count - 1;
	}
	if (l->hover >= count) {
		l->hover = -1;
	}
	l->pressed = -1;
	l->tilt_item = -1;
	l->tilt = (struct c8ui_tilt){ 0 };
	l->last_click_index = -1;
	c8ui_widget_queue_layout(w);
}

int c8ui_list_get_count(struct c8ui_widget *w) {
	return ((struct list *)w->data)->count;
}

void c8ui_list_redraw(struct c8ui_widget *w) {
	drop_kept(w->data);
	c8ui_widget_queue_draw(w);
}

void c8ui_list_set_keep(struct c8ui_widget *w, bool keep) {
	struct list *l = w->data;
	l->keep = keep;
	if (!keep) {
		drop_kept(l);
	}
	c8ui_widget_queue_draw(w);
}

void c8ui_list_redraw_item(struct c8ui_widget *w, int index) {
	struct list *l = w->data;
	if (l->kept && index >= 0 && index < l->count) {
		c8ui_kept_drop(&l->kept[index]);
	}
	damage_item(w, index);
}

void c8ui_list_not_final(struct c8ui_widget *w) {
	((struct list *)w->data)->not_final = true;
}

void c8ui_list_set_multiple(struct c8ui_widget *w, bool multiple) {
	((struct list *)w->data)->multiple = multiple;
}

void c8ui_list_set_checks(struct c8ui_widget *w, bool checks) {
	((struct list *)w->data)->checks = checks;
	c8ui_widget_queue_draw(w);
}

void c8ui_list_set_click_opens(struct c8ui_widget *w, bool click_opens) {
	((struct list *)w->data)->click_opens = click_opens;
}

void c8ui_list_on_open(struct c8ui_widget *w, c8ui_list_fn fn, void *data) {
	struct list *l = w->data;
	l->open_fn = fn;
	l->open_data = data;
}

void c8ui_list_on_select(struct c8ui_widget *w, c8ui_action_fn fn,
		void *data) {
	struct list *l = w->data;
	l->select_fn = fn;
	l->select_data = data;
}

void c8ui_list_on_drag(struct c8ui_widget *w, c8ui_list_fn fn, void *data) {
	struct list *l = w->data;
	l->drag_fn = fn;
	l->drag_data = data;
}

void c8ui_list_on_context(struct c8ui_widget *w, c8ui_list_context_fn fn,
		void *data) {
	struct list *l = w->data;
	l->context_fn = fn;
	l->context_data = data;
}

int c8ui_list_get_selected(struct c8ui_widget *w) {
	struct list *l = w->data;
	for (int i = 0; i < l->count; i++) {
		if (l->selected[i]) {
			return i;
		}
	}
	return -1;
}

bool c8ui_list_is_selected(struct c8ui_widget *w, int i) {
	struct list *l = w->data;
	return i >= 0 && i < l->count && l->selected[i];
}

int c8ui_list_selected_count(struct c8ui_widget *w) {
	struct list *l = w->data;
	int n = 0;
	for (int i = 0; i < l->count; i++) {
		n += l->selected[i];
	}
	return n;
}

void c8ui_list_select(struct c8ui_widget *w, int i) {
	struct list *l = w->data;
	clear_selection(l);
	if (i >= 0 && i < l->count) {
		l->selected[i] = true;
		l->cursor = l->anchor = i;
	}
	c8ui_widget_queue_draw(w);
}

void c8ui_list_set_selected(struct c8ui_widget *w, int i, bool selected) {
	struct list *l = w->data;
	if (i >= 0 && i < l->count) {
		l->selected[i] = selected;
		c8ui_widget_queue_draw(w);
	}
}

void c8ui_list_select_all(struct c8ui_widget *w, bool selected) {
	struct list *l = w->data;
	for (int i = 0; i < l->count; i++) {
		l->selected[i] = selected;
	}
	selection_changed(w);
}

void c8ui_list_draw_text(struct c8ui_widget *w, cairo_t *cr,
		const struct c8ui_list_item *item, struct c8ui_icon *icon,
		const char *title, const char *subtitle) {
	struct list *l = w->data;
	const char *family = c8ui_widget_font(w);
	struct c8ui_rect r = item->rect;
	struct c8ui_font tf = c8ui_text_font(C8UI_TEXT_BODY);
	struct c8ui_font sf = c8ui_text_font(C8UI_TEXT_CAPTION);
	double tw, th, sw = 0, sh = 0;
	c8ui_text_size(family, tf, "Ag", 0, 0, &tw, &th);
	if (subtitle && subtitle[0]) {
		c8ui_text_size(family, sf, "Ag", 0, 0, &sw, &sh);
	}
	if (l->mode == C8UI_LIST_ROWS) {
		double pad = 10, x = r.x + pad;
		if (icon) {
			double size = r.height - 2 * 8 > 48 ? 48 : r.height - 2 * 8;
			c8ui_icon_draw_fit(cr, icon, x + size / 2, r.y + r.height / 2,
				size);
			x += size + 12;
		}
		double y = r.y + (r.height - th - sh) / 2;
		double width = r.x + r.width - pad - x;
		c8ui_set_source(cr, item->fg, 1);
		c8ui_text_draw(cr, family, tf, title, x, y, width, 1);
		if (sh > 0) {
			c8ui_set_source(cr, item->fg, item->secondary);
			c8ui_text_draw(cr, family, sf, subtitle, x, y + th, width, 1);
		}
		return;
	}
	/* A cell: the icon fills the top, the text under it */
	double pad = 8;
	double text_h = th + sh;
	double size = r.height - text_h - 3 * pad;
	if (size > r.width - 2 * pad) {
		size = r.width - 2 * pad;
	}
	if (icon && size > 0) {
		c8ui_icon_draw_fit(cr, icon, r.x + r.width / 2,
			r.y + pad + (r.height - text_h - 3 * pad) / 2, size);
	}
	double y = r.y + r.height - pad - text_h;
	double width = r.width - 2 * pad;
	/* Centred */
	double ttw, tth;
	c8ui_text_size(family, tf, title, width, 1, &ttw, &tth);
	c8ui_set_source(cr, item->fg, 1);
	c8ui_text_draw(cr, family, tf, title, r.x + (r.width - ttw) / 2, y, width,
		1);
	if (sh > 0) {
		double stw, sth;
		c8ui_text_size(family, sf, subtitle, width, 1, &stw, &sth);
		c8ui_set_source(cr, item->fg, item->secondary);
		c8ui_text_draw(cr, family, sf, subtitle, r.x + (r.width - stw) / 2,
			y + th, width, 1);
	}
}
