/*
 * Start: the patterned background, the header with the user card and its
 * power menu, the groups of tiles (scrolling sideways, dragged around,
 * selected for the app bar). Typing hands over to search.c.
 *
 * It is one widget drawing everything, as the tiles move too freely for
 * a box layout. Live tiles are drawn here like any other: tiles.c and
 * templates.c draw what live.c has for them.
 */
#define _GNU_SOURCE
#include <malloc.h>
#include <ctype.h>
#include <math.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <glib.h>
#include <gio/gio.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include "shell.h"
#include "pattern.h"

#define OPEN_MS 650
/* In the glasses Start sweeps away as it closes (the compositor keeps
 * it up for this long: its START_CLOSE_MS) */
#define CLOSE_MS 280
/* A touchpad click wobbles: a quick click needs a long way to drag, a
 * press held a moment only a little */
#define DRAG_THRESHOLD 10
#define DRAG_THRESHOLD_QUICK 40
#define DRAG_QUICK_MS 300
#define TOUCH_SLOP 12 // px a finger moves before it pans instead of taps
#define TOUCH_HOLD_MS 500 // press and hold: select, then drag to move
#define TOUCH_REST_MS 60 // a finger resting this long before lifting: no flick
#define GAP_EDGE 12 // px into the gap between groups that still count as the group
#define NAME_FONT ((struct c8ui_font){ 20, C8UI_WEIGHT_LIGHT })
#define NAME_MIN_W 260 // the name box, for narrow groups
#define USER_PICTURE_SIZE 40
#define USER_CARD_Y 46
#define HEADER_BAND 120 // "Start" and the user card are drawn inside this, from the top
#define USER_MENU_WIDTH 240
#define USER_MENU_ITEM 40
#define USER_MENU_PAD 4
#define USER_MENU_GAP 12 // between the account and power groups
#define APPBAR_BUTTON_W 110

enum appbar_button {
	BUTTON_UNPIN,
	BUTTON_RESIZE,
	BUTTON_COLOR,
	BUTTON_LIVE,
	BUTTON_LABEL,
	BUTTON_CLEAR,
	BUTTON_CUSTOMISE,
};

static const char *const appbar_labels[] = {
	[BUTTON_UNPIN] = "Unpin from Start",
	[BUTTON_RESIZE] = "Resize",
	[BUTTON_COLOR] = "Colour",
	[BUTTON_LIVE] = "Live tile",
	[BUTTON_LABEL] = "Name",
	[BUTTON_CLEAR] = "Clear selection",
	[BUTTON_CUSTOMISE] = "Customise",
};

enum user_item {
	USER_LOCK,
	USER_SIGN_OUT,
	USER_SLEEP,
	USER_RESTART,
	USER_SHUT_DOWN,
	USER_EXIT,
};

static const char *const user_labels[] = {
	[USER_LOCK] = "Lock",
	[USER_SIGN_OUT] = "Sign out",
	[USER_SLEEP] = "Sleep",
	[USER_RESTART] = "Restart",
	[USER_SHUT_DOWN] = "Shut down",
	[USER_EXIT] = "Exit cont8nuum",
};

struct button {
	struct rect box;
	int id;
};

enum grab {
	GRAB_NONE,
	GRAB_PRESS,
	GRAB_DRAG,
};

/* What a finger on the screen turned out to be doing */
enum touch_mode {
	TOUCH_NONE,
	TOUCH_PENDING, // a tap so far
	TOUCH_PAN_X, // sliding the page sideways
	TOUCH_PAN_Y, // pulling All apps up or down
	TOUCH_HELD, // held on a tile: it's selected, and moving drags it
	TOUCH_SPENT, // did its thing; the rest of it does nothing
};

static struct {
	struct shell_surface *surface;
	struct c8ui_widget *w; // cleared in its destroy

	int width, height, rows, content_width;
	double scroll, scroll_target;
	double fling; // px/ms, coasting after a flick
	int64_t opened_at, last_tick, frame_now;
	int64_t closed_at; // the closing sweep's start (glasses), 0 = none
	guint rotate_timer;

	enum grab grab;
	struct tile *grab_tile;
	double grab_x, grab_y, grab_dx, grab_dy;
	int64_t grab_time;
	struct tile *focus;

	/* Background app bar (right-click on nothing): Customise */
	bool bar_open;
	/* Customising: every group shows its name, or "Name group", to click
	 * and type in */
	bool customise;
	struct group *editing; // the group whose name is being typed
	struct c8ui_textedit *edit;
	double edit_scroll;
	bool edit_drag;

	/* The finger working Start; others are ignored meanwhile */
	struct {
		enum touch_mode mode;
		int32_t id;
		double x0, y0, x, y;
		uint32_t last_time;
		double vx; // px/ms
		bool in_apps; // landed on All apps
		bool in_search; // on search results
		struct tile *tile; // the tile it landed on
		guint hold_timer;
	} touch;

	/* Three or more fingers, touchpad or screen */
	struct c8ui_tab_swipe swipe;

	struct button appbar[6];
	int appbar_count;

	struct c8ui_icon *user_picture;
	bool user_picture_loaded;
	struct rect user_box;
	bool menu_open;
	struct button menu[6]; // relative to the menu
	int menu_count, menu_hover;
	struct rect menu_box;

	/* All of Start but the live tiles, rebuilt each frame */
	cairo_region_t *opaque;

	guint rest_timer;

	/* The next tick draws all of Start again, not only the tiles that
	 * changed: set by whoever starts an animation (animate) */
	bool tick_whole;

	/* The pattern, kept as an image */
	cairo_surface_t *bg;
	int bg_w, bg_h;
	double bg_scale;
	bool bg_dirty;
} st;

static void animate(void) {
	if (st.w) {
		st.tick_whole = true;
		c8ui_widget_animate(st.w);
	}
}

/* All of Start is drawn again */
static void redraw(void) {
	c8ui_widget_queue_draw(st.w);
}

/* Pressed (at x, y on Start) or let go: it sinks in toward the press or
 * springs back, Metro's press tilt; start_tick runs it */
static void press_tile(struct tile *tile, bool down, double x, double y) {
	tile->pressed = down;
	c8ui_tilt_set(&tile->tilt, down, x + st.scroll - tile->cur_x,
		y - tile->cur_y, c8ui_now());
	if (st.w) {
		c8ui_widget_animate(st.w);
	}
}

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

static double text_width(double size, enum c8ui_weight weight,
		const char *s) {
	double w, h;
	c8ui_text_size(c8ui_widget_font(st.w), (struct c8ui_font){ size, weight },
		s, 0, 0, &w, &h);
	return w;
}

/* Layout */

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

static void relayout(void) {
	if (st.height == 0) {
		return;
	}
	int pitch = tile_cell() + TILE_GAP;
	int rows = (st.height - START_TILES_Y - 56 + TILE_GAP) / pitch;
	st.rows = rows < 4 ? 4 : rows;
	st.content_width = tiles_layout(st.rows);
	/* In the glasses the shell's screen widens to it while Start is up,
	 * so nothing needs scrolling there */
	static int sent = -1;
	if (st.content_width != sent && shell.proto) {
		sent = st.content_width;
		c8_shell_v1_set_start_width(shell.proto, sent);
	}
	clamp_scroll();
	animate();
}

static void scroll_into_view(struct tile *tile) {
	scroll_reveal(&st.scroll_target, &tile->box, st.content_width, st.width);
	animate();
}

/* The background */

static void draw_pattern(cairo_t *cr, int w, int h) {
	c8_draw_background(cr, w, h, shell.appearance.background,
		shell.appearance.pattern, C8_BACKGROUND_START);
}

/* Photos set (or a file manager removed) the picture: drawn again */
static void picture_changed(GFileMonitor *m, GFile *file, GFile *other,
		GFileMonitorEvent event, gpointer data) {
	if (event == G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT ||
			event == G_FILE_MONITOR_EVENT_ATTRIBUTE_CHANGED) {
		return;
	}
	const char *start = c8_background_name(C8_BACKGROUND_START);
	const char *lock = c8_background_name(C8_BACKGROUND_LOCK);
	char *a = g_file_get_basename(file);
	char *b = other ? g_file_get_basename(other) : NULL;
	if (strcmp(a, start) == 0 || g_strcmp0(b, start) == 0) {
		st.bg_dirty = true;
		redraw();
	}
	if (strcmp(a, lock) == 0 || g_strcmp0(b, lock) == 0) {
		login_picture_changed(); // the login screen's copy
	}
	g_free(a);
	g_free(b);
}

static void watch_picture(void) {
	char *dir = c8_background_dir();
	g_mkdir_with_parents(dir, 0700);
	GFile *f = g_file_new_for_path(dir);
	/* Kept for the shell's life */
	GFileMonitor *m = g_file_monitor_directory(f, G_FILE_MONITOR_WATCH_MOVES,
		NULL, NULL);
	if (m) {
		g_signal_connect(m, "changed", G_CALLBACK(picture_changed), NULL);
	}
	g_object_unref(f);
	g_free(dir);
}

static void draw_background(cairo_t *cr) {
	cairo_surface_t *target = cairo_get_target(cr);
	double sx, sy;
	cairo_surface_get_device_scale(target, &sx, &sy);
	int w = st.width, h = st.height;
	if (st.bg == NULL || st.bg_w != w || st.bg_h != h || st.bg_scale != sx) {
		if (st.bg) {
			cairo_surface_destroy(st.bg);
		}
		st.bg = cairo_surface_create_similar(target, CAIRO_CONTENT_COLOR, w,
			h);
		st.bg_w = w;
		st.bg_h = h;
		st.bg_scale = sx;
		st.bg_dirty = true;
	}
	if (st.bg_dirty) {
		cairo_t *bcr = cairo_create(st.bg);
		draw_pattern(bcr, w, h);
		cairo_destroy(bcr);
		st.bg_dirty = false;
	}
	/* It stays put while the tiles scroll, like All apps: a drifting
	 * background makes people motion sick */
	cairo_set_source_surface(cr, st.bg, 0, 0);
	cairo_paint(cr);
}

/* The header and the user card */

static void user_name(char *buf, size_t len) {
	/* Asked for every frame Start draws: looked up once */
	static char known[128];
	static bool looked;
	if (!looked) {
		looked = true;
		struct passwd *pw = getpwuid(getuid());
		const char *name = NULL;
		if (pw && pw->pw_gecos && pw->pw_gecos[0]) {
			name = pw->pw_gecos;
		} else if (pw) {
			name = pw->pw_name;
		} else {
			name = getenv("USER");
		}
		snprintf(known, sizeof(known), "%s", name ? name : "");
		char *comma = strchr(known, ',');
		if (comma) {
			*comma = '\0';
		}
	}
	/* Stealth mode: the persona's, and no picture (draw_header) */
	snprintf(buf, len, "%s", c8_stealth() ? c8_stealth_name() : known);
}

static struct c8ui_icon *load_user_picture(void) {
	struct passwd *pw = getpwuid(getuid());
	const char *home = getenv("HOME");
	if (home == NULL && pw) {
		home = pw->pw_dir;
	}
	char path[1024];
	struct c8ui_icon *icon = NULL;
	if (pw) {
		snprintf(path, sizeof(path), "/var/lib/AccountsService/icons/%s",
			pw->pw_name);
		icon = c8ui_icon_load(NULL, path);
	}
	static const char *faces[] = { ".face", ".face.icon" };
	for (size_t i = 0; icon == NULL && home && i < 2; i++) {
		snprintf(path, sizeof(path), "%s/%s", home, faces[i]);
		icon = c8ui_icon_load(NULL, path);
	}
	return icon;
}

static void draw_header(cairo_t *cr) {
	cairo_set_source_rgb(cr, 1, 1, 1);
	text(cr, 48, C8UI_WEIGHT_LIGHT, "Start", START_MARGIN_X, 36, 0);

	char name[128];
	user_name(name, sizeof(name));
	double tw = text_width(26, C8UI_WEIGHT_LIGHT, name);
	int ax = st.width - 40 - USER_PICTURE_SIZE, ay = USER_CARD_Y;
	text(cr, 26, C8UI_WEIGHT_LIGHT, name, ax - 16 - tw, ay + 2, 0);
	st.user_box = (struct rect){
		.x = ax - 16 - (int)tw - 8, .y = ay - 6,
		.width = (int)tw + 16 + USER_PICTURE_SIZE + 16,
		.height = USER_PICTURE_SIZE + 12,
	};

	if (!st.user_picture_loaded) {
		st.user_picture = load_user_picture();
		st.user_picture_loaded = true;
	}
	if (st.user_picture && !c8_stealth()) {
		/* Fill the square, cropping the longer side */
		double iw, ih;
		c8ui_icon_get_size(st.user_picture, &iw, &ih);
		double scale = USER_PICTURE_SIZE / (iw < ih ? iw : ih);
		double dw = iw * scale, dh = ih * scale;
		cairo_save(cr);
		cairo_rectangle(cr, ax, ay, USER_PICTURE_SIZE, USER_PICTURE_SIZE);
		cairo_clip(cr);
		c8ui_icon_draw(cr, st.user_picture, ax + (USER_PICTURE_SIZE - dw) / 2,
			ay + (USER_PICTURE_SIZE - dh) / 2, dw, dh);
		cairo_restore(cr);
		return;
	}
	c8ui_set_source(cr, c8ui_shade(shell.appearance.accent, 0.8), 1);
	cairo_rectangle(cr, ax, ay, USER_PICTURE_SIZE, USER_PICTURE_SIZE);
	cairo_fill(cr);
	if (name[0]) {
		char initial[2] = { (char)toupper((unsigned char)name[0]), 0 };
		cairo_set_source_rgb(cr, 1, 1, 1);
		double iw = text_width(22, C8UI_WEIGHT_NORMAL, initial);
		text(cr, 22, C8UI_WEIGHT_NORMAL, initial,
			ax + USER_PICTURE_SIZE / 2.0 - iw / 2, ay + 5, 0);
	}
}

/* The user menu: a white list under the user card, like the login
 * screen's */

static void show_menu(bool show) {
	if (show == st.menu_open) {
		return;
	}
	st.menu_open = show;
	redraw();
	if (!show) {
		return;
	}
	st.menu_count = 0;
	st.menu_hover = -1;
	int y = USER_MENU_PAD;
	uint32_t power = shell.power;
	if (power & C8_SHELL_V1_POWER_EXIT) {
		/* Nested in another desktop, lock and power would act on the
		 * host: leaving is all there is */
		st.menu[st.menu_count++] = (struct button){
			{ 0, y, USER_MENU_WIDTH, USER_MENU_ITEM }, USER_EXIT };
		y += USER_MENU_ITEM;
	} else {
		static const uint32_t needs[] = {
			[USER_LOCK] = C8_SHELL_V1_POWER_LOCK,
			[USER_SIGN_OUT] = C8_SHELL_V1_POWER_SIGN_OUT,
			[USER_SLEEP] = C8_SHELL_V1_POWER_SLEEP,
			[USER_RESTART] = C8_SHELL_V1_POWER_RESTART,
			[USER_SHUT_DOWN] = C8_SHELL_V1_POWER_SHUT_DOWN,
		};
		for (int id = USER_LOCK; id <= USER_SHUT_DOWN; id++) {
			if (!(power & needs[id]) && id != USER_SIGN_OUT) {
				continue;
			}
			if (id >= USER_SLEEP && st.menu_count > 0 &&
					st.menu[st.menu_count - 1].id < USER_SLEEP) {
				y += USER_MENU_GAP;
			}
			st.menu[st.menu_count++] = (struct button){
				{ 0, y, USER_MENU_WIDTH, USER_MENU_ITEM }, id };
			y += USER_MENU_ITEM;
		}
	}
	st.menu_box = (struct rect){
		st.user_box.x + st.user_box.width - USER_MENU_WIDTH,
		st.user_box.y + st.user_box.height + 4,
		USER_MENU_WIDTH, y + USER_MENU_PAD,
	};
}

static int menu_at(double x, double y) {
	for (int i = 0; i < st.menu_count; i++) {
		if (in_rect(&st.menu[i].box, x - st.menu_box.x, y - st.menu_box.y)) {
			return i;
		}
	}
	return -1;
}

static void menu_action(int id) {
	static const uint32_t commands[] = {
		[USER_LOCK] = C8_SHELL_V1_COMMAND_LOCK,
		[USER_SIGN_OUT] = C8_SHELL_V1_COMMAND_SIGN_OUT,
		[USER_SLEEP] = C8_SHELL_V1_COMMAND_SLEEP,
		[USER_RESTART] = C8_SHELL_V1_COMMAND_RESTART,
		[USER_SHUT_DOWN] = C8_SHELL_V1_COMMAND_SHUT_DOWN,
		[USER_EXIT] = C8_SHELL_V1_COMMAND_SIGN_OUT,
	};
	show_menu(false);
	c8_shell_v1_run(shell.proto, commands[id]);
}

static void draw_menu(cairo_t *cr) {
	struct rect *m = &st.menu_box;
	cairo_save(cr);
	cairo_translate(cr, m->x, m->y);
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_rectangle(cr, 0, 0, m->width, m->height);
	cairo_fill(cr);
	c8ui_set_source(cr, 0xd0d0d0, 1);
	cairo_set_line_width(cr, 1);
	cairo_rectangle(cr, 0.5, 0.5, m->width - 1, m->height - 1);
	cairo_stroke(cr);
	for (int i = 0; i < st.menu_count; i++) {
		struct button *b = &st.menu[i];
		if (i == st.menu_hover) {
			c8ui_set_source(cr, 0xe4e4e4, 1);
			cairo_rectangle(cr, b->box.x, b->box.y, b->box.width,
				b->box.height);
			cairo_fill(cr);
		}
		if (i > 0 && b->id >= USER_SLEEP && st.menu[i - 1].id < USER_SLEEP) {
			c8ui_set_source(cr, 0xd0d0d0, 1);
			cairo_rectangle(cr, 16, b->box.y - USER_MENU_GAP / 2.0,
				m->width - 32, 1);
			cairo_fill(cr);
		}
		cairo_set_source_rgb(cr, 0, 0, 0);
		text(cr, 15, C8UI_WEIGHT_NORMAL, user_labels[b->id], b->box.x + 16,
			b->box.y + 10, b->box.width - 32);
	}
	cairo_restore(cr);
}

/* Selection and the app bar */

static int selected_count(void) {
	int n = 0;
	struct group *group;
	struct tile *tile;
	for_each_tile(group, tile) {
		n += tile->selected;
	}
	return n;
}

static struct tile *first_selected(void) {
	struct group *group;
	struct tile *tile;
	for_each_tile(group, tile) {
		if (tile->selected) {
			return tile;
		}
	}
	return NULL;
}

static uint32_t next_color(struct tile *tile) {
	uint32_t cur = tile_color(tile);
	for (int i = 0; i < METRO_PALETTE_LEN; i++) {
		if (metro_palette[i] == cur) {
			return metro_palette[(i + 1) % METRO_PALETTE_LEN];
		}
	}
	return metro_palette[0];
}

static void update_appbar(void) {
	st.appbar_count = 0;
	int n = selected_count();
	if (n > 0) {
		st.bar_open = false;
	}
	if (n == 0 && st.bar_open) {
		st.appbar[st.appbar_count++] = (struct button){
			{ 40, 0, APPBAR_BUTTON_W, APPBAR_HEIGHT }, BUTTON_CUSTOMISE };
	} else if (n > 0) {
		static const int ids[] = { BUTTON_UNPIN, BUTTON_RESIZE, BUTTON_COLOR,
			BUTTON_LIVE, BUTTON_LABEL };
		int x = 40;
		for (size_t i = 0; i < sizeof(ids) / sizeof(ids[0]); i++) {
			if (n > 1 && ids[i] != BUTTON_UNPIN && ids[i] != BUTTON_COLOR) {
				continue;
			}
			st.appbar[st.appbar_count++] = (struct button){
				{ x, 0, APPBAR_BUTTON_W, APPBAR_HEIGHT }, ids[i] };
			x += APPBAR_BUTTON_W;
		}
		st.appbar[st.appbar_count++] = (struct button){
			{ st.width - 150, 0, APPBAR_BUTTON_W, APPBAR_HEIGHT },
			BUTTON_CLEAR };
	}
	redraw();
}

static void set_selected(struct tile *tile, bool selected) {
	tile->selected = selected;
	redraw();
}

static void clear_selection(void) {
	struct group *group;
	struct tile *tile;
	for_each_tile(group, tile) {
		tile->selected = false;
	}
	update_appbar();
}

static void toggle_selected(struct tile *tile) {
	set_selected(tile, !tile->selected);
	update_appbar(); // which draws again
}

static void draw_appbar_glyph(cairo_t *cr, int id, double cx, double cy) {
	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);
	switch (id) {
	case BUTTON_UNPIN:
	case BUTTON_CLEAR:
		cairo_move_to(cr, cx - 7, cy - 7);
		cairo_line_to(cr, cx + 7, cy + 7);
		cairo_move_to(cr, cx + 7, cy - 7);
		cairo_line_to(cr, cx - 7, cy + 7);
		if (id == BUTTON_CLEAR) {
			cairo_new_path(cr);
			cairo_move_to(cr, cx - 8, cy);
			cairo_line_to(cr, cx + 8, cy);
		}
		cairo_stroke(cr);
		break;
	case BUTTON_RESIZE:
		cairo_rectangle(cr, cx - 9, cy - 9, 18, 18);
		cairo_stroke(cr);
		cairo_rectangle(cr, cx - 9, cy + 1, 8, 8);
		cairo_fill(cr);
		break;
	case BUTTON_COLOR: {
		struct tile *tile = first_selected();
		c8ui_set_source(cr, tile ? next_color(tile) : metro_palette[0], 1);
		cairo_arc(cr, cx, cy, 10, 0, 2 * M_PI);
		cairo_fill(cr);
		break;
	}
	case BUTTON_LIVE:
		for (int i = -1; i <= 1; i++) {
			cairo_move_to(cr, cx - 9, cy + i * 6);
			cairo_line_to(cr, cx + 9, cy + i * 6);
		}
		cairo_stroke(cr);
		break;
	case BUTTON_LABEL: {
		double tw = text_width(16, C8UI_WEIGHT_NORMAL, "Aa");
		text(cr, 16, C8UI_WEIGHT_NORMAL, "Aa", cx - tw / 2, cy - 11, 0);
		break;
	}
	case BUTTON_CUSTOMISE:
		/* A pencil */
		cairo_move_to(cr, cx - 7, cy + 7);
		cairo_line_to(cr, cx - 6, cy + 2);
		cairo_line_to(cr, cx + 4, cy - 8);
		cairo_line_to(cr, cx + 8, cy - 4);
		cairo_line_to(cr, cx - 2, cy + 6);
		cairo_close_path(cr);
		cairo_stroke(cr);
		break;
	}
}

static void draw_appbar(cairo_t *cr) {
	double top = st.height - APPBAR_HEIGHT;
	c8ui_set_source(cr, 0x121212, 0.94);
	cairo_rectangle(cr, 0, top, st.width, APPBAR_HEIGHT);
	cairo_fill(cr);
	struct tile *tile = first_selected();
	for (int i = 0; i < st.appbar_count; i++) {
		struct button *b = &st.appbar[i];
		double cx = b->box.x + b->box.width / 2.0;
		draw_appbar_glyph(cr, b->id, cx, top + 30);
		const char *label = appbar_labels[b->id];
		char buf[64];
		if (b->id == BUTTON_LIVE && tile) {
			snprintf(buf, sizeof(buf), "Turn live tile %s",
				tile->live_enabled ? "off" : "on");
			label = buf;
		} else if (b->id == BUTTON_LABEL && tile) {
			snprintf(buf, sizeof(buf), "%s name",
				tile->label ? "Hide" : "Show");
			label = buf;
		} else if (b->id == BUTTON_RESIZE && tile) {
			static const char *next[] = { "Medium", "Wide", "Large", "Small" };
			snprintf(buf, sizeof(buf), "Resize: %s", next[tile->size]);
			label = buf;
		}
		cairo_set_source_rgb(cr, 1, 1, 1);
		double tw = text_width(12, C8UI_WEIGHT_NORMAL, label);
		double max = b->box.width - 4;
		text(cr, 12, C8UI_WEIGHT_NORMAL, label, cx - fmin(tw, max) / 2,
			top + 56, max);
	}
}

static void unpin(struct tile *tile) {
	if (st.focus == tile) {
		st.focus = NULL;
	}
	if (st.grab_tile == tile) {
		st.grab = GRAB_NONE;
		st.grab_tile = NULL;
	}
	tile_destroy(tile);
}

static void set_customise(bool on);
static void prune(void);

static void appbar_action(int id) {
	if (id == BUTTON_CUSTOMISE) {
		set_customise(true);
		return;
	}
	struct tile *first = first_selected();
	if (first == NULL) {
		return;
	}
	uint32_t color = next_color(first);
	bool live = !first->live_enabled, label = !first->label;
	struct group *group, *gtmp;
	struct tile *tile, *tmp;
	wl_list_for_each_safe(group, gtmp, &tile_groups, link) {
		wl_list_for_each_safe(tile, tmp, &group->tiles, link) {
			if (!tile->selected) {
				continue;
			}
			switch (id) {
			case BUTTON_UNPIN:
				unpin(tile);
				continue;
			case BUTTON_RESIZE:
				tile->size = (tile->size + 1) % (TILE_LARGE + 1);
				break;
			case BUTTON_COLOR:
				tile->color = color;
				tile->has_color = true;
				break;
			case BUTTON_LIVE:
				tile->live_enabled = live;
				tile->slide = 0;
				break;
			case BUTTON_LABEL:
				tile->label = label;
				break;
			case BUTTON_CLEAR:
				tile->selected = false;
				break;
			}
			tile->face_dirty = true;
		}
	}
	prune();
	relayout();
	update_appbar();
	if (id != BUTTON_CLEAR) {
		tiles_save();
		tiles_style_windows();
	}
}

/* Groups: their names, customising, new groups */

/* Drops emptied groups, and with them a name being typed */
static void prune(void) {
	if (st.editing && wl_list_empty(&st.editing->tiles)) {
		st.editing = NULL;
	}
	groups_prune();
}

/* The tiles were moved, added or taken away: lay them out and keep it */
static void commit_layout(void) {
	prune();
	relayout();
	tiles_save();
}

static bool header_shown(struct group *group) {
	return group->width > 0 && (group->name[0] || st.customise ||
		group == st.editing);
}

/* Where a group's name is, or would be, on screen */
static struct rect header_box(struct group *group) {
	const char *label = group->name[0] ? group->name : "Name group";
	double tw = text_width(NAME_FONT.size, NAME_FONT.weight, label);
	int w = (int)fmax(tw, group->width);
	if (group == st.editing && w < NAME_MIN_W) {
		w = NAME_MIN_W;
	}
	return (struct rect){ group->x - (int)st.scroll - 8, START_TILES_Y - 46,
		w + 16, 36 };
}

static struct group *header_at(double x, double y) {
	struct group *group;
	wl_list_for_each(group, &tile_groups, link) {
		struct rect box = header_box(group);
		if (header_shown(group) && in_rect(&box, x, y)) {
			return group;
		}
	}
	return NULL;
}

static void stop_editing(bool keep) {
	struct group *group = st.editing;
	if (group == NULL) {
		return;
	}
	st.editing = NULL;
	st.edit_drag = false;
	redraw();
	if (!keep) {
		return;
	}
	char *name = g_strstrip(g_strdup(c8ui_textedit_get(st.edit)));
	if (strcmp(name, group->name) != 0) {
		group_set_name(group, name);
		tiles_save();
	}
	g_free(name);
}

static void start_editing(struct group *group) {
	stop_editing(true);
	if (st.edit == NULL) {
		st.edit = c8ui_textedit_new(NULL);
	}
	st.editing = group;
	st.edit_scroll = 0;
	c8ui_textedit_set(st.edit, group->name);
	c8ui_textedit_select_all(st.edit);
	redraw();
}

static void set_customise(bool on) {
	if (!on) {
		stop_editing(true);
	}
	st.customise = on;
	st.bar_open = false;
	update_appbar();
}

static double edit_text_x(double x) {
	struct rect box = header_box(st.editing);
	return x - (box.x + 8 - st.edit_scroll);
}

static void edit_moved(void) {
	struct rect box = header_box(st.editing);
	c8ui_textedit_scroll_to_caret(st.edit, c8ui_widget_font(st.w), NAME_FONT,
		box.width - 16, &st.edit_scroll);
	redraw();
}

static bool edit_key(const struct c8ui_event *ev) {
	switch (ev->sym) {
	case XKB_KEY_Return:
	case XKB_KEY_KP_Enter:
	case XKB_KEY_Tab:
		stop_editing(true);
		return true;
	case XKB_KEY_Escape:
		stop_editing(false);
		return true;
	}
	if (c8ui_textedit_key(st.edit, st.w->root, ev) != C8UI_EDIT_IGNORED) {
		edit_moved();
	}
	return true; // typing here never starts a search
}

static void draw_headers(cairo_t *cr, double alpha) {
	const char *family = c8ui_widget_font(st.w);
	struct group *group;
	wl_list_for_each(group, &tile_groups, link) {
		if (!header_shown(group)) {
			continue;
		}
		struct rect box = header_box(group);
		if (group == st.editing) {
			/* Typing the name: a white box, as Windows 8 has */
			cairo_set_source_rgb(cr, 1, 1, 1);
			cairo_rectangle(cr, box.x, box.y, box.width, box.height);
			cairo_fill(cr);
			cairo_save(cr);
			cairo_rectangle(cr, box.x + 2, box.y, box.width - 4, box.height);
			cairo_clip(cr);
			c8ui_textedit_draw(st.edit, cr, family, NAME_FONT,
				box.x + 8 - st.edit_scroll, box.y + 6, box.y + 5,
				box.height - 10, shell.appearance.accent, true, true, 1);
			cairo_restore(cr);
			continue;
		}
		bool placeholder = group->name[0] == '\0';
		cairo_set_source_rgba(cr, 1, 1, 1, alpha * (placeholder ? 0.5 : 1));
		text(cr, NAME_FONT.size, NAME_FONT.weight,
			placeholder ? "Name group" : group->name, box.x + 8, box.y + 6,
			box.width - 16);
		if (st.customise) {
			/* Something to click */
			cairo_set_source_rgba(cr, 1, 1, 1, alpha * 0.35);
			cairo_rectangle(cr, box.x + 8, box.y + box.height - 2,
				box.width - 16, 1);
			cairo_fill(cr);
		}
	}
}

/* Tiles */

void start_activate_tile(struct tile *tile, struct rect from) {
	live_activated(tile);
	if (tile->exec && tile->exec[0]) {
		splash_show(from, tile_color(tile), tile->icon);
		shell_launch(tile->exec);
	}
}

static void activate_tile(struct tile *tile) {
	struct rect from = tile->box;
	from.x -= (int)st.scroll;
	start_activate_tile(tile, from);
}

static struct tile *tile_at(double x, double y) {
	double tx = x + st.scroll;
	struct group *group;
	struct tile *tile;
	for_each_tile(group, tile) {
		if (st.grab == GRAB_DRAG && tile == st.grab_tile) {
			continue;
		}
		if (in_rect(&tile->box, tx, y)) {
			return tile;
		}
	}
	return NULL;
}

/* Tiles sweep in from the right as Start opens, staggered by where they
 * are on screen */
static void sweep(struct tile *tile, double *offset, double *alpha) {
	*offset = 0;
	*alpha = 1;
	int64_t since = st.frame_now - st.opened_at;
	/* How far across the screen it is: the left goes first */
	double across = fmax(0, fmin(1, (tile->box.x - st.scroll) / st.width));
	if (st.closed_at) {
		/* Closing: the opening in reverse, off to the right and gone,
		 * the tiles on the left first */
		double delay = across * 80;
		double t = fmax(0, fmin(1, (st.frame_now - st.closed_at - delay) /
			(CLOSE_MS - 80.0)));
		*offset = t * t * 160;
		*alpha = 1 - t;
		return;
	}
	if (since < OPEN_MS + 400) {
		double delay = across * 260;
		double p = ease_out((since - delay) / (OPEN_MS - 200.0));
		*offset = (1 - p) * 160;
		*alpha = p;
	}
	if (st.grab == GRAB_DRAG && st.grab_tile == tile) {
		*alpha *= 0.85;
	}
}

static void draw_one(cairo_t *cr, struct tile *tile) {
	double offset, alpha;
	sweep(tile, &offset, &alpha);
	tile->alpha = alpha;
	double x = tile->cur_x + offset - st.scroll, y = tile->cur_y;
	/* Not among what this frame draws (another tile changed, or it's
	 * scrolled off): its face waits until it is */
	if (!c8ui_clip_shows(cr, round(x), round(y), tile->box.width,
			tile->box.height)) {
		return;
	}
	tile_draw(cr, st.w, tile, x, y);
}

/* Only this tile looks different (its live content, a flip): it alone is
 * drawn again, where it is now. Anything that moves tiles or covers them
 * draws all of Start instead. */
static void redraw_tile(struct tile *tile) {
	if (st.w == NULL) {
		return;
	}
	if (search_active() || apps_progress() > 0) {
		redraw();
		return;
	}
	c8ui_widget_queue_draw_rect(st.w, floor(tile->cur_x - st.scroll) - 1,
		floor(tile->cur_y) - 1, tile->box.width + 2, tile->box.height + 2);
}

static void draw_apps_button(cairo_t *cr) {
	if (st.appbar_count == 0) {
		apps_draw_arrow(cr, START_MARGIN_X + 16, st.height - 32, false);
	}
}

static void start_draw(struct c8ui_widget *w, cairo_t *cr) {
	if (st.width == 0) {
		return;
	}
	if (st.frame_now == 0) {
		st.frame_now = now_ms();
	}
	if (shell.appearance.xr) {
		/* In the glasses Start is only its tiles, floating where you
		 * look; what's clear is clear (the room shows through) */
		cairo_save(cr);
		cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
		cairo_paint(cr);
		cairo_restore(cr);
	} else {
		/* The pattern covers everything, so all of Start is opaque.
		 * Without saying so the compositor draws every window and the
		 * wallpaper under it, each frame. */
		cairo_rectangle_int_t all = { 0, 0, st.width, st.height };
		st.opaque = cairo_region_create_rectangle(&all);
		draw_background(cr);
	}
	if (search_active()) {
		search_draw(cr, w, st.frame_now);
		goto done;
	}
	double progress = apps_progress();
	if (progress > 0) {
		cairo_save(cr);
		cairo_translate(cr, 0, round((1 - progress) * st.height));
		apps_draw(cr, w);
		cairo_restore(cr);
	}
	if (progress >= 1) {
		goto done;
	}
	cairo_save(cr);
	cairo_translate(cr, 0, round(-progress * st.height));
	/* Closing, the header and group names fade as the tiles go */
	double fade = st.closed_at ? fmax(0, 1 - (double)(st.frame_now -
		st.closed_at) / CLOSE_MS) : 1;
	if (fade < 1) {
		cairo_push_group(cr);
	}
	/* Not when only tiles are being drawn again: the name and the
	 * picture are slow for nothing */
	if (c8ui_clip_shows(cr, 0, 0, st.width, HEADER_BAND)) {
		draw_header(cr);
	}
	if (fade < 1) {
		cairo_pop_group_to_source(cr);
		cairo_paint_with_alpha(cr, fade);
	}

	double labels = st.frame_now - st.opened_at < OPEN_MS ?
		ease_out((double)(st.frame_now - st.opened_at) / OPEN_MS) : 1;
	draw_headers(cr, labels * fade);
	struct group *group;
	struct tile *tile;
	for_each_tile(group, tile) {
		if (!(st.grab == GRAB_DRAG && st.grab_tile == tile)) {
			draw_one(cr, tile);
		}
	}
	if (st.grab == GRAB_DRAG && st.grab_tile) {
		draw_one(cr, st.grab_tile); // on top
	}

	if (fade > 0) {
		if (fade < 1) {
			cairo_push_group(cr);
		}
		draw_apps_button(cr);
		if (fade < 1) {
			cairo_pop_group_to_source(cr);
			cairo_paint_with_alpha(cr, fade);
		}
	}
	if (st.appbar_count > 0) {
		draw_appbar(cr);
	}
	if (st.menu_open) {
		draw_menu(cr);
	}
	cairo_restore(cr);
done:
	c8ui_window_set_opaque_region(shell_surface_window(st.surface),
		st.opaque);
	cairo_region_destroy(st.opaque);
	st.opaque = NULL;
}

/* Animation */

static gboolean rotate_due(gpointer data) {
	st.rotate_timer = 0;
	if (st.w) {
		/* Not animate(): a flip changes only its tile */
		c8ui_widget_animate(st.w);
	}
	return G_SOURCE_REMOVE;
}

static void schedule_rotation(int64_t now) {
	g_clear_handle_id(&st.rotate_timer, g_source_remove);
	if (!shell.start_visible || !shell.appearance.live_tiles) {
		return;
	}
	int64_t next = INT64_MAX;
	struct group *group;
	struct tile *tile;
	for_each_tile(group, tile) {
		if (tile_slide_count(tile) > 1 && tile->next_rotate < next) {
			next = tile->next_rotate;
		}
	}
	if (next != INT64_MAX) {
		int64_t delay = next - now;
		st.rotate_timer = g_timeout_add(delay < 16 ? 16 : (guint)delay,
			rotate_due, NULL);
	}
}

static bool start_tick(struct c8ui_widget *w, int64_t now) {
	double dt = st.last_tick && now - st.last_tick < 100 ?
		now - st.last_tick : 16;
	st.last_tick = now;
	st.frame_now = now;
	bool animating = false;
	/* Whether all of Start is drawn again after this tick. Not when
	 * all that happens is tiles flipping: then only they are. */
	bool whole = st.tick_whole || st.grab == GRAB_DRAG;
	st.tick_whole = false;

	if (apps_tick(now, dt)) {
		animating = whole = true;
	}
	if (search_tick(now, dt)) {
		animating = whole = true;
	}
	if (scroll_step(&st.fling, &st.scroll, &st.scroll_target, dt,
			st.content_width, st.width)) {
		animating = whole = true;
	}
	double k = 1 - exp(-dt / 70.0); // the tiles ease to their places alike
	struct group *group;
	struct tile *tile;
	for_each_tile(group, tile) {
		if (st.grab == GRAB_DRAG && st.grab_tile == tile) {
			tile->cur_x = st.grab_x + st.scroll - st.grab_dx;
			tile->cur_y = st.grab_y - st.grab_dy;
		} else {
			double dx = tile->box.x - tile->cur_x;
			double dy = tile->box.y - tile->cur_y;
			if (fabs(dx) > 0.5 || fabs(dy) > 0.5) {
				tile->cur_x += dx * k;
				tile->cur_y += dy * k;
				animating = whole = true;
			} else {
				if (tile->cur_x != tile->box.x ||
						tile->cur_y != tile->box.y) {
					whole = true; // its last step
				}
				tile->cur_x = tile->box.x;
				tile->cur_y = tile->box.y;
			}
		}
		if (tile_tick(tile, now)) {
			animating = true;
		}
		if (c8ui_tilt_moving(&tile->tilt, c8ui_now())) {
			animating = true;
			redraw_tile(tile); // sinking in or springing back
		}
	}
	if (now - st.opened_at < OPEN_MS + 400) {
		animating = whole = true;
	}
	if (st.closed_at && now - st.closed_at < CLOSE_MS + 50) {
		animating = whole = true;
	}
	if (!animating) {
		st.last_tick = 0;
		schedule_rotation(now);
	}
	if (whole) {
		c8ui_widget_queue_draw(w);
	} else {
		for_each_tile(group, tile) {
			if (tile->face_dirty || tile->flip_moved) {
				redraw_tile(tile);
			}
		}
	}
	return animating;
}

/* Dragging tiles */

static void drag_begin(void) {
	stop_editing(true);
}

static int index_in_group(struct tile *tile) {
	int i = 0;
	struct tile *t;
	wl_list_for_each(t, &tile->group->tiles, link) {
		if (t == tile) {
			return i;
		}
		i++;
	}
	return -1;
}

/* The tile goes into the order of the group under the pointer, where it
 * lands nearest to where it's held; the others flow around it. Over the
 * gap between two groups (or past either end) it starts a new group
 * there. */
static void drag_update(double x, double y) {
	struct tile *dragged = st.grab_tile;
	/* Scroll when dragging near the edges */
	if (x > st.width - 60) {
		st.scroll_target += 24;
	} else if (x < 60) {
		st.scroll_target -= 24;
	}
	clamp_scroll();

	double px = x + st.scroll;
	double left = px - st.grab_dx, top = y - st.grab_dy;
	struct group *target = NULL, *gap_before = NULL, *group;
	bool gap = true;
	wl_list_for_each(group, &tile_groups, link) {
		if (group->width <= 0) {
			continue;
		}
		if (px < group->x - GAP_EDGE) {
			gap_before = group;
			break;
		}
		if (px <= group->x + group->width + GAP_EDGE) {
			target = group;
			gap = false;
			break;
		}
	}
	/* A gap beside the group it is alone in: that group, already new */
	struct group *own = dragged->group;
	if (gap && wl_list_length(&own->tiles) == 1) {
		struct group *after = own->link.next == &tile_groups ? NULL :
			wl_container_of(own->link.next, after, link);
		if (gap_before == own || gap_before == after) {
			target = own;
			gap = false;
		}
	}
	if (gap) {
		tile_move(dragged, group_create_before(gap_before, ""), 0);
	} else {
		int index = tiles_drop_index(target, dragged, st.rows, left, top);
		if (target == own && index == index_in_group(dragged)) {
			return;
		}
		tile_move(dragged, target, index);
	}
	prune();
	relayout();
}

/* Pointer */

static void pointer_release(double x, double y);

/* Lets go of a pressed tile without doing anything with it */
static void drop_grab(void) {
	if (st.grab_tile) {
		press_tile(st.grab_tile, false, 0, 0);
	}
	st.grab = GRAB_NONE;
	st.grab_tile = NULL;
	redraw();
}

static void pointer_motion(double x, double y) {
	if (st.menu_open) {
		int i = menu_at(x, y);
		if (i != st.menu_hover) {
			st.menu_hover = i;
			redraw();
		}
	}
	/* The press was cancelled (the pointer was taken away before the
	 * release): no button is down, so nothing is carried */
	if (!st.w->pressed && st.touch.mode != TOUCH_HELD) {
		st.edit_drag = false;
	}
	if (st.grab != GRAB_NONE && st.touch.mode != TOUCH_HELD &&
			!st.w->pressed) {
		if (st.grab == GRAB_DRAG) {
			pointer_release(x, y); // dropped where it is
		} else {
			drop_grab();
		}
	}
	if (st.edit_drag && st.editing) {
		c8ui_textedit_drag(st.edit, c8ui_widget_font(st.w), NAME_FONT,
			edit_text_x(x));
		edit_moved();
		return;
	}
	double threshold = now_ms() - st.grab_time < DRAG_QUICK_MS ?
		DRAG_THRESHOLD_QUICK : DRAG_THRESHOLD;
	if (st.grab == GRAB_PRESS && st.grab_tile &&
			hypot(x - st.grab_x, y - st.grab_y) > threshold) {
		st.grab = GRAB_DRAG;
		drag_begin();
		press_tile(st.grab_tile, false, 0, 0);
	}
	if (st.grab == GRAB_DRAG) {
		st.grab_x = x;
		st.grab_y = y;
		drag_update(x, y);
		animate();
	}
}

static void pointer_release(double x, double y) {
	struct tile *tile = st.grab_tile;
	if (st.grab == GRAB_PRESS && tile) {
		press_tile(tile, false, 0, 0);
		if (selected_count() > 0) {
			toggle_selected(tile);
		} else if (tile_at(x, y) == tile) {
			activate_tile(tile);
		}
	} else if (st.grab == GRAB_DRAG) {
		commit_layout();
	}
	st.grab = GRAB_NONE;
	st.grab_tile = NULL;
	st.edit_drag = false;
	animate();
}

static bool pointer_press(double x, double y, uint32_t button) {
	/* An open menu takes the click; outside it, the click just closes it */
	if (st.menu_open) {
		int i = menu_at(x, y);
		if (i >= 0 && button == C8UI_BUTTON_LEFT) {
			menu_action(st.menu[i].id);
		} else if (i < 0) {
			show_menu(false);
		}
		return true;
	}
	if (button == C8UI_BUTTON_LEFT && in_rect(&st.user_box, x, y)) {
		clear_selection();
		show_menu(true);
		return true;
	}
	if (st.appbar_count > 0 && y >= st.height - APPBAR_HEIGHT) {
		double ay = y - (st.height - APPBAR_HEIGHT);
		for (int i = 0; i < st.appbar_count; i++) {
			if (in_rect(&st.appbar[i].box, x, ay)) {
				appbar_action(st.appbar[i].id);
				break;
			}
		}
		return true;
	}

	/* Typing a group's name: a click in the box moves the caret, one
	 * anywhere else keeps the name and goes on */
	if (st.editing) {
		struct rect box = header_box(st.editing);
		if (in_rect(&box, x, y)) {
			if (button == C8UI_BUTTON_LEFT) {
				c8ui_textedit_press(st.edit, c8ui_widget_font(st.w),
					NAME_FONT, edit_text_x(x), false);
				st.edit_drag = true;
				edit_moved();
			}
			return true;
		}
		stop_editing(true);
	}
	/* A group's name: click it to rename it */
	struct group *header = header_at(x, y);
	if (header && (button == C8UI_BUTTON_LEFT ||
			button == C8UI_BUTTON_RIGHT)) {
		if (!st.customise) {
			set_customise(true);
		}
		start_editing(header);
		return true;
	}

	struct rect apps_button = { START_MARGIN_X - 8, st.height - 56, 48, 48 };
	if (button == C8UI_BUTTON_LEFT && in_rect(&apps_button, x, y)) {
		start_open_apps();
		apps_show(true);
		return true;
	}

	struct tile *tile = tile_at(x, y);
	if (button == C8UI_BUTTON_RIGHT) {
		if (tile) {
			set_selected(tile, !tile->selected);
		} else if (selected_count() > 0) {
			clear_selection();
		} else {
			/* On nothing: the app bar with Customise */
			st.bar_open = !st.bar_open;
		}
		update_appbar();
		return true;
	}
	if (button != C8UI_BUTTON_LEFT) {
		return false;
	}
	if (tile == NULL) {
		st.bar_open = false;
		if (st.customise) {
			set_customise(false);
		}
		clear_selection();
		return true;
	}
	st.grab = GRAB_PRESS;
	st.grab_tile = tile;
	st.grab_x = x;
	st.grab_y = y;
	st.grab_time = now_ms();
	st.grab_dx = x + st.scroll - tile->cur_x;
	st.grab_dy = y - tile->cur_y;
	press_tile(tile, true, x, y);
	redraw();
	return true;
}

/* A touchpad swipe sideways coasts on when the fingers lift while still
 * moving, as a finger flick does: the speed of the last scroll steps, in
 * the units scroll_target moves by */
#define PAD_GAP_MS 120
#define PAD_MIN 0.05

static struct {
	double v; // px/ms
	int64_t last;
} pad;

static void pad_sample(double delta, bool precise) {
	if (!precise) {
		pad.last = 0;
		pad.v = 0;
		return;
	}
	int64_t now = now_ms();
	int64_t dt = pad.last ? now - pad.last : 0;
	if (pad.last == 0 || dt > PAD_GAP_MS) {
		pad.v = 0;
		dt = 0;
	}
	pad.last = now;
	if (dt > 0) {
		pad.v = pad.v * 0.4 + delta / (double)(dt < 4 ? 4 : dt) * 0.6;
	}
}

/* Sends whichever page is up coasting on at v px/ms */
static void fling_page(bool in_search, bool in_apps, double v) {
	if (in_search) {
		search_fling(v);
	} else if (in_apps) {
		apps_fling(v);
	} else {
		st.fling = v;
		animate();
	}
}

static void pad_lift(void) {
	double v = pad.v;
	bool moving = pad.last && now_ms() - pad.last < PAD_GAP_MS &&
		fabs(v) > PAD_MIN;
	pad.last = 0;
	pad.v = 0;
	if (!moving) {
		return;
	}
	fling_page(search_active(), apps_active(), v);
}

static void scroll(double dx, double dy, bool precise) {
	double most = fabs(dx) > fabs(dy) ? dx : dy; // the way it mostly went
	if (search_active()) {
		/* Results only go sideways, whichever way the fingers do */
		double delta = most * (precise ? 2 : 8);
		pad_sample(delta, precise);
		search_scroll(delta);
		return;
	}
	/* A touchpad's up and down moves between Start and All apps with
	 * the fingers; sideways scrolls the page */
	if (precise && (apps_dragging() || fabs(dy) > fabs(dx))) {
		pad_sample(0, false);
		apps_drag(dy);
		return;
	}
	if (apps_dragging()) {
		return; // a swipe's sideways wobble
	}
	/* A wheel scrolls sideways, the way the pages go */
	double delta = precise ? dx * 2 : most * 8;
	pad_sample(delta, precise);
	if (apps_active()) {
		apps_scroll(delta);
		return;
	}
	scroll_by(&st.fling, &st.scroll, &st.scroll_target, delta,
		st.content_width, st.width, false);
	animate();
}

/* Touch: a finger on Start pans it with the finger and flicks it on; up
 * brings All apps, down puts it away; a tap is a click; swiping a tile
 * down, or holding it, selects it, and once held it drags to move */

static void touch_unpress(void) {
	if (st.touch.tile && st.touch.tile->pressed && st.grab == GRAB_NONE) {
		press_tile(st.touch.tile, false, 0, 0);
		redraw();
	}
}

static void touch_stop_hold(void) {
	g_clear_handle_id(&st.touch.hold_timer, g_source_remove);
}

static gboolean touch_held(gpointer data) {
	st.touch.hold_timer = 0;
	if (st.touch.mode != TOUCH_PENDING || st.touch.in_search) {
		return G_SOURCE_REMOVE;
	}
	double x = st.touch.x0, y = st.touch.y0;
	if (st.touch.in_apps) {
		apps_press(x, y, C8UI_BUTTON_RIGHT);
		st.touch.mode = TOUCH_SPENT;
		return G_SOURCE_REMOVE;
	}
	struct tile *tile = st.touch.tile;
	if (tile == NULL && selected_count() == 0 && !header_at(x, y) &&
			y > START_TILES_Y - 48 && y < st.height - APPBAR_HEIGHT) {
		/* Held on the background: the app bar, as a right-click */
		st.bar_open = true;
		update_appbar();
		st.touch.mode = TOUCH_SPENT;
		return G_SOURCE_REMOVE;
	}
	if (tile == NULL || tile_at(x, y) != tile) {
		return G_SOURCE_REMOVE; // holding on nothing: still a pan or tap
	}
	/* Pressed as the mouse would: moving on from here drags it. Before
	 * selecting, which brings up the app bar, maybe over this spot. */
	pointer_press(x, y, C8UI_BUTTON_LEFT);
	press_tile(tile, false, 0, 0);
	if (st.grab_tile == tile && !tile->selected) {
		set_selected(tile, true);
		update_appbar();
	}
	st.touch.mode = TOUCH_HELD;
	redraw();
	return G_SOURCE_REMOVE;
}

static void touch_down(int32_t id, uint32_t time, double x, double y) {
	if (st.touch.mode != TOUCH_NONE) {
		return; // a second finger
	}
	st.touch.mode = TOUCH_PENDING;
	st.touch.id = id;
	st.touch.x0 = st.touch.x = x;
	st.touch.y0 = st.touch.y = y;
	st.touch.last_time = time;
	st.touch.vx = 0;
	st.touch.in_apps = apps_active();
	st.touch.in_search = search_active();
	st.touch.tile = NULL;
	/* A finger stops a coasting page where it is */
	st.fling = 0;
	st.scroll_target = st.scroll;
	apps_fling(0);
	search_fling(0);
	if (!st.touch.in_apps && !st.touch.in_search && !st.menu_open) {
		st.touch.tile = tile_at(x, y);
		if (st.touch.tile) {
			press_tile(st.touch.tile, true, x, y);
			redraw();
		}
	}
	if (!st.menu_open) {
		st.touch.hold_timer = g_timeout_add(TOUCH_HOLD_MS, touch_held, NULL);
	}
}

/* Moved far enough to be more than a tap: which way decides what */
static void touch_decide(double dx, double dy) {
	touch_stop_hold();
	touch_unpress();
	if (st.menu_open) {
		return; // only taps while the menu is open
	}
	if (fabs(dx) > fabs(dy)) {
		st.touch.mode = TOUCH_PAN_X;
		return;
	}
	if (st.touch.in_search) {
		st.touch.mode = TOUCH_SPENT;
		return;
	}
	bool up = dy < 0;
	if (st.touch.in_apps ? !up : up) {
		st.touch.mode = TOUCH_PAN_Y;
		return;
	}
	/* Down on a tile: Windows 8's cross-slide, to select it */
	struct tile *tile = st.touch.tile;
	if (!st.touch.in_apps && !up && tile) {
		toggle_selected(tile);
	}
	st.touch.mode = TOUCH_SPENT;
}

static void touch_motion(uint32_t time, double x, double y) {
	double mx = x - st.touch.x, my = y - st.touch.y;
	uint32_t dt = time - st.touch.last_time;
	double v = mx / (dt < 4 ? 4 : dt);
	st.touch.vx = dt > TOUCH_REST_MS ? v : 0.6 * st.touch.vx + 0.4 * v;
	st.touch.last_time = time;
	st.touch.x = x;
	st.touch.y = y;

	if (st.touch.mode == TOUCH_PENDING) {
		double dx = x - st.touch.x0, dy = y - st.touch.y0;
		if (hypot(dx, dy) < TOUCH_SLOP) {
			return;
		}
		touch_decide(dx, dy);
		/* Take up from where the finger is now, not where it landed */
		mx = my = 0;
	}
	switch (st.touch.mode) {
	case TOUCH_PAN_X:
		if (st.touch.in_search) {
			search_pan(-mx);
		} else if (st.touch.in_apps) {
			apps_pan(-mx);
		} else {
			scroll_by(&st.fling, &st.scroll, &st.scroll_target, -mx,
				st.content_width, st.width, true);
			animate();
		}
		break;
	case TOUCH_PAN_Y:
		if (my != 0) {
			apps_drag_finger(-my);
		}
		break;
	case TOUCH_HELD:
		pointer_motion(x, y);
		break;
	default:
		break;
	}
}

static void touch_up(uint32_t time, bool cancel) {
	enum touch_mode mode = st.touch.mode;
	double x = st.touch.x, y = st.touch.y;
	st.touch.mode = TOUCH_NONE;
	touch_stop_hold();
	switch (mode) {
	case TOUCH_PENDING:
		touch_unpress();
		if (cancel) {
			break;
		}
		/* A tap: a click where it landed */
		if (st.touch.in_search) {
			search_press(st.touch.x0, st.touch.y0, C8UI_BUTTON_LEFT);
		} else if (st.touch.in_apps) {
			apps_press(st.touch.x0, st.touch.y0, C8UI_BUTTON_LEFT);
		} else if (pointer_press(st.touch.x0, st.touch.y0,
				C8UI_BUTTON_LEFT)) {
			pointer_release(x, y);
		}
		break;
	case TOUCH_PAN_X: {
		/* Let go while moving: it coasts on */
		double v = time - st.touch.last_time > TOUCH_REST_MS || cancel ?
			0 : -st.touch.vx;
		fling_page(st.touch.in_search, st.touch.in_apps, v);
		break;
	}
	case TOUCH_PAN_Y:
		apps_drag_end();
		break;
	case TOUCH_HELD:
		if (st.grab == GRAB_DRAG) {
			pointer_release(x, y);
		} else {
			/* Held without moving: just the selection */
			drop_grab();
		}
		break;
	default:
		break;
	}
	st.touch.tile = NULL;
}

/* Keyboard */

static void set_focus(struct tile *tile) {
	if (st.focus == tile) {
		return;
	}
	if (st.focus) {
		st.focus->focused = false;
	}
	st.focus = tile;
	if (tile) {
		tile->focused = true;
		scroll_into_view(tile);
	}
	redraw();
}

static void move_focus(int dx, int dy) {
	struct tile *from = st.focus;
	struct group *group;
	struct tile *tile;
	if (from == NULL) {
		for_each_tile(group, tile) {
			set_focus(tile);
			return;
		}
		return;
	}
	struct tile *best = NULL;
	double best_score = INFINITY;
	for_each_tile(group, tile) {
		if (tile == from) {
			continue;
		}
		double score = focus_distance(&from->box, &tile->box, dx, dy);
		if (score < best_score) {
			best_score = score;
			best = tile;
		}
	}
	if (best) {
		set_focus(best);
	}
}

static bool menu_key(uint32_t sym) {
	int n = st.menu_count, i = st.menu_hover;
	switch (sym) {
	case XKB_KEY_Up:
		st.menu_hover = i <= 0 ? n - 1 : i - 1;
		break;
	case XKB_KEY_Down:
		st.menu_hover = i < 0 || i >= n - 1 ? 0 : i + 1;
		break;
	case XKB_KEY_Return:
	case XKB_KEY_KP_Enter:
	case XKB_KEY_space:
		if (i >= 0) {
			menu_action(st.menu[i].id);
		}
		break;
	default:
		show_menu(false);
		break;
	}
	redraw();
	return true;
}

static bool start_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 (selected_count() > 0) {
			clear_selection();
		} else if (st.bar_open || st.customise) {
			set_customise(false);
		} else {
			/* The compositor keeps Start up when there's no app */
			c8_shell_v1_set_start_visible(shell.proto, false);
		}
		return true;
	case XKB_KEY_Home:
		st.scroll_target = 0;
		animate();
		return true;
	case XKB_KEY_End:
		st.scroll_target = st.content_width;
		clamp_scroll();
		animate();
		return true;
	case XKB_KEY_Return:
	case XKB_KEY_KP_Enter:
		if (st.focus) {
			activate_tile(st.focus);
		}
		return true;
	case XKB_KEY_Delete:
		if (selected_count() > 0) {
			appbar_action(BUTTON_UNPIN);
		}
		return true;
	case XKB_KEY_space:
		if (st.focus) {
			toggle_selected(st.focus);
			return true;
		}
		break;
	}
	return false;
}

static bool key(const struct c8ui_event *ev) {
	if (st.menu_open) {
		return menu_key(ev->sym);
	}
	if (search_active()) {
		return search_key(ev);
	}
	if (st.editing && !apps_active()) {
		return edit_key(ev);
	}
	if (ev->sym == XKB_KEY_Tab && (ev->mods & C8UI_MOD_CTRL)) {
		start_open_apps();
		apps_show(!apps_active());
		return true;
	}
	if (apps_active() ? apps_key(ev) : start_key(ev)) {
		return true;
	}
	/* Typing, on Start or All apps alike, is a search */
	if ((ev->mods & (C8UI_MOD_CTRL | C8UI_MOD_SUPER | C8UI_MOD_ALT)) ||
			ev->text == NULL || (unsigned char)ev->text[0] <= 0x20 ||
			ev->text[0] == 0x7f) {
		return false;
	}
	search_begin(ev->text);
	return true;
}

/* The widget */

static void start_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	*width = avail;
	*height = 0;
}

static void start_layout(struct c8ui_widget *w) {
	int width = (int)w->rect.width, height = (int)w->rect.height;
	if (width != st.width || height != st.height) {
		st.width = width;
		st.height = height;
		relayout();
		update_appbar();
		apps_resize(width, height);
		search_resize(width, height);
	}
}

static bool start_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	double x = ev->x - w->rect.x, y = ev->y - w->rect.y;
	switch (ev->type) {
	case C8UI_EVENT_MOTION:
		if (search_active()) {
			search_motion(x, y);
		} else if (!apps_active()) {
			pointer_motion(x, y);
		}
		return true;
	case C8UI_EVENT_PRESS:
		if (search_active()) {
			return search_press(x, y, ev->button);
		}
		if (apps_active()) {
			return apps_press(x, y, ev->button);
		}
		return pointer_press(x, y, ev->button);
	case C8UI_EVENT_RELEASE:
		if (search_active()) {
			search_release();
		} else if (!apps_active()) {
			pointer_release(x, y);
		}
		return true;
	case C8UI_EVENT_SCROLL:
		scroll(ev->dx, ev->dy, ev->precise);
		return true;
	case C8UI_EVENT_SCROLL_STOP:
		apps_drag_end();
		pad_lift();
		return true;
	case C8UI_EVENT_SWIPE_BEGIN:
	case C8UI_EVENT_SWIPE_UPDATE:
	case C8UI_EVENT_SWIPE_END: {
		/* Sideways on All apps changes tabs, like the headings */
		int step;
		bool took = c8ui_tab_swipe(&st.swipe, ev, &step);
		if (step && apps_active() && !search_active()) {
			apps_swipe(step);
		}
		return took;
	}
	case C8UI_EVENT_TOUCH_DOWN:
		touch_down(ev->touch_id, ev->time, x, y);
		return true;
	case C8UI_EVENT_TOUCH_MOTION:
		if (st.touch.mode != TOUCH_NONE && ev->touch_id == st.touch.id) {
			touch_motion(ev->time, x, y);
		}
		return true;
	case C8UI_EVENT_TOUCH_UP:
	case C8UI_EVENT_TOUCH_CANCEL:
		if (st.touch.mode != TOUCH_NONE && ev->touch_id == st.touch.id) {
			touch_up(ev->time, ev->type == C8UI_EVENT_TOUCH_CANCEL);
		}
		return true;
	case C8UI_EVENT_KEY:
		return key(ev);
	default:
		return false;
	}
}

struct c8ui_widget *start_widget(void) {
	return st.w;
}

static void start_destroy(struct c8ui_widget *w) {
	st.w = NULL;
}

static const struct c8ui_widget_impl start_impl = {
	.name = "start",
	.measure = start_measure,
	.layout = start_layout,
	.draw = start_draw,
	.event = start_event,
	.tick = start_tick,
	.tick_damages = true,
	.destroy = start_destroy,
};

/* From the rest of the shell */

void start_animate(void) {
	animate();
}

void start_redraw(void) {
	redraw();
}

void start_open_apps(void) {
	show_menu(false);
	set_customise(false);
	clear_selection(); // and the app bar with it
	search_end();
	if (st.grab == GRAB_DRAG) {
		commit_layout();
	}
	st.grab = GRAB_NONE;
	st.grab_tile = NULL;
}

void start_pinned(struct tile *tile) {
	relayout();
	tiles_save();
	tiles_style_windows();
	scroll_into_view(tile);
}

void start_unpin(struct tile *tile) {
	unpin(tile);
	commit_layout();
	tiles_style_windows();
}

void start_tile_changed(struct tile *tile) {
	redraw_tile(tile);
	if (st.w && !st.last_tick) {
		schedule_rotation(now_ms());
	}
}

void start_init(void) {
	tiles_load();
	st.surface = shell_surface_new(C8_SHELL_V1_ROLE_START);
	c8ui_window_set_background(shell_surface_window(st.surface),
		shell.appearance.background, shell.appearance.xr ? 0 : 1);
	st.w = c8ui_widget_new(&start_impl, NULL);
	st.w->fill = true;
	st.w->expand = true;
	c8ui_widget_set_scheme(st.w, C8UI_SCHEME_DARK);
	c8ui_root_set_child(shell_surface_root(st.surface), st.w);
	apps_init();
	search_init();
	watch_picture();
	login_picture_init();
	st.opened_at = now_ms();
	animate();
}

/* Start is hidden most of the time, behind an app. Once it has been for
 * a while it stops drawing and lets go of what's quick to make again: the
 * window's two buffers and the background, a screenful each, and All apps'
 * rows. The tiles' faces stay, so it comes back at once. */
#define REST_AFTER_S 10

static gboolean rest(gpointer data) {
	st.rest_timer = 0;
	if (shell.start_visible || st.surface == NULL) {
		return G_SOURCE_REMOVE;
	}
	c8ui_window_suspend(shell_surface_window(st.surface), true);
	g_clear_pointer(&st.bg, cairo_surface_destroy);
	apps_rest();
	malloc_trim(0);
	return G_SOURCE_REMOVE;
}

void start_visible_changed(void) {
	int64_t now = now_ms();
	st.closed_at = 0;
	g_clear_handle_id(&st.rest_timer, g_source_remove);
	if (st.surface) {
		c8ui_window_suspend(shell_surface_window(st.surface), false);
	}
	if (!shell.start_visible) {
		st.rest_timer = g_timeout_add_seconds(REST_AFTER_S, rest, NULL);
	}
	if (shell.start_visible) {
		st.opened_at = now;
		int i = 0;
		struct group *group;
		struct tile *tile;
		for_each_tile(group, tile) {
			tile_reset_rotation(tile, now, i++);
		}
		animate();
		return;
	}
	struct group *group;
	struct tile *tile;
	for_each_tile(group, tile) {
		tile->selected = tile->focused = tile->pressed = false;
		tile->tilt = (struct c8ui_tilt){ 0 };
	}
	apps_reset();
	search_end();
	set_customise(false);
	st.focus = NULL;
	st.grab = GRAB_NONE;
	st.grab_tile = NULL;
	show_menu(false);
	update_appbar();
	g_clear_handle_id(&st.rotate_timer, g_source_remove);
	if (shell.appearance.xr) {
		/* The compositor keeps Start up while this plays */
		st.closed_at = now;
		animate();
	}
}

void start_power_changed(void) {
	show_menu(false);
}

void start_windows_changed(void) {
	tiles_style_windows();
}

void start_appearance_changed(void) {
	c8ui_window_set_background(shell_surface_window(st.surface),
		shell.appearance.background, shell.appearance.xr ? 0 : 1);
	st.bg_dirty = true;
	struct group *group;
	struct tile *tile;
	for_each_tile(group, tile) {
		tile->face_dirty = true;
		/* The icon theme may have changed */
		c8ui_icon_destroy(tile->icon_image);
		tile->icon_image = NULL;
		tile->icon_loaded = false;
	}
	relayout(); // more tiles means smaller cells
	tiles_style_windows();
	apps_restyle();
	search_restyle();
	redraw();
}

void start_open_search(const char *text) {
	panels_close();
	c8_shell_v1_set_start_visible(shell.proto, true);
	show_menu(false);
	search_begin(text);
}

void start_action(enum c8_shell_v1_action action) {
	switch (action) {
	case C8_SHELL_V1_ACTION_START:
		panels_close();
		c8_shell_v1_set_start_visible(shell.proto, !shell.start_visible);
		break;
	case C8_SHELL_V1_ACTION_SEARCH:
		/* In an app with its own search, the app's */
		context_search();
		break;
	case C8_SHELL_V1_ACTION_APPS:
		panels_close();
		c8_shell_v1_set_start_visible(shell.proto, true);
		start_open_apps();
		apps_show(true);
		break;
	case C8_SHELL_V1_ACTION_VOLUME_UP:
	case C8_SHELL_V1_ACTION_VOLUME_DOWN:
	case C8_SHELL_V1_ACTION_VOLUME_MUTE:
	case C8_SHELL_V1_ACTION_MIC_MUTE:
	case C8_SHELL_V1_ACTION_BRIGHTNESS_UP:
	case C8_SHELL_V1_ACTION_BRIGHTNESS_DOWN:
	case C8_SHELL_V1_ACTION_MEDIA_PLAY_PAUSE:
	case C8_SHELL_V1_ACTION_MEDIA_NEXT:
	case C8_SHELL_V1_ACTION_MEDIA_PREVIOUS:
	case C8_SHELL_V1_ACTION_MEDIA_STOP:
		media_action(action);
		break;
	default:
		panels_action(action);
		break;
	}
}
