/*
 * Search: typing anywhere on Start or All apps turns the page into
 * results, in columns side by side: the tiles that match (live ones by
 * what they show, too) with live tile widgets not yet pinned, then apps,
 * PC settings pages and running it as a command, then files by name.
 * Enter opens the best one, which is outlined; the arrows move between
 * them. Escape, or backspacing it all away, goes back to where it began.
 *
 * start.c hands it drawing and input while it is up, over Start's
 * background; Start and All apps keep their state underneath.
 */
#define _GNU_SOURCE
#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include "shell.h"

#define BOX_X (START_MARGIN_X + 190)
#define BOX_Y 52
#define BOX_W 360
#define BOX_H 38
#define BOTTOM_GAP 72
#define COL_GAP 24
#define ICON_PX 28
#define OPEN_MS 500

#define MAX_TILES 40
#define MAX_WIDGETS 8
#define MAX_APPS 24
#define MAX_SETTINGS 6
#define MAX_FILES 40
#define MAX_ITEMS (MAX_TILES + MAX_WIDGETS + MAX_APPS + MAX_SETTINGS + 1 + \
	MAX_FILES)

enum kind {
	ITEM_TILE,
	ITEM_WIDGET,
	ITEM_APP,
	ITEM_SETTING,
	ITEM_RUN,
	ITEM_FILE,
};

enum section {
	SECTION_TILES,
	SECTION_APPS,
	SECTION_FILES,
	SECTION_COUNT,
};

static const char *const section_names[] = {
	[SECTION_TILES] = "Tiles",
	[SECTION_APPS] = "Apps",
	[SECTION_FILES] = "Files",
};

/* PC settings pages, by what's on them */
struct setting_page {
	const char *page, *title, *words, *icon;
};

static const struct setting_page setting_pages[] = {
	{ "personalise", "Personalise", "accent colour color start background "
		"pattern theme font icons appearance tiles", "preferences-desktop" },
	{ "displays", "Displays", "screen monitor resolution scale refresh rate "
		"rotation orientation night light warm colours blue",
		"preferences-desktop-display" },
	{ "info", "PC info", "about computer processor cpu memory ram graphics "
		"system kernel version name", "computer" },
	{ "mouse", "Mouse and touchpad", "pointer cursor touchpad trackpad tap "
		"click scrolling natural speed acceleration", "input-mouse" },
	{ "keyboard", "Keyboard", "layout language repeat delay keymap",
		"input-keyboard" },
	{ "shortcuts", "Keyboard shortcuts", "keys bindings hotkeys",
		"preferences-desktop-keyboard-shortcuts" },
	{ "startup", "Startup apps", "autostart login sign in", "system-run" },
	{ "power", "Power", "sleep screen off battery lid idle lock suspend "
		"shut down restart", "battery" },
	{ "defaults", "Default apps", "browser mail email files file manager music video photos "
		"calendar maps terminal text editor open with", "preferences-desktop" },
	{ "general", "General", "terminal x11 xwayland apps", "preferences-system" },
};

struct item {
	enum kind kind;
	enum section section;
	struct tile *tile;
	struct app *app;
	const struct setting_page *setting;
	struct file_hit file;
	struct rect box;
	/* A row drawn once and kept: pango and a group per row each frame
	 * made the opening sweep stutter */
	cairo_surface_t *face;
	double face_scale;
	unsigned face_gen;
};

/* Icons by name, for settings, files and Run */
struct named_icon {
	struct c8ui_icon_request *req;
	cairo_surface_t *raster;
	int px;
	bool missing;
};

static struct {
	bool active;
	struct c8ui_textedit *edit; // the search box
	const char *query; // its text: refreshed after every edit
	double box_scroll;
	bool box_drag; // selecting in the box with the pointer
	char *folded;
	struct item items[MAX_ITEMS];
	int count, focus;
	int section_x[SECTION_COUNT];
	bool section_shown[SECTION_COUNT];

	int width, height, content_width;
	double scroll, scroll_target, fling;
	int64_t opened_at;
	double scale;
	unsigned icon_gen; // bumped as icons arrive: faces drawn before redo
	GHashTable *icons; // name -> struct named_icon
} se = { .query = "", .focus = -1, .scale = 1 };

/* Matching */

static bool word_start(const char *text, const char *at) {
	if (at == text) {
		return true;
	}
	unsigned char c = (unsigned char)at[-1];
	return c < 0x80 && !isalnum(c);
}

int search_score(const char *text, const char *query) {
	if (text == NULL || query == NULL || query[0] == '\0') {
		return 0;
	}
	const char *at = strstr(text, query);
	if (at == NULL) {
		return 0;
	}
	if (at == text) {
		return strcmp(text, query) == 0 ? 4 : 3;
	}
	for (; at; at = strstr(at + 1, query)) {
		if (word_start(text, at)) {
			return 2;
		}
	}
	/* Inside a word: one letter would find nearly everything */
	return query[1] ? 1 : 0;
}

/* Fuzzy matching, for names: the query's letters in order with gaps
 * allowed, like fzf. Each letter scores, more at the start of a word or
 * a camelCase hump and in unbroken runs; gaps cost a little. */

#define FUZZY_MATCH 16
#define FUZZY_GAP_START 3
#define FUZZY_GAP 1
#define FUZZY_FIRST 10 // the very start of the name
#define FUZZY_WORD 8 // after a space, dash, dot, underscore...
#define FUZZY_CAMEL 7 // fooBar
#define FUZZY_RUN 4 // at least, for each letter that follows the last
#define FUZZY_PREFIX 20
/* Below this per letter typed it's letters scattered all over */
#define FUZZY_MIN 10

static bool word_char(unsigned char c) {
	return c >= 0x80 || isalnum(c);
}

/* How much a letter at i counts for where it sits; case comes from the
 * name as written, when casefolding left it the same length */
static int fuzzy_bonus(const char *text, const char *orig, size_t i) {
	if (i == 0) {
		return FUZZY_FIRST;
	}
	if (!word_char((unsigned char)text[i - 1])) {
		return FUZZY_WORD;
	}
	if (orig && isupper((unsigned char)orig[i]) &&
			islower((unsigned char)orig[i - 1])) {
		return FUZZY_CAMEL;
	}
	if (isdigit((unsigned char)text[i]) &&
			!isdigit((unsigned char)text[i - 1])) {
		return FUZZY_CAMEL;
	}
	return 0;
}

int search_fuzzy(const char *text, const char *orig, const char *query) {
	if (text == NULL || query == NULL || query[0] == '\0') {
		return 0;
	}
	size_t tn = strlen(text), qn = strlen(query);
	if (orig && strlen(orig) != tn) {
		orig = NULL;
	}
	/* One letter: only where a word starts, or it finds everything */
	if (qn == 1) {
		int s = search_score(text, query);
		return s >= 2 ? FUZZY_MATCH + FUZZY_WORD * 2 + (s - 2) * FUZZY_PREFIX :
			0;
	}
	/* The earliest end of a match, then back from there to its latest
	 * start: the tightest window, as fzf's first pass does */
	size_t ti = 0, qi = 0;
	for (; ti < tn && qi < qn; ti++) {
		qi += text[ti] == query[qi];
	}
	if (qi < qn) {
		return 0;
	}
	size_t end = ti, start = end;
	for (qi = qn; qi > 0; ) {
		start--;
		qi -= text[start] == query[qi - 1];
	}
	int score = 0, run_bonus = 0;
	bool run = false, gap = false;
	qi = 0;
	for (size_t i = start; i < end; i++) {
		if (qi < qn && text[i] == query[qi]) {
			int bonus = fuzzy_bonus(text, orig, i);
			if (run) {
				bonus = MAX(bonus, MAX(run_bonus, FUZZY_RUN));
			} else {
				run_bonus = bonus;
			}
			score += FUZZY_MATCH + (qi == 0 ? bonus * 2 : bonus);
			run = true;
			gap = false;
			qi++;
		} else {
			score -= gap ? FUZZY_GAP : FUZZY_GAP_START;
			run = false;
			gap = true;
		}
	}
	if (strncmp(text, query, qn) == 0) {
		score += tn == qn ? FUZZY_PREFIX * 2 : FUZZY_PREFIX;
	}
	return score >= (int)qn * FUZZY_MIN ? score : 0;
}

/* A name as written, for fuzzy matching */
static int name_score(const char *name, const char *query) {
	if (name == NULL) {
		return 0;
	}
	char *folded = g_utf8_casefold(name, -1);
	int score = search_fuzzy(folded, name, query);
	g_free(folded);
	return score;
}

/* Longer text (what a tile shows, keywords) by the start of a word, at a
 * score below any name that matches */
static int text_score(const char *text, const char *query) {
	if (text == NULL) {
		return 0;
	}
	char *folded = g_utf8_casefold(text, -1);
	int score = search_score(folded, query) >= 2 ?
		(int)strlen(query) * FUZZY_MIN - 1 : 0;
	g_free(folded);
	return score;
}

/* What a live tile shows, minus its images */
static int live_score(struct tile *tile, const char *query) {
	struct live *live = live_find(tile->id);
	int best = 0;
	for (guint i = 0; live && i < live->updates->len; i++) {
		struct live_update *u = live->updates->pdata[i];
		GHashTableIter iter;
		gpointer key, value;
		g_hash_table_iter_init(&iter, u->fields);
		while (g_hash_table_iter_next(&iter, &key, &value)) {
			if (strstr(key, "image") || strstr(key, "src")) {
				continue;
			}
			int score = text_score(value, query);
			best = score > best ? score : best;
		}
	}
	return best;
}

struct tile_hit {
	struct tile *tile;
	int score, order;
};

static int tile_hit_cmp(const void *a, const void *b) {
	const struct tile_hit *x = a, *y = b;
	return x->score != y->score ? y->score - x->score : x->order - y->order;
}

/* Packed biggest first, so they fit together without holes; the best
 * match is the one outlined wherever it lands */
static int tile_size_cmp(const void *a, const void *b) {
	const struct tile_hit *x = a, *y = b;
	if (x->tile->size != y->tile->size) {
		return (int)y->tile->size - (int)x->tile->size;
	}
	return tile_hit_cmp(a, b);
}

static void clear_items(void) {
	for (int i = 0; i < se.count; i++) {
		if (se.items[i].face) {
			cairo_surface_destroy(se.items[i].face);
		}
	}
	se.count = 0;
}

static struct item *add(enum kind kind, enum section section) {
	struct item *item = &se.items[se.count++];
	*item = (struct item){ .kind = kind, .section = section };
	return item;
}

/* Whether the first word is a program, so Enter runs it rather than
 * opening a file of that name */
static bool is_program(const char *query) {
	char *word = g_strndup(query, strcspn(query, " \t"));
	char *path = g_find_program_in_path(word);
	g_free(word);
	g_free(path);
	return path != NULL;
}

/* Enter's choice: a tile, else an app, a settings page, then a file
 * unless what was typed is a command */
static int best_item(void) {
	static const enum kind order[] = { ITEM_TILE, ITEM_APP, ITEM_SETTING };
	for (size_t k = 0; k < G_N_ELEMENTS(order); k++) {
		for (int i = 0; i < se.count; i++) {
			if (se.items[i].kind == order[k]) {
				return i;
			}
		}
	}
	int run = -1, file = -1;
	for (int i = 0; i < se.count; i++) {
		if (se.items[i].kind == ITEM_RUN) {
			run = i;
		} else if (se.items[i].kind == ITEM_FILE && file < 0) {
			file = i;
		}
	}
	return file >= 0 && !is_program(se.query) ? file : run;
}

static void layout(void);

static void query(void) {
	clear_items();
	g_free(se.folded);
	se.folded = g_utf8_casefold(se.query, -1);
	if (se.query[0] == '\0') {
		se.focus = -1;
		layout();
		return;
	}
	const char *q = se.folded;

	/* Tiles: the name counts most, then its id and what it shows */
	struct tile_hit tiles[MAX_TILES];
	int ntiles = 0, order = 0;
	struct group *group;
	struct tile *tile;
	for_each_tile(group, tile) {
		int score = name_score(tile->name, q);
		if (score == 0) {
			score = name_score(tile->id, q) * 3 / 4;
		}
		if (score == 0 && tile_is_live(tile)) {
			score = live_score(tile, q);
		}
		if (score > 0 && ntiles < MAX_TILES) {
			tiles[ntiles++] = (struct tile_hit){ tile, score, order };
		}
		order++;
	}
	qsort(tiles, ntiles, sizeof(*tiles), tile_hit_cmp);
	struct tile *best = ntiles ? tiles[0].tile : NULL;
	qsort(tiles, ntiles, sizeof(*tiles), tile_size_cmp);
	for (int i = 0; i < ntiles; i++) {
		add(ITEM_TILE, SECTION_TILES)->tile = tiles[i].tile;
	}
	struct app *apps[MAX_APPS];
	int n = apps_search(q, true, apps, MAX_WIDGETS);
	for (int i = 0; i < n; i++) {
		add(ITEM_WIDGET, SECTION_TILES)->app = apps[i];
	}

	/* Apps not already found as tiles */
	n = apps_search(q, false, apps, MAX_APPS);
	for (int i = 0; i < n; i++) {
		bool shown = false;
		for (int t = 0; t < ntiles && !shown; t++) {
			shown = apps_same(apps[i], tiles[t].tile);
		}
		if (!shown) {
			add(ITEM_APP, SECTION_APPS)->app = apps[i];
		}
	}
	/* Settings pages by title, else by what's on them; best first */
	struct {
		const struct setting_page *page;
		int score;
	} pages[G_N_ELEMENTS(setting_pages)];
	int npages = 0;
	for (size_t i = 0; i < G_N_ELEMENTS(setting_pages); i++) {
		const struct setting_page *page = &setting_pages[i];
		int score = name_score(page->title, q);
		if (score == 0) {
			score = text_score(page->words, q);
		}
		if (score > 0) {
			int at = npages++;
			for (; at > 0 && pages[at - 1].score < score; at--) {
				pages[at] = pages[at - 1];
			}
			pages[at].page = page;
			pages[at].score = score;
		}
	}
	for (int i = 0; i < npages && i < MAX_SETTINGS; i++) {
		add(ITEM_SETTING, SECTION_APPS)->setting = pages[i].page;
	}
	add(ITEM_RUN, SECTION_APPS);

	struct file_hit files[MAX_FILES];
	n = files_search(q, files, MAX_FILES);
	for (int i = 0; i < n; i++) {
		add(ITEM_FILE, SECTION_FILES)->file = files[i];
	}

	se.focus = best_item();
	for (int i = 0; best && i < se.count; i++) {
		if (se.items[i].tile == best) {
			se.focus = i; // a tile is Enter's first choice
		}
	}
	se.scroll_target = 0;
	se.fling = 0;
	layout();
}

/* Layout: each section is a heading over columns that fill downwards,
 * the tiles packed four cells wide as in a group on Start */

static void layout(void) {
	int cell = tile_cell(), pitch = cell + TILE_GAP;
	int top = START_TILES_Y, bottom = se.height - BOTTOM_GAP;
	int rows = (bottom - top + TILE_GAP) / pitch;
	rows = rows < 4 ? 4 : rows;
	int band_w = BAND_CELLS * pitch - TILE_GAP;
	rows = rows > 64 ? 64 : rows;
	int x = START_MARGIN_X, right = x;

	for (int s = 0; s < SECTION_COUNT; s++) {
		se.section_shown[s] = false;
		int col_x = x, y = top;
		/* Cells taken in the current band of tiles */
		bool used[BAND_CELLS][64] = { 0 };
		int used_rows = 0;
		for (int i = 0; i < se.count; i++) {
			struct item *item = &se.items[i];
			if (item->section != (enum section)s) {
				continue;
			}
			if (!se.section_shown[s]) {
				se.section_shown[s] = true;
				se.section_x[s] = x;
			}
			if (item->kind == ITEM_TILE) {
				int cw, ch;
				tile_size_cells(item->tile->size, &cw, &ch);
				ch = ch > rows ? rows : ch;
				int pc = -1, pr = -1;
				for (int r = 0; pc < 0 && r + ch <= rows; r++) {
					for (int c = 0; pc < 0 && c + cw <= BAND_CELLS; c++) {
						bool free = true;
						for (int dc = 0; free && dc < cw; dc++) {
							for (int dr = 0; free && dr < ch; dr++) {
								free = !used[c + dc][r + dr];
							}
						}
						if (free) {
							pc = c;
							pr = r;
						}
					}
				}
				if (pc < 0) {
					/* This band is full: the next one along */
					col_x += band_w + TILE_GAP;
					memset(used, 0, sizeof(used));
					used_rows = 0;
					pc = pr = 0;
				}
				for (int dc = 0; dc < cw; dc++) {
					for (int dr = 0; dr < ch; dr++) {
						used[pc + dc][pr + dr] = true;
					}
				}
				used_rows = pr + ch > used_rows ? pr + ch : used_rows;
				item->box = (struct rect){ col_x + pc * pitch,
					top + pr * pitch, cw * pitch - TILE_GAP,
					ch * pitch - TILE_GAP };
				y = top + used_rows * pitch + 16;
				right = col_x + band_w > right ? col_x + band_w : right;
				continue;
			}
			/* A row, under any tiles; a full column starts another */
			if (y + ENTRY_H > bottom && y > top) {
				col_x = right + COL_GAP;
				y = top;
				memset(used, 0, sizeof(used));
				used_rows = 0;
			}
			item->box = (struct rect){ col_x, y, ENTRY_W, ENTRY_H };
			y += ENTRY_PITCH;
			right = col_x + ENTRY_W > right ? col_x + ENTRY_W : right;
		}
		if (se.section_shown[s]) {
			x = right + GROUP_GAP;
		}
	}
	se.content_width = right + START_MARGIN_X;
	double max = se.content_width - se.width;
	se.scroll_target = fmin(se.scroll_target, fmax(max, 0));
	start_animate();
}

static void scroll_into_view(struct item *item) {
	scroll_reveal(&se.scroll_target, &item->box, se.content_width, se.width);
	start_animate();
}

/* Icons by name */

static void named_free(gpointer data) {
	struct named_icon *ni = data;
	c8ui_icon_request_cancel(ni->req);
	if (ni->raster) {
		cairo_surface_destroy(ni->raster);
	}
	g_free(ni);
}

static void named_loaded(void *data, cairo_surface_t *image) {
	struct named_icon *ni = data;
	ni->req = NULL;
	if (image) {
		ni->raster = image;
	} else {
		ni->missing = true;
	}
	se.icon_gen++;
	start_redraw();
}

/* The first of names the theme has, NULL while it loads or if none */
static cairo_surface_t *named_icon(const char *const *names, int n) {
	int px = (int)ceil(ICON_PX * se.scale);
	for (int i = 0; i < n; i++) {
		if (names[i] == NULL) {
			continue;
		}
		char key[256];
		snprintf(key, sizeof(key), "%d:%s", px, names[i]);
		struct named_icon *ni = g_hash_table_lookup(se.icons, key);
		if (ni == NULL) {
			ni = g_new0(struct named_icon, 1);
			ni->px = px;
			g_hash_table_insert(se.icons, g_strdup(key), ni);
			ni->req = c8ui_icon_request(shell.appearance.icon_theme,
				names[i], px, true, named_loaded, ni);
		}
		if (ni->raster) {
			return ni->raster;
		}
		if (!ni->missing) {
			return NULL; // on its way
		}
	}
	return NULL;
}

/* Drawing */

static void text(cairo_t *cr, const char *family, double size,
		enum c8ui_weight weight, const char *s, double x, double y,
		double max_width) {
	c8ui_text_draw(cr, family, (struct c8ui_font){ size, weight }, s, x, y,
		max_width, max_width > 0 ? 1 : 0);
}

static void draw_icon_raster(cairo_t *cr, cairo_surface_t *raster,
		double cx, double cy) {
	int iw = cairo_image_surface_get_width(raster);
	int ih = cairo_image_surface_get_height(raster);
	double s = ICON_PX / ceil(ICON_PX * se.scale);
	cairo_save(cr);
	cairo_translate(cr, cx - iw * s / 2, cy - ih * s / 2);
	cairo_scale(cr, s, s);
	cairo_set_source_surface(cr, raster, 0, 0);
	cairo_paint(cr);
	cairo_restore(cr);
}

/* "~/Documents/notes" for the folder a file is in */
static void parent_label(const char *path, char *out, size_t len) {
	const char *home = g_get_home_dir();
	size_t hlen = strlen(home);
	const char *slash = strrchr(path, '/');
	int plen = slash ? (int)(slash - path) : 0;
	if (strncmp(path, home, hlen) == 0 && (int)hlen <= plen &&
			(path[hlen] == '/' || path[hlen] == '\0')) {
		snprintf(out, len, "~%.*s", plen - (int)hlen, path + hlen);
	} else {
		/* Outside home it can still name the login (/run/media/LOGIN) */
		char *where = g_strndup(plen ? path : "/", plen ? plen : 1);
		snprintf(out, len, "%s", c8_stealth_show(where));
		g_free(where);
	}
}

/* For themes without file icons: a folder, or a page with its corner
 * turned down, in white outline */
static void draw_file_glyph(cairo_t *cr, bool dir, double cx, double cy) {
	cairo_save(cr);
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_set_line_width(cr, 1.5);
	cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
	if (dir) {
		double l = cx - 12, r = cx + 12, t = cy - 8, b = cy + 9;
		cairo_move_to(cr, l, b);
		cairo_line_to(cr, l, t);
		cairo_line_to(cr, l + 8, t);
		cairo_line_to(cr, l + 11, t + 3);
		cairo_line_to(cr, r, t + 3);
		cairo_line_to(cr, r, b);
		cairo_close_path(cr);
		cairo_move_to(cr, l, t + 7);
		cairo_line_to(cr, r, t + 7);
	} else {
		double l = cx - 9, r = cx + 9, t = cy - 12, b = cy + 12, k = 6;
		cairo_move_to(cr, l, t);
		cairo_line_to(cr, r - k, t);
		cairo_line_to(cr, r, t + k);
		cairo_line_to(cr, r, b);
		cairo_line_to(cr, l, b);
		cairo_close_path(cr);
		cairo_move_to(cr, r - k, t);
		cairo_line_to(cr, r - k, t + k);
		cairo_line_to(cr, r, t + k);
	}
	cairo_stroke(cr);
	cairo_restore(cr);
}

static void draw_row(cairo_t *cr, const char *family, struct item *item) {
	char line1[256], line2[256];
	const char *names[3] = { NULL };
	char *type = NULL, *generic = NULL;
	bool square = true;
	switch (item->kind) {
	case ITEM_SETTING:
		snprintf(line1, sizeof(line1), "%s", item->setting->title);
		snprintf(line2, sizeof(line2), "PC settings");
		names[0] = item->setting->icon;
		names[1] = "preferences-system";
		break;
	case ITEM_RUN:
		snprintf(line1, sizeof(line1), "Run \"%s\"", se.query);
		snprintf(line2, sizeof(line2), "Command");
		names[0] = "system-run";
		names[1] = "utilities-terminal";
		break;
	case ITEM_FILE: {
		snprintf(line1, sizeof(line1), "%s",
			c8_stealth_show(item->file.name));
		parent_label(item->file.path, line2, sizeof(line2));
		square = false;
		if (item->file.dir) {
			names[0] = "folder";
			break;
		}
		/* By the name only: nothing is read from the file */
		type = g_content_type_guess(item->file.name, NULL, 0, NULL);
		GIcon *icon = g_content_type_get_icon(type);
		if (G_IS_THEMED_ICON(icon)) {
			const char *const *themed = g_themed_icon_get_names(
				G_THEMED_ICON(icon));
			names[0] = themed && themed[0] ? themed[0] : NULL;
			if (names[0]) {
				names[0] = g_intern_string(names[0]);
			}
		}
		g_object_unref(icon);
		generic = g_content_type_get_generic_icon_name(type);
		names[1] = generic;
		names[2] = "text-x-generic";
		break;
	}
	default:
		return;
	}
	if (square) {
		c8ui_set_source(cr, shell.appearance.accent, 1);
		cairo_rectangle(cr, 0, 0, ENTRY_H, ENTRY_H);
		cairo_fill(cr);
	}
	cairo_surface_t *raster = named_icon(names, 3);
	if (raster) {
		draw_icon_raster(cr, raster, ENTRY_H / 2.0, ENTRY_H / 2.0);
	} else if (item->kind == ITEM_FILE) {
		draw_file_glyph(cr, item->file.dir, ENTRY_H / 2.0, ENTRY_H / 2.0);
	}
	g_free(type);
	g_free(generic);
	double tx = ENTRY_H + 12, tw = ENTRY_W - ENTRY_H - 16;
	cairo_set_source_rgb(cr, 1, 1, 1);
	text(cr, family, 15, C8UI_WEIGHT_NORMAL, line1, tx, 0, tw);
	cairo_set_source_rgba(cr, 1, 1, 1, 0.6);
	text(cr, family, 12, C8UI_WEIGHT_NORMAL, line2, tx, 21, tw);
}

#define BOX_FONT ((struct c8ui_font){ 18, C8UI_WEIGHT_NORMAL })
#define BOX_PAD 10

static void draw_box(cairo_t *cr, const char *family) {
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_rectangle(cr, BOX_X, BOX_Y, BOX_W, BOX_H);
	cairo_fill(cr);
	cairo_save(cr);
	cairo_rectangle(cr, BOX_X + 2, BOX_Y, BOX_W - 4, BOX_H);
	cairo_clip(cr);
	if (se.query[0]) {
		c8ui_textedit_draw(se.edit, cr, family, BOX_FONT,
			BOX_X + BOX_PAD - se.box_scroll, BOX_Y + 7, BOX_Y + 6, BOX_H - 12,
			shell.appearance.accent, true, true, 1);
	} else {
		cairo_set_source_rgb(cr, 0.45, 0.45, 0.45);
		text(cr, family, 18, C8UI_WEIGHT_NORMAL, "Search or run a command",
			BOX_X + BOX_PAD, BOX_Y + 7, BOX_W - 2 * BOX_PAD);
	}
	cairo_restore(cr);
}

static void draw_item(cairo_t *cr, struct c8ui_widget *w, struct item *item,
		double x, double y, double alpha) {
	const char *family = c8ui_widget_font(w);
	if (item->kind == ITEM_TILE) {
		/* Its face as on Start, without Start's marks on it */
		struct tile *tile = item->tile;
		bool focused = tile->focused, selected = tile->selected;
		bool pressed = tile->pressed;
		tile->focused = tile->selected = tile->pressed = false;
		tile->alpha = alpha;
		tile_draw(cr, w, tile, x, y);
		tile->focused = focused;
		tile->selected = selected;
		tile->pressed = pressed;
		return;
	}
	if (item->kind == ITEM_WIDGET || item->kind == ITEM_APP) {
		apps_draw_entry(cr, family, item->app, x, y, alpha);
		return;
	}
	double sx, sy;
	cairo_surface_get_device_scale(cairo_get_target(cr), &sx, &sy);
	if (item->face && (item->face_scale != sx ||
			item->face_gen != se.icon_gen)) {
		cairo_surface_destroy(item->face);
		item->face = NULL;
	}
	if (item->face == NULL) {
		item->face = cairo_surface_create_similar(cairo_get_target(cr),
			CAIRO_CONTENT_COLOR_ALPHA, ENTRY_W, ENTRY_H);
		item->face_scale = sx;
		item->face_gen = se.icon_gen;
		cairo_t *fcr = cairo_create(item->face);
		draw_row(fcr, family, item);
		cairo_destroy(fcr);
	}
	cairo_set_source_surface(cr, item->face, round(x), round(y));
	cairo_paint_with_alpha(cr, alpha);
}

void search_draw(cairo_t *cr, struct c8ui_widget *w, int64_t now) {
	const char *family = c8ui_widget_font(w);
	double sx, sy;
	cairo_surface_get_device_scale(cairo_get_target(cr), &sx, &sy);
	se.scale = sx;

	cairo_set_source_rgb(cr, 1, 1, 1);
	text(cr, family, 48, C8UI_WEIGHT_LIGHT, "Search", START_MARGIN_X, 36, 0);
	draw_box(cr, family);

	if (se.query[0] == '\0') {
		cairo_set_source_rgba(cr, 1, 1, 1, 0.7);
		text(cr, family, 20, C8UI_WEIGHT_LIGHT,
			"Type to search your tiles, apps, settings and files.",
			START_MARGIN_X, START_TILES_Y, 0);
		return;
	}

	/* Columns sweep in from the right as it opens, as tiles do on Start */
	int64_t since = now - se.opened_at;
	for (int s = 0; s < SECTION_COUNT; s++) {
		if (!se.section_shown[s]) {
			continue;
		}
		double x = se.section_x[s] - se.scroll;
		double p = ease_out((since - fmax(0, fmin(1, x / se.width)) * 200) /
			(OPEN_MS - 150.0));
		cairo_set_source_rgba(cr, 1, 1, 1, p);
		text(cr, family, 20, C8UI_WEIGHT_LIGHT, section_names[s],
			x + (1 - p) * 120, START_TILES_Y - 40, 0);
	}
	for (int i = 0; i < se.count; i++) {
		struct item *item = &se.items[i];
		double x = item->box.x - se.scroll;
		if (x + item->box.width < 0 || x > se.width) {
			continue;
		}
		double delay = fmax(0, fmin(1, x / se.width)) * 200;
		double p = ease_out((since - delay) / (OPEN_MS - 150.0));
		x += (1 - p) * 120;
		draw_item(cr, w, item, x, item->box.y, p);
		if (i == se.focus) {
			cairo_set_source_rgba(cr, 1, 1, 1, p);
			cairo_set_line_width(cr, 2);
			cairo_rectangle(cr, round(x) - 3, item->box.y - 3,
				item->box.width + 6, item->box.height + 6);
			cairo_stroke(cr);
		}
	}
}

bool search_tick(int64_t now, double dt) {
	if (!se.active) {
		return false;
	}
	bool animating = now - se.opened_at < OPEN_MS + 200;
	if (scroll_step(&se.fling, &se.scroll, &se.scroll_target, dt,
			se.content_width, se.width)) {
		animating = true;
	}
	return animating;
}

/* Opening things */

static struct rect on_screen(struct item *item) {
	struct rect r = item->box;
	r.x -= (int)se.scroll;
	return r;
}

static void close_start(void) {
	search_end();
	c8_shell_v1_set_start_visible(shell.proto, false);
}

static void activate(struct item *item) {
	char *cmd, *quoted;
	switch (item->kind) {
	case ITEM_TILE:
		start_activate_tile(item->tile, on_screen(item));
		break;
	case ITEM_APP:
		apps_activate_at(item->app, on_screen(item));
		break;
	case ITEM_WIDGET:
		/* Pinned: back to Start, where the new tile is */
		apps_activate_at(item->app, on_screen(item));
		search_end();
		break;
	case ITEM_SETTING:
		cmd = g_strdup_printf("c8-settings --page %s", item->setting->page);
		c8_shell_v1_launch(shell.proto, cmd);
		g_free(cmd);
		close_start();
		break;
	case ITEM_RUN:
		c8_shell_v1_launch(shell.proto, se.query);
		close_start();
		break;
	case ITEM_FILE:
		quoted = g_shell_quote(item->file.path);
		cmd = g_strdup_printf("xdg-open %s", quoted);
		c8_shell_v1_launch(shell.proto, cmd);
		g_free(cmd);
		g_free(quoted);
		close_start();
		break;
	}
}

/* Input */

static void set_focus(int index) {
	se.focus = index;
	if (index >= 0) {
		scroll_into_view(&se.items[index]);
	}
	start_redraw();
}

/* To the nearest one that way, preferring those straight across */
static void move_focus(int dx, int dy) {
	if (se.focus < 0) {
		if (se.count > 0) {
			set_focus(0);
		}
		return;
	}
	struct rect *from = &se.items[se.focus].box;
	int best = -1;
	double best_score = INFINITY;
	for (int i = 0; i < se.count; i++) {
		if (i == se.focus) {
			continue;
		}
		double score = focus_distance(from, &se.items[i].box, dx, dy);
		if (score < best_score) {
			best_score = score;
			best = i;
		}
	}
	if (best >= 0) {
		set_focus(best);
	}
}

static const char *box_family(void) {
	struct c8ui_widget *w = start_widget();
	return w ? c8ui_widget_font(w) : NULL;
}

static void box_moved(void) {
	se.query = c8ui_textedit_get(se.edit);
	c8ui_textedit_scroll_to_caret(se.edit, box_family(), BOX_FONT,
		BOX_W - 2 * BOX_PAD, &se.box_scroll);
	start_redraw();
}

static void changed(void) {
	box_moved();
	if (se.query[0] == '\0') {
		search_end(); // emptied: back to where it began
		return;
	}
	query();
}

static void pasted(struct c8ui_textedit *te, void *data) {
	if (se.active) {
		changed();
	}
}

/* Down past the end of a column goes on to the next one */
static void step_focus(int dir) {
	int to = se.focus < 0 ? 0 : se.focus + dir;
	if (to >= 0 && to < se.count) {
		set_focus(to);
	}
}

bool search_key(const struct c8ui_event *ev) {
	switch (ev->sym) {
	case XKB_KEY_Escape:
		search_end();
		return true;
	case XKB_KEY_Up:
	case XKB_KEY_Down: {
		int dir = ev->sym == XKB_KEY_Down ? 1 : -1, from = se.focus;
		move_focus(0, dir);
		if (se.focus == from) {
			step_focus(dir);
		}
		return true;
	}
	case XKB_KEY_Tab:
	case XKB_KEY_ISO_Left_Tab:
		step_focus(ev->mods & C8UI_MOD_SHIFT ? -1 : 1);
		return true;
	case XKB_KEY_Return:
	case XKB_KEY_KP_Enter:
		if (se.focus >= 0) {
			activate(&se.items[se.focus]);
		}
		return true;
	}
	struct c8ui_widget *w = start_widget();
	switch (c8ui_textedit_key(se.edit, w ? w->root : NULL, ev)) {
	case C8UI_EDIT_CHANGED:
		changed();
		return true;
	case C8UI_EDIT_MOVED:
		box_moved();
		return true;
	default:
		return false;
	}
}

static bool in_box(double x, double y) {
	struct rect box = { BOX_X, BOX_Y, BOX_W, BOX_H };
	return in_rect(&box, x, y);
}

static double box_text_x(double x) {
	return x - (BOX_X + BOX_PAD - se.box_scroll);
}

void search_motion(double x, double y) {
	if (se.box_drag) {
		c8ui_textedit_drag(se.edit, box_family(), BOX_FONT, box_text_x(x));
		box_moved();
	}
}

void search_release(void) {
	se.box_drag = false;
}

bool search_press(double x, double y, uint32_t button) {
	if (button != C8UI_BUTTON_LEFT) {
		return true;
	}
	if (in_box(x, y)) {
		c8ui_textedit_press(se.edit, box_family(), BOX_FONT, box_text_x(x),
			false);
		se.box_drag = true;
		box_moved();
		return true;
	}
	double px = x + se.scroll;
	for (int i = 0; i < se.count; i++) {
		struct rect hit = se.items[i].box;
		if (se.items[i].kind != ITEM_TILE) {
			hit.height = ENTRY_PITCH; // the gap below a row too
		}
		if (in_rect(&hit, px, y)) {
			se.focus = i;
			activate(&se.items[i]);
			return true;
		}
	}
	/* A click on nothing goes back */
	search_end();
	return true;
}

void search_scroll(double delta) {
	scroll_by(&se.fling, &se.scroll, &se.scroll_target, delta,
		se.content_width, se.width, false);
	start_animate();
}

void search_pan(double delta) {
	scroll_by(&se.fling, &se.scroll, &se.scroll_target, delta,
		se.content_width, se.width, true);
	start_animate();
}

void search_fling(double v) {
	se.fling = v;
	start_animate();
}

/* From the rest of the shell */

bool search_active(void) {
	return se.active;
}

void search_begin(const char *text) {
	if (!se.active) {
		se.active = true;
		c8ui_textedit_set(se.edit, "");
		se.box_scroll = 0;
		se.box_drag = false;
		se.scroll = se.scroll_target = 0;
		se.opened_at = now_ms();
		apps_rescan();
		files_refresh();
	}
	if (text) {
		c8ui_textedit_insert(se.edit, text);
	}
	box_moved();
	query(); // empty is fine here: Super+S opens it so
}

void search_end(void) {
	if (!se.active) {
		return;
	}
	se.active = false;
	c8ui_textedit_set(se.edit, "");
	se.query = c8ui_textedit_get(se.edit);
	se.box_drag = false;
	clear_items();
	se.focus = -1;
	se.fling = 0;
	start_animate();
}

void search_resize(int width, int height) {
	se.width = width;
	se.height = height;
	if (se.active) {
		layout();
	}
}

void search_restyle(void) {
	g_hash_table_remove_all(se.icons);
	if (se.active) {
		layout(); // the tile size may have changed
	}
}

/* A new file index: its hits replace the old ones, which are gone */
static void files_changed(void) {
	if (se.active) {
		int focus = se.focus;
		enum kind kind = focus >= 0 ? se.items[focus].kind : ITEM_RUN;
		query();
		/* Keep a choice made with the arrows unless it was a file */
		if (focus >= 0 && focus < se.count && kind != ITEM_FILE &&
				se.items[focus].kind == kind) {
			se.focus = focus;
		}
		start_redraw();
	}
}

void search_init(void) {
	se.icons = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
		named_free);
	files_init(files_changed);
	se.edit = c8ui_textedit_new(NULL);
	se.query = c8ui_textedit_get(se.edit);
	c8ui_textedit_on_change(se.edit, pasted, NULL);
}
