/*
 * All apps: every application from the freedesktop .desktop files,
 * alphabetised into letter groups that flow down and across in columns,
 * like Windows 8.1's apps view, and a second tab of live tile widgets
 * (.widget files) to pin. It sits below Start and slides up into place;
 * on a touchpad the page follows the fingers. start.c draws it and hands
 * it input while it is up.
 */
#define _GNU_SOURCE
#include <ctype.h>
#include <dirent.h>
#include <locale.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <unistd.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include "shell.h"

#define SLIDE_MS 350
#define TAB_MS 300 // the list sliding in after a tab change
#define TAB_SLIDE 120 // px it slides from
#define APPS_Y 152
#define COL_W 280
#define COL_GAP 24
#define ITEM_H 48
#define ITEM_SQUARE 40
#define ICON_SIZE 28
#define LETTER_H 48
#define BOTTOM_GAP 72
#define APPBAR_BUTTON_W 110

/* Touchpad scrolling slides the page with the fingers: this many units of
 * scroll travel take it all the way between Start and All apps. */
#define DRAG_TRAVEL 600.0
/* No stop event (some devices never send one): settle after this pause */
#define DRAG_IDLE_MS 150
/* Fingers resting this long before lifting means no momentum */
#define DRAG_REST_MS 60
/* The release spring's stiffness, per ms: critically damped, so it starts
 * at the fingers' speed and eases into place without bouncing */
#define SPRING_OMEGA 0.012

enum tab {
	TAB_APPS,
	TAB_WIDGETS,
	TAB_COUNT,
};

enum {
	BUTTON_PIN,
	BUTTON_CLEAR,
};

struct app {
	char *id, *name, *exec, *icon, *key, *comment, *provider;
	char *terms; // casefolded, for search: generic name, keywords, ...
	char group[64]; // the letter heading, or a widget's category
	bool widget;
	enum tile_size size; // widgets: the tile's size when pinned
	/* Its own colour (X-Cont8nuum-Color=, a widget's Color=): behind its
	 * icon here, and its tile's when pinned */
	bool has_color;
	uint32_t color;

	/* The icon, drawn for the screen's scale by the loader thread */
	struct c8ui_icon_request *icon_req;
	cairo_surface_t *icon_raster;
	int icon_px, icon_req_px;
	bool icon_missing;

	struct rect box;
	bool selected, focused;

	/* The entry, kept as an image while it doesn't change */
	cairo_surface_t *face;
	double face_scale;
	bool face_dirty, face_pinned;
};

struct letter {
	char text[64];
	int x, y;
};

static struct {
	struct app *lists[TAB_COUNT];
	int counts[TAB_COUNT];
	int64_t stamps[TAB_COUNT];
	bool scanned[TAB_COUNT];
	enum tab tab;
	struct app *apps; // the current tab's
	int count;

	struct letter *letters;
	int letter_count, letter_cap;

	int width, height, content_width;
	double scale;
	double scroll, scroll_target;
	double fling; // px/ms, coasting after a flick
	int focus, selected;
	struct rect tab_boxes[TAB_COUNT];
	int64_t tab_changed; // when the tab last changed, for its slide
	int tab_dir; // 1: the new tab came from the right
	struct {
		struct rect box;
		int id;
	} appbar[2];

	/* 0: Start, 1: All apps */
	bool active;
	double progress, anim_from, spring_velocity;
	int64_t anim_start;
	bool spring, dragging;
	double drag_velocity;
	int64_t drag_last;
	guint drag_timer;
} ap = { .focus = -1, .selected = -1, .scale = 1 };

/* Scanning */

static char locale_full[32], locale_lang[16];

static void init_locale(void) {
	static bool done;
	if (done) {
		return;
	}
	done = true;
	setlocale(LC_COLLATE, "");
	const char *l = getenv("LC_ALL");
	if (l == NULL || l[0] == '\0') {
		l = getenv("LC_MESSAGES");
	}
	if (l == NULL || l[0] == '\0') {
		l = getenv("LANG");
	}
	if (l == NULL) {
		return;
	}
	/* ll_CC.encoding@modifier -> ll_CC and ll */
	snprintf(locale_full, sizeof(locale_full), "%.*s", (int)strcspn(l, ".@"), l);
	snprintf(locale_lang, sizeof(locale_lang), "%.*s",
		(int)strcspn(locale_full, "_"), locale_full);
}

static bool in_list(const char *list, const char *item) {
	size_t len = strlen(item);
	for (const char *p = list; *p; ) {
		size_t n = strcspn(p, ";");
		if (n == len && strncasecmp(p, item, len) == 0) {
			return true;
		}
		p += n;
		if (*p == ';') {
			p++;
		}
	}
	return false;
}

static bool have_exec(const char *prog) {
	if (prog[0] == '/') {
		return access(prog, X_OK) == 0;
	}
	char *path = g_find_program_in_path(prog);
	g_free(path);
	return path != NULL;
}

/* A desktop entry's Exec as something sh -c can run: the string escapes
 * undone (\\ is one backslash, as the spec has it), the %f-style field
 * codes dropped, then split into its arguments the way GIO does and
 * each put back quoted for the shell where it needs it. Handing the
 * line to the shell as written let an argument with a quote in it
 * (Flatpak writes those as '\\'') end its quotes early and run the rest
 * as commands. NULL if it doesn't parse. */
static char *clean_exec(const char *value) {
	GString *plain = g_string_new(NULL);
	for (const char *p = value; *p; p++) {
		if (*p == '\\' && p[1]) {
			p++;
			switch (*p) {
			case 's':
			case 'n':
			case 't':
			case 'r':
				g_string_append_c(plain, ' ');
				break;
			case '\\':
				g_string_append_c(plain, '\\');
				break;
			default:
				g_string_append_c(plain, '\\');
				g_string_append_c(plain, *p);
				break;
			}
		} else if (*p == '%' && p[1]) {
			p++;
			if (*p == '%') {
				g_string_append_c(plain, '%');
			}
			/* Any other field code expands to nothing here */
		} else {
			g_string_append_c(plain, *p);
		}
	}
	char **argv = NULL;
	gboolean ok = g_shell_parse_argv(plain->str, NULL, &argv, NULL);
	g_string_free(plain, TRUE);
	if (!ok) {
		return NULL;
	}
	static const char safe[] = "abcdefghijklmnopqrstuvwxyz"
		"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_@%+=:,./-";
	GString *out = g_string_new(NULL);
	for (char **a = argv; *a; a++) {
		if (out->len) {
			g_string_append_c(out, ' ');
		}
		if ((*a)[0] && strspn(*a, safe) == strlen(*a)) {
			g_string_append(out, *a);
		} else {
			char *quoted = g_shell_quote(*a);
			g_string_append(out, quoted);
			g_free(quoted);
		}
	}
	g_strfreev(argv);
	/* The callers free() it */
	char *line = strdup(out->str);
	g_string_free(out, TRUE);
	return line;
}

static void app_free(struct app *app) {
	free(app->id);
	free(app->name);
	free(app->exec);
	free(app->icon);
	free(app->key);
	free(app->comment);
	free(app->provider);
	g_free(app->terms);
	c8ui_icon_request_cancel(app->icon_req);
	if (app->icon_raster) {
		cairo_surface_destroy(app->icon_raster);
	}
	if (app->face) {
		cairo_surface_destroy(app->face);
	}
}

/* key = value lines of one [section] of a desktop-entry-like file */
typedef void (*entry_fn)(const char *key, const char *value, void *data);

static bool read_entry(const char *path, const char *section, entry_fn fn,
		void *data) {
	FILE *f = fopen(path, "r");
	if (f == NULL) {
		return false;
	}
	bool in_entry = false;
	char *line = NULL;
	size_t cap = 0;
	while (getline(&line, &cap, f) > 0) {
		line[strcspn(line, "\r\n")] = '\0';
		if (line[0] == '[') {
			in_entry = strcmp(line, section) == 0;
			continue;
		}
		char *eq = strchr(line, '=');
		if (!in_entry || line[0] == '#' || eq == NULL) {
			continue;
		}
		char *kend = eq;
		while (kend > line && isspace((unsigned char)kend[-1])) {
			kend--;
		}
		*kend = '\0';
		char *value = eq + 1;
		while (isspace((unsigned char)*value)) {
			value++;
		}
		fn(line, value, data);
	}
	free(line);
	fclose(f);
	return true;
}

struct entry {
	char *name, *name_full, *name_lang;
	char *exec, *icon, *try_exec, *comment, *provider, *category, *size;
	char *generic, *keywords, *keywords_lang, *color;
	bool application, hidden, terminal;
	bool command; // a widget with Command=: c8-widget script feeds it
};

static void entry_free(struct entry *e) {
	free(e->name);
	free(e->name_full);
	free(e->name_lang);
	free(e->exec);
	free(e->icon);
	free(e->color);
	free(e->try_exec);
	free(e->comment);
	free(e->provider);
	free(e->category);
	free(e->size);
	free(e->generic);
	free(e->keywords);
	free(e->keywords_lang);
}

static void entry_key(const char *key, const char *value, void *data) {
	struct entry *e = data;
	char localized[64];
	if (strcmp(key, "Type") == 0) {
		e->application = strcmp(value, "Application") == 0;
	} else if (strcmp(key, "Name") == 0) {
		set_str(&e->name, value);
	} else if (strncmp(key, "Name[", 5) == 0) {
		if (locale_full[0] && (snprintf(localized, sizeof(localized),
				"Name[%s]", locale_full), strcmp(key, localized) == 0)) {
			set_str(&e->name_full, value);
		} else if (locale_lang[0] && (snprintf(localized, sizeof(localized),
				"Name[%s]", locale_lang), strcmp(key, localized) == 0)) {
			set_str(&e->name_lang, value);
		}
	} else if (strcmp(key, "Exec") == 0) {
		set_str(&e->exec, value);
	} else if (strcmp(key, "TryExec") == 0) {
		set_str(&e->try_exec, value);
	} else if (strcmp(key, "Icon") == 0) {
		set_str(&e->icon, value);
	} else if (strcmp(key, "Comment") == 0) {
		set_str(&e->comment, value);
	} else if (strcmp(key, "GenericName") == 0) {
		set_str(&e->generic, value);
	} else if (strcmp(key, "Keywords") == 0) {
		set_str(&e->keywords, value);
	} else if (locale_lang[0] && strncmp(key, "Keywords[", 9) == 0 &&
			strncmp(key + 9, locale_lang, strlen(locale_lang)) == 0) {
		set_str(&e->keywords_lang, value);
	} else if (strcmp(key, "X-Cont8nuum-Color") == 0 ||
			strcmp(key, "Color") == 0) {
		set_str(&e->color, value);
	} else if (strcmp(key, "Provider") == 0) {
		set_str(&e->provider, value);
	} else if (strcmp(key, "Command") == 0) {
		e->command = value[0] != '\0';
	} else if (strcmp(key, "Category") == 0) {
		set_str(&e->category, value);
	} else if (strcmp(key, "Size") == 0) {
		set_str(&e->size, value);
	} else if (strcmp(key, "Terminal") == 0) {
		e->terminal = strcmp(value, "true") == 0;
	} else if (strcmp(key, "NoDisplay") == 0 || strcmp(key, "Hidden") == 0) {
		e->hidden |= strcmp(value, "true") == 0;
	} else if (strcmp(key, "OnlyShowIn") == 0) {
		e->hidden |= !in_list(value, "cont8nuum");
	} else if (strcmp(key, "NotShowIn") == 0) {
		e->hidden |= in_list(value, "cont8nuum");
	}
}

static const char *shown_name(struct entry *e) {
	return e->name_full ? e->name_full : e->name_lang ? e->name_lang : e->name;
}

/* The program's name in a command line, past any path and @terminal */
static const char *cmd_base(const char *cmd) {
	if (strncmp(cmd, "@terminal -e ", 13) == 0) {
		cmd += 13;
	}
	size_t len = strcspn(cmd, " \t");
	const char *base = cmd;
	for (const char *p = cmd; p < cmd + len; p++) {
		if (*p == '/') {
			base = p + 1;
		}
	}
	return base;
}

static bool parse_desktop(const char *path, struct app *app) {
	struct entry e = { 0 };
	if (!read_entry(path, "[Desktop Entry]", entry_key, &e)) {
		return false;
	}
	const char *name = shown_name(&e);
	bool ok = e.application && !e.hidden && name && e.exec &&
		(e.try_exec == NULL || have_exec(e.try_exec));
	char *cmd = ok ? clean_exec(e.exec) : NULL;
	ok = ok && cmd && cmd[0];
	if (!ok) {
		free(cmd);
	}
	if (ok) {
		if (e.terminal) {
			if (asprintf(&app->exec, "@terminal -e %s", cmd) < 0) {
				app->exec = NULL;
			}
			free(cmd);
		} else {
			app->exec = cmd;
		}
		app->name = strdup(name);
		app->icon = e.icon ? strdup(e.icon) : NULL;
		app->has_color = e.color && c8ui_parse_color(e.color, &app->color);
		/* What else search finds it by; the program too, as people
		 * know some apps by their command */
		size_t plen = strcspn(cmd_base(app->exec), " \t");
		char *terms = g_strdup_printf("%s;%s;%s;%s;%.*s",
			e.generic ? e.generic : "", e.keywords ? e.keywords : "",
			e.keywords_lang ? e.keywords_lang : "",
			e.comment ? e.comment : "", (int)plen, cmd_base(app->exec));
		app->terms = g_utf8_casefold(terms, -1);
		g_free(terms);
	}
	entry_free(&e);
	return ok && app->exec;
}

/*
 * A live tile widget, from $XDG_DATA_DIRS/cont8nuum/widgets/ID.widget:
 *
 *   [Widget]
 *   Name=Processor
 *   Comment=Load, the busiest threads and clock speed
 *   Icon=cont8nuum-processor
 *   Category=System
 *   Provider=c8-widget processor %i   (feeds the tile; %i is the tile id)
 *   Exec=...                          (optional, run when the tile is clicked)
 *   Size=wide                         (small, medium, wide or large)
 *   TryExec=c8-widget
 *
 * Or, with no program of its own, in place of Provider:
 *
 *   Command=df -h --output=pcent / | tail -1   (through sh; what it prints
 *                                               is the tile)
 *   Interval=60                                (seconds between runs)
 *   Template=block                             (text unless said)
 *
 * which `c8-widget script` runs, reading those three from the file.
 */
static bool parse_widget(const char *path, const char *id, struct app *app) {
	struct entry e = { 0 };
	if (!read_entry(path, "[Widget]", entry_key, &e)) {
		return false;
	}
	const char *name = shown_name(&e);
	if (e.provider == NULL && e.command) {
		/* A command's output as the tile: c8-widget runs it from the file */
		char *quoted = g_shell_quote(path);
		e.provider = g_strdup_printf("c8-widget script --file %s %%i", quoted);
		g_free(quoted);
	}
	bool ok = !e.hidden && name && e.provider &&
		(e.try_exec == NULL || have_exec(e.try_exec));
	if (ok) {
		/* %i is the tile id; anything else is left alone */
		GString *provider = g_string_new(e.provider);
		g_string_replace(provider, "%i", id, 0);
		app->provider = g_string_free(provider, FALSE);
		app->name = strdup(name);
		app->exec = e.exec ? strdup(e.exec) : NULL;
		app->icon = e.icon ? strdup(e.icon) : NULL;
		app->has_color = e.color && c8ui_parse_color(e.color, &app->color);
		app->comment = e.comment ? strdup(e.comment) : NULL;
		app->terms = g_utf8_casefold(e.comment ? e.comment : "", -1);
		snprintf(app->group, sizeof(app->group), "%s",
			e.category ? e.category : "Other");
		app->size = TILE_MEDIUM;
		for (int i = 0; e.size && i <= TILE_LARGE; i++) {
			if (strcmp(e.size, tile_size_name(i)) == 0) {
				app->size = i;
			}
		}
		app->widget = true;
	}
	entry_free(&e);
	return ok;
}

struct scan {
	const char *ext; // .desktop or .widget
	struct app *apps;
	int count, cap;
	GHashTable *seen; // every id met, shown or not: the first one wins
};

static void scan_add(struct scan *scan, const struct app *app) {
	if (scan->count == scan->cap) {
		scan->cap = scan->cap ? scan->cap * 2 : 64;
		scan->apps = realloc(scan->apps, sizeof(*scan->apps) * scan->cap);
	}
	scan->apps[scan->count++] = *app;
}

/* The default apps (defaults.c), among the apps as "Web browser", "Mail"
 * and so on: each opens whatever is the default for it when used. A kind
 * that has a live tile widget running the same command (Calendar) is that
 * widget's tile: pinned from here it shows the widget's content too, and
 * both tabs see the one tile. */
static void scan_defaults(struct scan *scan) {
	for (int i = 0; i < defaults_count(); i++) {
		const struct c8_default_role *role = defaults_role(i);
		struct app app = { 0 };
		const struct app *widget = NULL;
		for (int j = 0; j < ap.counts[TAB_WIDGETS] && widget == NULL; j++) {
			const struct app *w = &ap.lists[TAB_WIDGETS][j];
			if (w->exec && strcmp(w->exec, role->exec) == 0) {
				widget = w;
			}
		}
		if (widget) {
			app.id = strdup(widget->id);
			app.provider = strdup(widget->provider);
			app.size = widget->size;
		} else if (asprintf(&app.id, "default-%s", role->id) < 0) {
			continue;
		}
		app.name = strdup(role->name);
		app.exec = strdup(role->exec);
		app.icon = strdup(role->icon);
		app.terms = g_utf8_casefold(role->terms, -1);
		app.key = g_utf8_casefold(app.name, -1);
		scan_add(scan, &app);
	}
}

static void scan_dir(struct scan *scan, const char *dir, const char *prefix,
		int depth) {
	DIR *d = opendir(dir);
	if (d == NULL) {
		return;
	}
	struct dirent *ent;
	while ((ent = readdir(d)) != NULL) {
		if (ent->d_name[0] == '.') {
			continue;
		}
		char path[2048], id[512];
		snprintf(path, sizeof(path), "%s/%s", dir, ent->d_name);
		snprintf(id, sizeof(id), "%s%s", prefix, ent->d_name);
		struct stat st;
		if (stat(path, &st) != 0) {
			continue;
		}
		if (S_ISDIR(st.st_mode)) {
			/* Subdirectories become part of the id: kde/foo -> kde-foo */
			if (depth < 3) {
				char sub[520];
				snprintf(sub, sizeof(sub), "%s-", id);
				scan_dir(scan, path, sub, depth + 1);
			}
			continue;
		}
		size_t len = strlen(id), ext = strlen(scan->ext);
		if (len <= ext || strcmp(id + len - ext, scan->ext) != 0) {
			continue;
		}
		id[len - ext] = '\0';
		if (g_hash_table_contains(scan->seen, id)) {
			continue;
		}
		g_hash_table_add(scan->seen, g_strdup(id));
		struct app app = { 0 };
		bool widget = strcmp(scan->ext, ".widget") == 0;
		if (!(widget ? parse_widget(path, id, &app) :
				parse_desktop(path, &app))) {
			app_free(&app);
			continue;
		}
		app.id = strdup(id);
		app.key = g_utf8_casefold(app.name, -1);
		scan_add(scan, &app);
	}
	closedir(d);
}

static const char *tab_dirs[] = {
	[TAB_APPS] = "applications",
	[TAB_WIDGETS] = "cont8nuum/widgets",
};

/* Calls fn for each data directory's `sub`, most important first */
static void for_each_data_dir(const char *sub,
		void (*fn)(const char *dir, void *data), void *data) {
	char *dir = g_build_filename(g_get_user_data_dir(), sub, NULL);
	fn(dir, data);
	g_free(dir);
	for (const char *const *d = g_get_system_data_dirs(); *d; d++) {
		dir = g_build_filename(*d, sub, NULL);
		fn(dir, data);
		g_free(dir);
	}
	/* Our own widgets, even when the prefix isn't in XDG_DATA_DIRS */
	dir = g_build_filename(C8_DATADIR, sub, NULL);
	fn(dir, data);
	g_free(dir);
}

static void scan_one(const char *dir, void *data) {
	scan_dir(data, dir, "", 0);
}

static void stamp_one(const char *dir, void *data) {
	struct stat st;
	if (stat(dir, &st) == 0) {
		*(int64_t *)data = *(int64_t *)data * 31 + st.st_mtim.tv_sec * 1000 +
			st.st_mtim.tv_nsec / 1000000;
	}
}

static int app_cmp(const void *a, const void *b) {
	const struct app *x = a, *y = b;
	/* Widgets are grouped by category; apps' groups follow from the name */
	int r = x->widget ? strcoll(x->group, y->group) : 0;
	if (r == 0) {
		r = strcoll(x->key, y->key);
	}
	return r ? r : strcmp(x->name, y->name);
}

static void app_letter(const struct app *app, char *out, size_t len) {
	unsigned char c = (unsigned char)app->name[0];
	if (c < 0x80) {
		snprintf(out, len, "%c", isalpha(c) ? toupper(c) : '#');
		return;
	}
	/* Non-ASCII: the whole first character, in capitals */
	gunichar u = g_unichar_toupper(g_utf8_get_char(app->name));
	int n = g_unichar_to_utf8(u, out);
	out[n] = '\0';
}

static void rescan(enum tab tab) {
	if (tab == TAB_APPS && !ap.scanned[TAB_WIDGETS]) {
		rescan(TAB_WIDGETS); // the default apps look for their widgets
	}
	int64_t stamp = 0;
	for_each_data_dir(tab_dirs[tab], stamp_one, &stamp);
	if (ap.scanned[tab] && stamp == ap.stamps[tab]) {
		return;
	}
	init_locale();
	if (ap.scanned[tab]) {
		/* Something was installed or removed: its icons may have too */
		c8ui_icon_cache_reset();
	}
	struct scan scan = {
		.ext = tab == TAB_WIDGETS ? ".widget" : ".desktop",
		.seen = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL),
	};
	for_each_data_dir(tab_dirs[tab], scan_one, &scan);
	if (tab == TAB_APPS) {
		scan_defaults(&scan);
	}
	g_hash_table_destroy(scan.seen);
	qsort(scan.apps, scan.count, sizeof(*scan.apps), app_cmp);

	for (int i = 0; i < ap.counts[tab]; i++) {
		app_free(&ap.lists[tab][i]);
	}
	free(ap.lists[tab]);
	ap.lists[tab] = scan.apps;
	ap.counts[tab] = scan.count;
	ap.stamps[tab] = stamp;
	ap.scanned[tab] = true;
	if (ap.tab == tab) {
		ap.apps = scan.apps;
		ap.count = scan.count;
		ap.focus = ap.selected = -1;
	}
	for (int i = 0; i < scan.count; i++) {
		struct app *app = &scan.apps[i];
		if (!app->widget) {
			app_letter(app, app->group, sizeof(app->group));
		}
		app->face_dirty = true;
	}
}

/* Layout */

static void clamp_scroll(void) {
	scroll_clamp(&ap.scroll_target, ap.content_width, ap.width);
}

static void layout(void) {
	ap.letter_count = 0;
	int bottom = ap.height - BOTTOM_GAP;
	int x = START_MARGIN_X, y = APPS_Y;
	const char *letter = "";
	for (int i = 0; i < ap.count; i++) {
		struct app *app = &ap.apps[i];
		bool new_letter = strcmp(app->group, letter) != 0;
		int need = (new_letter ? LETTER_H : 0) + ITEM_H;
		if (y + need > bottom && y > APPS_Y) {
			x += COL_W + COL_GAP;
			y = APPS_Y;
		}
		if (new_letter) {
			letter = app->group;
			if (ap.letter_count == ap.letter_cap) {
				ap.letter_cap = ap.letter_cap ? ap.letter_cap * 2 : 32;
				ap.letters = realloc(ap.letters,
					sizeof(*ap.letters) * ap.letter_cap);
			}
			struct letter *l = &ap.letters[ap.letter_count++];
			snprintf(l->text, sizeof(l->text), "%s", letter);
			l->x = x;
			l->y = y;
			y += LETTER_H;
		}
		app->box = (struct rect){ x, y, ENTRY_W, ENTRY_H };
		y += ITEM_H;
	}
	ap.content_width = x + COL_W + START_MARGIN_X;
	clamp_scroll();
	start_animate();
}

static void ensure_scanned(void) {
	if (!ap.scanned[ap.tab]) {
		rescan(ap.tab);
		layout();
	}
}

/* Drawing */

/* The tile an entry is pinned as: by id, or (an app) one that runs the
 * same command, as the shipped Terminal tile does */
static struct tile *app_tile(struct app *app) {
	struct tile *tile = tile_find(app->id);
	if (tile == NULL && !app->widget && app->exec) {
		tile = tile_find_exec(app->exec);
	}
	return tile;
}

static int icon_px(void) {
	return (int)ceil(ICON_SIZE * ap.scale);
}

static void icon_loaded(void *data, cairo_surface_t *image) {
	struct app *app = data;
	app->icon_req = NULL;
	if (image) {
		if (app->icon_raster) {
			cairo_surface_destroy(app->icon_raster);
		}
		app->icon_raster = image;
		app->icon_px = app->icon_req_px;
	} else {
		app->icon_missing = true;
	}
	app->face_dirty = true;
	start_redraw();
}

/* Asks for the entry's icon if it doesn't have one at this size yet */
static void want_icon(struct app *app) {
	int px = icon_px();
	if (app->icon_missing || app->icon_px == px ||
			(app->icon_req && app->icon_req_px == px)) {
		return;
	}
	c8ui_icon_request_cancel(app->icon_req);
	app->icon_req_px = px;
	app->icon_req = c8ui_icon_request(shell.appearance.icon_theme, app->icon,
		px, true, icon_loaded, app);
}

static void draw_glyph(cairo_t *cr, const char *family, struct app *app,
		double cx, double cy, double size) {
	char glyph[8];
	app_letter(app, glyph, sizeof(glyph));
	if (strcmp(glyph, "#") == 0) {
		snprintf(glyph, sizeof(glyph), "%.1s", app->name);
	}
	struct c8ui_font font = { size * 0.8, C8UI_WEIGHT_LIGHT };
	double tw, th;
	c8ui_text_size(family, font, glyph, 0, 0, &tw, &th);
	cairo_set_source_rgb(cr, 1, 1, 1);
	c8ui_text_draw(cr, family, font, glyph, cx - tw / 2, cy - th / 2, 0, 0);
}

static void draw_item(cairo_t *cr, const char *family, struct app *app,
		int w, int h, bool pinned) {
	uint32_t accent = shell.appearance.accent;
	if (app->selected) {
		c8ui_set_source(cr, accent, 0.55);
		cairo_paint(cr);
	}
	c8ui_set_source(cr, app->has_color ? app->color : accent, 1);
	cairo_rectangle(cr, 0, 0, ITEM_SQUARE, ITEM_SQUARE);
	cairo_fill(cr);
	if (app->icon_raster) {
		/* Made for the device pixels; drawn back at logical size */
		int iw = cairo_image_surface_get_width(app->icon_raster);
		int ih = cairo_image_surface_get_height(app->icon_raster);
		double s = (double)ICON_SIZE / app->icon_px;
		cairo_save(cr);
		cairo_translate(cr, (ITEM_SQUARE - iw * s) / 2,
			(ITEM_SQUARE - ih * s) / 2);
		cairo_scale(cr, s, s);
		cairo_set_source_surface(cr, app->icon_raster, 0, 0);
		cairo_paint(cr);
		cairo_restore(cr);
	} else if (app->icon_missing) {
		draw_glyph(cr, family, app, ITEM_SQUARE / 2.0, ITEM_SQUARE / 2.0,
			ICON_SIZE);
	}
	/* Otherwise it is still loading: the plain square until it arrives */

	struct c8ui_font name = { 15, C8UI_WEIGHT_NORMAL };
	cairo_set_source_rgb(cr, 1, 1, 1);
	if (app->comment) {
		c8ui_text_draw(cr, family, name, app->name, ITEM_SQUARE + 12, 0,
			w - ITEM_SQUARE - 16, 1);
		cairo_set_source_rgba(cr, 1, 1, 1, 0.6);
		c8ui_text_draw(cr, family, (struct c8ui_font){ 12,
			C8UI_WEIGHT_NORMAL }, app->comment, ITEM_SQUARE + 12, 21,
			w - ITEM_SQUARE - 16, 1);
	} else {
		c8ui_text_draw(cr, family, name, app->name, ITEM_SQUARE + 12, 9,
			w - ITEM_SQUARE - 16, 1);
	}
	if (pinned) {
		/* Already on Start: a short bar along the bottom */
		cairo_set_source_rgba(cr, 1, 1, 1, 0.6);
		cairo_rectangle(cr, ITEM_SQUARE + 12, h - 3, 16, 2);
		cairo_fill(cr);
	}
	if (app->focused) {
		cairo_set_source_rgb(cr, 1, 1, 1);
		cairo_set_line_width(cr, 2);
		cairo_rectangle(cr, 1, 1, w - 2, h - 2);
		cairo_stroke(cr);
	}
}

static void draw_one(cairo_t *cr, const char *family, struct app *app,
		double x, double y, double alpha) {
	int w = ENTRY_W, h = ENTRY_H;
	bool pinned = app_tile(app) != NULL;
	want_icon(app);
	cairo_surface_t *target = cairo_get_target(cr);
	if (app->face == NULL || app->face_scale != ap.scale) {
		if (app->face) {
			cairo_surface_destroy(app->face);
		}
		app->face = cairo_surface_create_similar(target,
			CAIRO_CONTENT_COLOR_ALPHA, w, h);
		app->face_scale = ap.scale;
		app->face_dirty = true;
	}
	if (app->face_dirty || app->face_pinned != pinned) {
		cairo_t *fcr = cairo_create(app->face);
		cairo_set_operator(fcr, CAIRO_OPERATOR_CLEAR);
		cairo_paint(fcr);
		cairo_set_operator(fcr, CAIRO_OPERATOR_OVER);
		draw_item(fcr, family, app, w, h, pinned);
		cairo_destroy(fcr);
		app->face_dirty = false;
		app->face_pinned = pinned;
	}
	cairo_set_source_surface(cr, app->face, round(x), round(y));
	cairo_paint_with_alpha(cr, alpha);
}

void apps_draw_entry(cairo_t *cr, const char *family, struct app *app,
		double x, double y, double alpha) {
	double sx, sy;
	cairo_surface_get_device_scale(cairo_get_target(cr), &sx, &sy);
	ap.scale = sx;
	draw_one(cr, family, app, x, y, alpha);
}

static const char *tab_names[] = {
	[TAB_APPS] = "Apps",
	[TAB_WIDGETS] = "Live tiles",
};

/* The tabs, as headings: the current one bright, the other dimmed */
static void draw_header(cairo_t *cr, const char *family) {
	struct c8ui_font font = { 48, C8UI_WEIGHT_LIGHT };
	int x = START_MARGIN_X;
	for (int i = 0; i < TAB_COUNT; i++) {
		double tw, th;
		c8ui_text_size(family, font, tab_names[i], 0, 0, &tw, &th);
		cairo_set_source_rgba(cr, 1, 1, 1, i == (int)ap.tab ? 1 : 0.4);
		c8ui_text_draw(cr, family, font, tab_names[i], x, 36, 0, 0);
		ap.tab_boxes[i] = (struct rect){ x, 30, (int)tw, 70 };
		x += (int)tw + 40;
	}
}

/* The round arrow button: up, back to Start */
void apps_draw_arrow(cairo_t *cr, double cx, double cy, bool up) {
	double d = up ? -1 : 1;
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_set_line_width(cr, 2);
	cairo_arc(cr, cx, cy, 15, 0, 2 * M_PI);
	cairo_stroke(cr);
	cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND);
	cairo_move_to(cr, cx - 6, cy - 3 * d);
	cairo_line_to(cr, cx, cy + 3 * d);
	cairo_line_to(cr, cx + 6, cy - 3 * d);
	cairo_stroke(cr);
	cairo_set_line_cap(cr, CAIRO_LINE_CAP_BUTT);
}

static void draw_appbar(cairo_t *cr, const char *family) {
	double top = ap.height - APPBAR_HEIGHT;
	c8ui_set_source(cr, 0x121212, 0.94);
	cairo_rectangle(cr, 0, top, ap.width, APPBAR_HEIGHT);
	cairo_fill(cr);
	bool pinned = ap.selected >= 0 && app_tile(&ap.apps[ap.selected]);
	for (int i = 0; i < 2; i++) {
		struct rect *b = &ap.appbar[i].box;
		double cx = b->x + b->width / 2.0, cy = top + 30;
		cairo_set_source_rgb(cr, 1, 1, 1);
		cairo_set_line_width(cr, 2);
		cairo_arc(cr, cx, cy, 19, 0, 2 * M_PI);
		cairo_stroke(cr);
		const char *label;
		if (ap.appbar[i].id == BUTTON_PIN) {
			/* A push pin, struck through when unpinning */
			cairo_arc(cr, cx, cy - 5, 5, 0, 2 * M_PI);
			cairo_fill(cr);
			cairo_move_to(cr, cx, cy);
			cairo_line_to(cr, cx, cy + 10);
			if (pinned) {
				cairo_move_to(cr, cx - 9, cy + 9);
				cairo_line_to(cr, cx + 9, cy - 9);
			}
			cairo_stroke(cr);
			label = pinned ? "Unpin from Start" : "Pin to Start";
		} else {
			cairo_move_to(cr, cx - 8, cy);
			cairo_line_to(cr, cx + 8, cy);
			cairo_stroke(cr);
			label = "Clear selection";
		}
		struct c8ui_font font = { 12, C8UI_WEIGHT_NORMAL };
		double tw, th;
		c8ui_text_size(family, font, label, 0, 0, &tw, &th);
		double max = b->width - 4;
		c8ui_text_draw(cr, family, font, label, cx - fmin(tw, max) / 2,
			top + 56, max, 1);
	}
}

void apps_draw(cairo_t *cr, struct c8ui_widget *w) {
	const char *family = c8ui_widget_font(w);
	double sx, sy;
	cairo_surface_get_device_scale(cairo_get_target(cr), &sx, &sy);
	ap.scale = sx; // icons and faces are redone at a new size
	ensure_scanned();
	draw_header(cr, family);

	/* A new tab's list slides in from the side it was on */
	double p = ease_out((double)(now_ms() - ap.tab_changed) / TAB_MS);
	double slide = (1 - p) * TAB_SLIDE * ap.tab_dir;
	cairo_save(cr);
	cairo_translate(cr, round(slide), 0);

	/* Only what's on screen */
	double lo = ap.scroll - COL_W - slide, hi = ap.scroll + ap.width - slide;
	struct c8ui_font lf = { 26, C8UI_WEIGHT_LIGHT };
	for (int i = 0; i < ap.letter_count; i++) {
		struct letter *l = &ap.letters[i];
		if (l->x < lo || l->x > hi) {
			continue;
		}
		double x = l->x - ap.scroll;
		cairo_set_source_rgba(cr, 1, 1, 1, p);
		c8ui_text_draw(cr, family, lf, l->text, x + 2, l->y, COL_W - 8, 1);
		cairo_set_source_rgba(cr, 1, 1, 1, 0.35 * p);
		cairo_rectangle(cr, x, l->y + LETTER_H - 13, COL_W - 8, 1);
		cairo_fill(cr);
	}
	for (int i = 0; i < ap.count; i++) {
		struct app *app = &ap.apps[i];
		if (app->box.x >= lo && app->box.x <= hi) {
			draw_one(cr, family, app, app->box.x - ap.scroll, app->box.y,
				p);
		}
	}
	if (ap.count == 0) {
		cairo_set_source_rgba(cr, 1, 1, 1, 0.7 * p);
		c8ui_text_draw(cr, family, (struct c8ui_font){ 20,
			C8UI_WEIGHT_LIGHT }, ap.tab == TAB_WIDGETS ?
			"No live tile widgets are installed." :
			"No apps found.", START_MARGIN_X, APPS_Y, 0, 0);
	}
	cairo_restore(cr);
	if (ap.selected >= 0) {
		draw_appbar(cr, family);
	} else {
		apps_draw_arrow(cr, START_MARGIN_X + 16, ap.height - 32, true);
	}
}

/* Show and hide */

static void clear_marks(void) {
	if (ap.focus >= 0) {
		ap.apps[ap.focus].focused = false;
		ap.apps[ap.focus].face_dirty = true;
	}
	if (ap.selected >= 0) {
		ap.apps[ap.selected].selected = false;
		ap.apps[ap.selected].face_dirty = true;
	}
	ap.focus = ap.selected = -1;
}

static void set_tab(enum tab tab) {
	if (tab != ap.tab) {
		ap.tab_dir = tab > ap.tab ? 1 : -1;
		ap.tab_changed = now_ms();
		start_animate();
	}
	clear_marks();
	ap.tab = tab;
	rescan(tab);
	ap.apps = ap.lists[tab];
	ap.count = ap.counts[tab];
	ap.scroll = ap.scroll_target = 0;
	layout();
}

bool apps_active(void) {
	return ap.active;
}

bool apps_swipe(int dir) {
	int tab = (int)ap.tab + dir;
	if (!ap.active || tab < 0 || tab >= TAB_COUNT) {
		return false;
	}
	set_tab(tab);
	return true;
}

double apps_progress(void) {
	return ap.progress;
}

bool apps_dragging(void) {
	return ap.dragging;
}

void apps_show(bool show) {
	if (ap.active == show) {
		return;
	}
	ap.active = show;
	ap.spring = false;
	ap.anim_from = ap.progress;
	/* Timed from the first frame, so however long getting the list ready
	 * takes, the slide still plays in full */
	ap.anim_start = 0;
	if (show) {
		set_tab(ap.tab);
	} else {
		clear_marks();
	}
	start_animate();
}

/* Start has been hidden a while: the rows are drawn again when wanted */
void apps_rest(void) {
	for (int t = 0; t < TAB_COUNT; t++) {
		for (int i = 0; ap.lists[t] && i < ap.counts[t]; i++) {
			g_clear_pointer(&ap.lists[t][i].face, cairo_surface_destroy);
		}
	}
}

void apps_reset(void) {
	ap.dragging = false;
	ap.spring = false;
	g_clear_handle_id(&ap.drag_timer, g_source_remove);
	apps_show(false);
	ap.progress = 0;
	ap.anim_start = 0;
}

static gboolean drag_timeout(gpointer data) {
	ap.drag_timer = 0;
	apps_drag_end();
	return G_SOURCE_REMOVE;
}

static void drag(double delta, bool idle_timer);

void apps_drag(double delta) {
	drag(delta, true);
}

void apps_drag_finger(double delta) {
	drag(delta, false);
}

static void drag(double delta, bool idle_timer) {
	int64_t now = now_ms();
	if (!ap.dragging) {
		if (!ap.active && ap.progress == 0) {
			if (delta <= 0) {
				return; // nothing above Start
			}
			start_open_apps(); // Start's half: closes menus, search
			apps_show(true);
		} else if (delta >= 0 && ap.progress >= 1 && !ap.spring) {
			return; // nothing below All apps
		}
		/* Catching the page mid-slide keeps its speed going */
		ap.dragging = true;
		ap.spring = false;
		ap.drag_velocity = 0;
		ap.drag_last = now;
	}
	double step = delta / DRAG_TRAVEL;
	ap.progress = fmin(fmax(ap.progress + step, 0), 1);
	/* Speed over the last few events; a pause starts it afresh */
	int64_t dt = now - ap.drag_last;
	double v = step / (dt < 4 ? 4 : dt);
	ap.drag_velocity = dt > DRAG_REST_MS ? v :
		0.6 * ap.drag_velocity + 0.4 * v;
	ap.drag_last = now;
	g_clear_handle_id(&ap.drag_timer, g_source_remove);
	if (idle_timer) {
		ap.drag_timer = g_timeout_add(DRAG_IDLE_MS, drag_timeout, NULL);
	}
	start_animate();
}

void apps_drag_end(void) {
	if (!ap.dragging) {
		return;
	}
	ap.dragging = false;
	g_clear_handle_id(&ap.drag_timer, g_source_remove);
	double v = ap.drag_velocity;
	if (now_ms() - ap.drag_last > DRAG_REST_MS) {
		v = 0;
	}
	/* Land where the momentum would carry it: the spring's coast is
	 * v / omega */
	bool show = ap.progress + v / SPRING_OMEGA > 0.5;
	if (show != ap.active) {
		apps_show(show);
	}
	ap.spring = true;
	ap.spring_velocity = v;
	ap.anim_from = ap.progress;
	ap.anim_start = 0;
	start_animate();
}

bool apps_tick(int64_t now, double dt) {
	bool animating = false;
	double target = ap.active ? 1 : 0;
	if (!ap.dragging && ap.progress != target && ap.anim_start == 0) {
		ap.anim_start = now;
	}
	if (ap.dragging) {
		/* The fingers set progress */
	} else if (ap.progress != target && ap.spring) {
		/* Critically damped: x(t) = (x0 + (v0 + w x0) t) e^(-w t),
		 * relative to the target */
		double t = (double)(now - ap.anim_start);
		double w = SPRING_OMEGA;
		double x0 = ap.anim_from - target;
		double x = (x0 + (ap.spring_velocity + w * x0) * t) * exp(-w * t);
		/* Done once it is close, or would pass the end it is heading to */
		if (fabs(x) < 0.001 || x * x0 < 0 || (x0 == 0 && t > 0)) {
			ap.progress = target;
			ap.spring = false;
		} else {
			ap.progress = target + x;
			if (ap.progress < 0 || ap.progress > 1) {
				ap.progress = target;
				ap.spring = false;
			} else {
				animating = true;
			}
		}
	} else if (ap.progress != target) {
		double t = (double)(now - ap.anim_start) / SLIDE_MS;
		if (t >= 1) {
			ap.progress = target;
		} else {
			ap.progress = ap.anim_from +
				(target - ap.anim_from) * ease_in_out(t);
			animating = true;
		}
	}
	if (ap.progress == 0) {
		return animating;
	}
	if (now - ap.tab_changed < TAB_MS) {
		animating = true;
	}
	if (scroll_step(&ap.fling, &ap.scroll, &ap.scroll_target, dt,
			ap.content_width, ap.width)) {
		animating = true;
	}
	return animating;
}

void apps_resize(int width, int height) {
	ap.width = width;
	ap.height = height;
	ap.appbar[0].box = (struct rect){ 40, 0, APPBAR_BUTTON_W, APPBAR_HEIGHT };
	ap.appbar[0].id = BUTTON_PIN;
	ap.appbar[1].box = (struct rect){ width - 150, 0, APPBAR_BUTTON_W,
		APPBAR_HEIGHT };
	ap.appbar[1].id = BUTTON_CLEAR;
	if (ap.scanned[ap.tab]) {
		layout();
	}
}

void apps_restyle(void) {
	for (int t = 0; t < TAB_COUNT; t++) {
		for (int i = 0; i < ap.counts[t]; i++) {
			struct app *app = &ap.lists[t][i];
			app->face_dirty = true;
			/* The icon theme may have changed */
			c8ui_icon_request_cancel(app->icon_req);
			app->icon_req = NULL;
			app->icon_px = 0;
			app->icon_missing = false;
		}
	}
}

/* Actions */

static void launch_at(struct app *app, struct rect from) {
	from.width = from.height = ITEM_SQUARE;
	splash_show(from, app->has_color ? app->color : shell.appearance.accent,
		app->icon);
	shell_launch(app->exec);
}

/* Where the entry is on the screen now, for the splash to grow from */
static struct rect app_on_screen(struct app *app) {
	double y = (1 - ap.progress) * ap.height;
	return (struct rect){ app->box.x - (int)ap.scroll, app->box.y + (int)y,
		0, 0 };
}

static void select_app(int index) {
	if (ap.selected >= 0) {
		ap.apps[ap.selected].selected = false;
		ap.apps[ap.selected].face_dirty = true;
	}
	ap.selected = index == ap.selected ? -1 : index;
	if (ap.selected >= 0) {
		ap.apps[ap.selected].selected = true;
		ap.apps[ap.selected].face_dirty = true;
	}
	start_redraw();
}

static void toggle_pin(struct app *app) {
	struct tile *tile = app_tile(app);
	if (tile) {
		start_unpin(tile);
		return;
	}
	struct group *group;
	if (wl_list_empty(&tile_groups)) {
		group = group_create("");
	} else {
		group = wl_container_of(tile_groups.prev, group, link);
	}
	tile = tile_create(group, app->id);
	set_str(&tile->name, app->name);
	set_str(&tile->exec, app->exec);
	set_str(&tile->icon, app->icon);
	tile->has_color = app->has_color;
	tile->color = app->color;
	if (app->provider) {
		set_str(&tile->provider, app->provider);
		tile->size = app->size;
	}
	start_pinned(tile);
	if (tile->provider) {
		c8_shell_v1_launch(shell.proto, tile->provider);
	}
}

/* Clicking an app launches it; clicking a widget pins it (or unpins it)
 * and, once pinned, goes back to Start to show the new tile */
static void activate(struct app *app) {
	apps_activate_at(app, app_on_screen(app));
}

/* Input */

static int app_at(double x, double y) {
	double ax = x + ap.scroll;
	for (int i = 0; i < ap.count; i++) {
		struct app *app = &ap.apps[i];
		/* Items are hit across the whole row, including the gap below */
		struct rect row = app->box;
		row.height = ITEM_H;
		if (in_rect(&row, ax, y)) {
			return i;
		}
	}
	return -1;
}

bool apps_press(double x, double y, uint32_t button) {
	if (ap.selected >= 0 && y >= ap.height - APPBAR_HEIGHT) {
		double ay = y - (ap.height - APPBAR_HEIGHT);
		for (int i = 0; i < 2; i++) {
			if (in_rect(&ap.appbar[i].box, x, ay)) {
				if (ap.appbar[i].id == BUTTON_PIN) {
					struct app *app = &ap.apps[ap.selected];
					toggle_pin(app);
					app->face_dirty = true;
				}
				select_app(ap.selected);
			}
		}
		return true;
	}
	struct rect back = { START_MARGIN_X - 8, ap.height - 56, 48, 48 };
	if (button == C8UI_BUTTON_LEFT && in_rect(&back, x, y)) {
		apps_show(false);
		return true;
	}
	for (int i = 0; i < TAB_COUNT; i++) {
		if (button == C8UI_BUTTON_LEFT && in_rect(&ap.tab_boxes[i], x, y)) {
			if (i != (int)ap.tab) {
				set_tab(i);
			}
			return true;
		}
	}
	int index = app_at(x, y);
	if (button == C8UI_BUTTON_RIGHT) {
		if (index >= 0) {
			select_app(index);
		} else if (ap.selected >= 0) {
			select_app(ap.selected);
		}
		return true;
	}
	if (button != C8UI_BUTTON_LEFT) {
		return false;
	}
	if (index < 0) {
		if (ap.selected >= 0) {
			select_app(ap.selected);
		}
		return true;
	}
	if (ap.selected >= 0) {
		/* With a selection, clicks change the selection, as on Start */
		select_app(index);
		return true;
	}
	activate(&ap.apps[index]);
	return true;
}

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

void apps_fling(double v) {
	ap.fling = v;
	start_animate();
}

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

static void set_focus(int index) {
	if (ap.focus == index) {
		return;
	}
	if (ap.focus >= 0) {
		ap.apps[ap.focus].focused = false;
		ap.apps[ap.focus].face_dirty = true;
	}
	ap.focus = index;
	if (index < 0) {
		start_redraw();
		return;
	}
	struct app *app = &ap.apps[index];
	app->focused = true;
	app->face_dirty = true;
	scroll_reveal(&ap.scroll_target, &app->box, ap.content_width, ap.width);
	start_animate();
}

static void move_focus(int dx, int dy) {
	if (ap.focus < 0) {
		set_focus(ap.count > 0 ? 0 : -1);
		return;
	}
	if (dy != 0) {
		/* Up and down walk the list, flowing between columns */
		int i = ap.focus + dy;
		if (i >= 0 && i < ap.count) {
			set_focus(i);
		}
		return;
	}
	struct rect *from = &ap.apps[ap.focus].box;
	int best = -1;
	double best_score = INFINITY;
	for (int i = 0; i < ap.count; i++) {
		struct app *app = &ap.apps[i];
		if (app->box.x == from->x ||
				(app->box.x - from->x) * dx < 0) {
			continue;
		}
		double score = abs(app->box.x - from->x) * 4 +
			abs(app->box.y - from->y);
		if (score < best_score) {
			best_score = score;
			best = i;
		}
	}
	if (best >= 0) {
		set_focus(best);
	}
}

/* Typing isn't taken here: Start turns it into a search */
bool apps_key(const struct c8ui_event *ev) {
	int dx, dy;
	if (arrow_dir(ev->sym, &dx, &dy)) {
		move_focus(dx, dy);
		return true;
	}
	switch (ev->sym) {
	case XKB_KEY_Escape:
		if (ap.selected >= 0) {
			select_app(ap.selected);
		} else {
			apps_show(false);
		}
		return true;
	case XKB_KEY_Home:
		ap.scroll_target = 0;
		start_animate();
		return true;
	case XKB_KEY_End:
		ap.scroll_target = ap.content_width;
		clamp_scroll();
		start_animate();
		return true;
	case XKB_KEY_Return:
	case XKB_KEY_KP_Enter:
		if (ap.focus >= 0) {
			activate(&ap.apps[ap.focus]);
		}
		return true;
	case XKB_KEY_Tab:
	case XKB_KEY_ISO_Left_Tab:
		set_tab((ap.tab + 1) % TAB_COUNT);
		return true;
	case XKB_KEY_space:
		if (ap.focus >= 0) {
			select_app(ap.focus);
			return true;
		}
		break;
	}
	return false;
}

/* Search's side */

void apps_rescan(void) {
	for (int t = TAB_COUNT - 1; t >= 0; t--) {
		rescan(t); // keeps ap.apps the open tab's list
	}
	layout();
}

struct scored {
	struct app *app;
	int score;
};

static int scored_cmp(const void *a, const void *b) {
	const struct scored *x = a, *y = b;
	if (x->score != y->score) {
		return y->score - x->score;
	}
	/* The lists are alphabetical: keep that among equals */
	return x->app < y->app ? -1 : x->app > y->app;
}

/* By the name, fuzzily; generic name, keywords, comment and the command
 * by word starts and below those, so "browser" finds Firefox but below an
 * app called Browser */
int apps_search(const char *query, bool widgets, struct app **out, int max) {
	enum tab tab = widgets ? TAB_WIDGETS : TAB_APPS;
	struct app *list = ap.lists[tab];
	int count = ap.counts[tab], n = 0;
	struct scored *hits = g_new(struct scored, count ? count : 1);
	for (int i = 0; i < count; i++) {
		struct app *app = &list[i];
		if (widgets && tile_find(app->id)) {
			continue; // already on Start, where its tile is found
		}
		int score = search_fuzzy(app->key, app->name, query);
		if (score == 0 && search_score(app->terms, query) >= 2) {
			/* Keywords and comments only by whole words' starts, and
			 * below any app found by its name */
			score = 1;
		}
		if (score > 0) {
			hits[n++] = (struct scored){ app, score };
		}
	}
	qsort(hits, n, sizeof(*hits), scored_cmp);
	n = n < max ? n : max;
	for (int i = 0; i < n; i++) {
		out[i] = hits[i].app;
	}
	g_free(hits);
	return n;
}

/* Whether a tile is this app, pinned */
char *apps_command(const char *desktop_path) {
	struct app app = { 0 };
	char *exec = NULL;
	if (parse_desktop(desktop_path, &app)) {
		exec = app.exec;
		app.exec = NULL;
	}
	app_free(&app);
	return exec;
}

bool apps_same(struct app *app, struct tile *tile) {
	return strcmp(tile->id, app->id) == 0 ||
		(tile->exec && app->exec && strcmp(tile->exec, app->exec) == 0);
}

void apps_activate_at(struct app *app, struct rect from) {
	if (!app->widget) {
		launch_at(app, from);
		return;
	}
	bool pin = app_tile(app) == NULL;
	toggle_pin(app);
	app->face_dirty = true;
	if (pin) {
		apps_show(false);
	}
}

/* Scanning takes a moment, so it's done shortly after startup rather
 * than when the view is first opened */
static gboolean preload(gpointer data) {
	/* Search holds on to entries: not under its feet */
	if (!ap.active && !search_active()) {
		apps_rescan();
	}
	return G_SOURCE_REMOVE;
}

void apps_init(void) {
	g_timeout_add(2000, preload, NULL);
}
