/*
 * The pinned tiles: groups, start.ini, the grid layout and drawing a
 * tile's face, static or live (live.c keeps the content, templates.c
 * draws it).
 */
#define _GNU_SOURCE
#include <errno.h>
#include <gio/gdesktopappinfo.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "shell.h"

#define FLIP_MS 600
#define ROTATE_MS 7000

struct wl_list tile_groups = { &tile_groups, &tile_groups };

static const char *size_names[] = {
	[TILE_SMALL] = "small",
	[TILE_MEDIUM] = "medium",
	[TILE_WIDE] = "wide",
	[TILE_LARGE] = "large",
};

static const char default_start_ini[] =
	"# cont8nuum start screen. Rewritten by c8-shell when you customise\n"
	"# Start; hand edits are fine while it isn't running.\n"
	"\n"
	"[group]\n"
	"tile = browser\n"
	"tile = files\n"
	"tile = terminal\n"
	"tile = personalise\n"
	"\n"
	"[group]\n"
	"tile = calendar\n"
	"tile = weather\n"
	"tile = nowplaying\n"
	"tile = clock\n"
	"tile = writer\n"
	"tile = battery\n"
	"tile = krita\n"
	"\n"
	"[group]\n"
	"tile = processor\n"
	"tile = memory\n"
	"tile = storage\n"
	"tile = power\n"
	"tile = network\n"
	"\n"
	"[tile browser]\n"
	"name = Web browser\n"
	"exec = @default browser\n"
	"icon = web-browser\n"
	"size = wide\n"
	"color = #0050ef\n"
	"\n"
	"[tile files]\n"
	"name = Files\n"
	"exec = @default files\n"
	"icon = system-file-manager\n"
	"size = medium\n"
	"color = #1ba1e2\n"
	"\n"
	"[tile terminal]\n"
	"name = Terminal\n"
	"exec = @terminal\n"
	"icon = utilities-terminal\n"
	"size = medium\n"
	"color = #2d004e\n"
	"\n"
	"[tile personalise]\n"
	"name = PC settings\n"
	"exec = c8-settings\n"
	"icon = preferences-desktop\n"
	"size = medium\n"
	"color = #6a00ff\n"
	"\n"
	"[tile calendar]\n"
	"name = Calendar\n"
	"icon = cont8nuum-calendar\n"
	"size = wide\n"
	"label = false\n"
	"exec = @default calendar\n"
	"provider = c8-widget calendar calendar\n"
	"\n"
	"[tile weather]\n"
	"name = Weather\n"
	"icon = cont8nuum-weather\n"
	"size = large\n"
	"label = false\n"
	"provider = c8-widget weather weather\n"
	"\n"
	"[tile clock]\n"
	"name = Clock\n"
	"icon = cont8nuum-clock\n"
	"size = medium\n"
	"provider = c8-widget clock clock\n"
	"\n"
	"[tile nowplaying]\n"
	"name = Now playing\n"
	"icon = cont8nuum-music\n"
	"size = wide\n"
	"provider = c8-widget nowplaying nowplaying\n"
	"\n"
	"[tile battery]\n"
	"name = Battery\n"
	"icon = cont8nuum-battery\n"
	"size = wide\n"
	"label = false\n"
	"provider = c8-widget battery battery\n"
	"\n"
	"[tile writer]\n"
	"name = Writer\n"
	"exec = libreoffice --writer\n"
	"icon = libreoffice-writer\n"
	"size = medium\n"
	"color = #2b579a\n"
	"\n"
	"[tile krita]\n"
	"name = Krita\n"
	"exec = krita\n"
	"icon = krita\n"
	"size = wide\n"
	"color = #d80073\n"
	"\n"
	"[tile processor]\n"
	"name = Processor\n"
	"icon = cont8nuum-processor\n"
	"size = wide\n"
	"provider = c8-widget processor processor\n"
	"\n"
	"[tile memory]\n"
	"name = Memory\n"
	"icon = cont8nuum-memory\n"
	"size = medium\n"
	"provider = c8-widget memory memory\n"
	"\n"
	"[tile storage]\n"
	"name = Storage\n"
	"icon = cont8nuum-storage\n"
	"size = medium\n"
	"provider = c8-widget storage storage\n"
	"\n"
	"[tile network]\n"
	"name = Network\n"
	"icon = cont8nuum-network\n"
	"size = medium\n"
	"color = #008a00\n"
	"label = false\n"
	"provider = c8-widget network network\n"
	"\n"
	"[tile power]\n"
	"name = Power mode\n"
	"icon = cont8nuum-power-mode\n"
	"size = wide\n"
	"provider = c8-widget power power\n";

const char *tile_size_name(enum tile_size size) {
	return size_names[size];
}

/* The model */

struct group *group_create_before(struct group *next, const char *name) {
	struct group *group = calloc(1, sizeof(*group));
	group->name = strdup(name ? name : "");
	wl_list_init(&group->tiles);
	wl_list_insert(next ? next->link.prev : tile_groups.prev, &group->link);
	return group;
}

struct group *group_create(const char *name) {
	return group_create_before(NULL, name);
}

void group_set_name(struct group *group, const char *name) {
	free(group->name);
	group->name = strdup(name ? name : "");
}

static void group_destroy(struct group *group) {
	struct tile *tile, *tmp;
	wl_list_for_each_safe(tile, tmp, &group->tiles, link) {
		tile_destroy(tile);
	}
	wl_list_remove(&group->link);
	free(group->name);
	free(group);
}

void groups_prune(void) {
	struct group *group, *tmp;
	wl_list_for_each_safe(group, tmp, &tile_groups, link) {
		if (wl_list_empty(&group->tiles)) {
			group_destroy(group);
		}
	}
}

struct tile *tile_find(const char *id) {
	struct group *group;
	struct tile *tile;
	for_each_tile(group, tile) {
		if (strcmp(tile->id, id) == 0) {
			return tile;
		}
	}
	return NULL;
}

struct tile *tile_find_exec(const char *exec) {
	struct group *group;
	struct tile *tile;
	for_each_tile(group, tile) {
		if (tile->exec && strcmp(tile->exec, exec) == 0) {
			return tile;
		}
	}
	return NULL;
}

struct tile *tile_create(struct group *group, const char *id) {
	struct tile *tile = calloc(1, sizeof(*tile));
	tile->group = group;
	tile->id = strdup(id);
	tile->size = TILE_MEDIUM;
	tile->label = true;
	tile->live_enabled = true;
	tile->flip = 1;
	tile->alpha = 1;
	tile->face_dirty = true;
	wl_list_insert(group->tiles.prev, &tile->link);
	return tile;
}

void tile_destroy(struct tile *tile) {
	wl_list_remove(&tile->link);
	c8ui_icon_destroy(tile->icon_image);
	g_clear_pointer(&tile->flip_from, cairo_surface_destroy);
	g_clear_pointer(&tile->flip_to, cairo_surface_destroy);
	if (tile->face) {
		cairo_surface_destroy(tile->face);
	}
	free(tile->id);
	free(tile->name);
	free(tile->exec);
	free(tile->icon);
	free(tile->provider);
	free(tile->image);
	free(tile->wide_image);
	if (tile->image_s) {
		cairo_surface_destroy(tile->image_s);
	}
	if (tile->wide_s) {
		cairo_surface_destroy(tile->wide_s);
	}
	free(tile);
}

void tile_size_cells(enum tile_size size, int *w, int *h) {
	static const int cells[][2] = {
		[TILE_SMALL] = { 1, 1 },
		[TILE_MEDIUM] = { 2, 2 },
		[TILE_WIDE] = { 4, 2 },
		[TILE_LARGE] = { 4, 4 },
	};
	*w = cells[size][0];
	*h = cells[size][1];
}

int tile_cell(void) {
	return shell.appearance.more_tiles ? 56 : 70;
}

static bool entry_color(const char *id, uint32_t *rgb);

uint32_t tile_color(struct tile *tile) {
	uint32_t rgb;
	if (tile->has_color) {
		return tile->color;
	}
	/* Not said for the tile: its app's own, if its desktop entry (or its
	 * widget file) has one */
	return tile->id && entry_color(tile->id, &rgb) ? rgb :
		shell.appearance.accent;
}

bool tile_is_live(struct tile *tile) {
	return tile->live_enabled && shell.appearance.live_tiles &&
		tile->size != TILE_SMALL;
}

/* start.ini */

static char *start_ini_path(void) {
	char *path;
	if (asprintf(&path, "%s/start.ini", shell.config_dir) < 0) {
		return NULL;
	}
	return path;
}

static bool parse_bool(const char *s) {
	return strcmp(s, "true") == 0 || strcmp(s, "yes") == 0 ||
		strcmp(s, "1") == 0;
}

static char *trim(char *s) {
	while (*s == ' ' || *s == '\t') {
		s++;
	}
	char *end = s + strlen(s);
	while (end > s && (end[-1] == ' ' || end[-1] == '\t' ||
			end[-1] == '\n' || end[-1] == '\r')) {
		*--end = '\0';
	}
	return s;
}

static void parse_line(char *line, struct group **group, struct tile **tile,
		bool *in_group) {
	line = trim(line);
	if (line[0] == '\0' || line[0] == '#' || line[0] == ';') {
		return;
	}
	if (line[0] == '[') {
		char *end = strchr(line, ']');
		if (end == NULL) {
			return;
		}
		*end = '\0';
		char *section = line + 1;
		*tile = NULL;
		*in_group = false;
		if (strncmp(section, "group", 5) == 0 &&
				(section[5] == '\0' || section[5] == ' ')) {
			*group = group_create(section[5] ? trim(section + 6) : "");
			*in_group = true;
		} else if (strncmp(section, "tile ", 5) == 0) {
			const char *id = trim(section + 5);
			*tile = tile_find(id);
			if (*tile == NULL) {
				if (*group == NULL) {
					*group = group_create("");
				}
				*tile = tile_create(*group, id);
			}
		}
		return;
	}
	char *eq = strchr(line, '=');
	if (eq == NULL) {
		return;
	}
	*eq = '\0';
	char *key = trim(line), *value = trim(eq + 1);
	if (*in_group) {
		if (strcmp(key, "tile") == 0 && value[0] && tile_find(value) == NULL) {
			tile_create(*group, value);
		}
		return;
	}
	struct tile *t = *tile;
	if (t == NULL) {
		return; // [appearance] from before it moved to config.ini, say
	}
	if (strcmp(key, "name") == 0) {
		set_str(&t->name, value);
	} else if (strcmp(key, "exec") == 0) {
		set_str(&t->exec, value);
	} else if (strcmp(key, "icon") == 0) {
		set_str(&t->icon, value);
	} else if (strcmp(key, "provider") == 0) {
		set_str(&t->provider, value);
	} else if (strcmp(key, "image") == 0) {
		set_str(&t->image, value);
	} else if (strcmp(key, "wide_image") == 0) {
		set_str(&t->wide_image, value);
	} else if (strcmp(key, "color") == 0) {
		t->has_color = c8ui_parse_color(value, &t->color);
	} else if (strcmp(key, "live") == 0) {
		t->live_enabled = parse_bool(value);
	} else if (strcmp(key, "label") == 0) {
		t->label = parse_bool(value);
	} else if (strcmp(key, "secondary") == 0) {
		t->secondary = parse_bool(value);
	} else if (strcmp(key, "pos") == 0) {
		/* From before tiles flowed in order: only sorts them, once */
		t->has_pos = sscanf(value, "%d,%d", &t->pos_col, &t->pos_row) == 2 &&
			t->pos_col >= 0 && t->pos_row >= 0;
	} else if (strcmp(key, "size") == 0) {
		for (int i = 0; i <= TILE_LARGE; i++) {
			if (strcmp(value, size_names[i]) == 0) {
				t->size = i;
			}
		}
	}
}

static void parse(FILE *f) {
	struct group *group = NULL;
	struct tile *tile = NULL;
	bool in_group = false;
	char *line = NULL;
	size_t cap = 0;
	while (getline(&line, &cap, f) >= 0) {
		parse_line(line, &group, &tile, &in_group);
	}
	free(line);
}

static int mkdir_p(const char *dir) {
	char *copy = strdup(dir);
	for (char *p = copy + 1; *p; p++) {
		if (*p == '/') {
			*p = '\0';
			mkdir(copy, 0755);
			*p = '/';
		}
	}
	int ret = mkdir(copy, 0755) == 0 || errno == EEXIST ? 0 : -1;
	free(copy);
	return ret;
}

/* Cells from when tiles could go anywhere (pos = in start.ini): the
 * order that reads the same, band by band, top to bottom. Tiles without
 * one go after, as listed. */
struct pos_sort {
	struct tile *tile;
	long key;
};

static int pos_cmp(const void *a, const void *b) {
	const struct pos_sort *pa = a, *pb = b;
	return pa->key < pb->key ? -1 : pa->key > pb->key;
}

static void order_by_pos(void) {
	struct group *group;
	wl_list_for_each(group, &tile_groups, link) {
		int n = wl_list_length(&group->tiles), i = 0;
		struct pos_sort *sort = calloc(n + 1, sizeof(*sort));
		struct tile *tile, *tmp;
		wl_list_for_each(tile, &group->tiles, link) {
			long band = tile->pos_col / BAND_CELLS;
			sort[i].tile = tile;
			sort[i].key = tile->has_pos ? (band * 1000 + tile->pos_row) *
				1000 + tile->pos_col % BAND_CELLS : 1000000000L;
			sort[i].key = sort[i].key * 1000 + i; // keeps ties as listed
			i++;
		}
		qsort(sort, n, sizeof(*sort), pos_cmp);
		wl_list_for_each_safe(tile, tmp, &group->tiles, link) {
			wl_list_remove(&tile->link);
		}
		for (i = 0; i < n; i++) {
			wl_list_insert(group->tiles.prev, &sort[i].tile->link);
			sort[i].tile->has_pos = false;
		}
		free(sort);
	}
}

void tiles_load(void) {
	char *path = start_ini_path();
	FILE *f = path ? fopen(path, "r") : NULL;
	if (f == NULL && path && mkdir_p(shell.config_dir) == 0) {
		FILE *out = fopen(path, "w");
		if (out) {
			fputs(default_start_ini, out);
			fclose(out);
		}
		f = fopen(path, "r");
	}
	if (f == NULL) {
		/* Nowhere to keep it: start from the defaults anyway */
		f = fmemopen((void *)default_start_ini, strlen(default_start_ini),
			"r");
	}
	if (f) {
		parse(f);
		fclose(f);
	}
	free(path);
	groups_prune();
	order_by_pos();
	live_tiles_changed();
}

void tiles_save(void) {
	char *path = start_ini_path(), *tmp = NULL;
	if (path == NULL || mkdir_p(shell.config_dir) != 0 ||
			asprintf(&tmp, "%s.tmp", path) < 0) {
		fprintf(stderr, "c8-shell: cannot save start.ini\n");
		free(path);
		return;
	}
	FILE *f = fopen(tmp, "w");
	if (f == NULL) {
		fprintf(stderr, "c8-shell: cannot write %s: %s\n", tmp,
			strerror(errno));
		free(path);
		free(tmp);
		return;
	}
	fprintf(f, "# cont8nuum start screen. Rewritten by c8-shell when you "
		"customise\n# Start; hand edits are fine while it isn't running.\n");
	struct group *group;
	struct tile *tile;
	wl_list_for_each(group, &tile_groups, link) {
		if (wl_list_empty(&group->tiles)) {
			continue;
		}
		fprintf(f, "\n[group%s%s]\n", group->name[0] ? " " : "",
			group->name);
		wl_list_for_each(tile, &group->tiles, link) {
			fprintf(f, "tile = %s\n", tile->id);
		}
	}
	for_each_tile(group, tile) {
		fprintf(f, "\n[tile %s]\n", tile->id);
		if (tile->name) {
			fprintf(f, "name = %s\n", tile->name);
		}
		if (tile->exec) {
			fprintf(f, "exec = %s\n", tile->exec);
		}
		if (tile->icon) {
			fprintf(f, "icon = %s\n", tile->icon);
		}
		fprintf(f, "size = %s\n", size_names[tile->size]);
		if (tile->has_color) {
			fprintf(f, "color = #%06x\n", tile->color & 0xffffff);
		}
		if (!tile->live_enabled) {
			fprintf(f, "live = false\n");
		}
		if (!tile->label) {
			fprintf(f, "label = false\n");
		}
		if (tile->provider) {
			fprintf(f, "provider = %s\n", tile->provider);
		}
		if (tile->image) {
			fprintf(f, "image = %s\n", tile->image);
		}
		if (tile->wide_image) {
			fprintf(f, "wide_image = %s\n", tile->wide_image);
		}
		if (tile->secondary) {
			fprintf(f, "secondary = true\n");
		}
	}
	if (fclose(f) != 0 || rename(tmp, path) != 0) {
		fprintf(stderr, "c8-shell: cannot save %s: %s\n", path,
			strerror(errno));
		unlink(tmp);
	}
	free(path);
	free(tmp);
	/* Every change to the tiles is saved: the bus hears of it here */
	live_tiles_changed();
}

struct tile *tile_pin_secondary(const char *id, const char *name,
		const char *exec, const char *icon, bool has_color, uint32_t color,
		enum tile_size size) {
	struct group *group;
	if (wl_list_empty(&tile_groups)) {
		group = group_create("");
	} else {
		group = wl_container_of(tile_groups.prev, group, link);
	}
	struct tile *tile = tile_create(group, id);
	set_str(&tile->name, name);
	set_str(&tile->exec, exec);
	if (icon && icon[0]) {
		set_str(&tile->icon, icon);
	}
	tile->has_color = has_color;
	tile->color = color;
	tile->size = size;
	tile->secondary = true;
	return tile;
}

void tiles_launch_providers(void) {
	struct group *group;
	struct tile *tile;
	for_each_tile(group, tile) {
		live_restart_provider(tile);
	}
}

/* Layout */

/*
 * Windows 8's packing: each group is `rows` cells tall and its tiles flow
 * in order into column-bands four cells wide, each taking the first gap
 * that fits it (so small and medium tiles fill in beside each other and
 * no holes are left). Only the order is kept, never a cell: moving a
 * tile means putting it somewhere else in the order.
 */

struct grid {
	bool *occ;
	int cols, rows;
};

static bool grid_free(struct grid *g, int c, int r, int cw, int ch) {
	if (c < 0 || r < 0 || c + cw > g->cols || r + ch > g->rows) {
		return false;
	}
	for (int dy = 0; dy < ch; dy++) {
		for (int dx = 0; dx < cw; dx++) {
			if (g->occ[(r + dy) * g->cols + c + dx]) {
				return false;
			}
		}
	}
	return true;
}

static void grid_fill(struct grid *g, int c, int r, int cw, int ch) {
	for (int dy = 0; dy < ch; dy++) {
		for (int dx = 0; dx < cw; dx++) {
			g->occ[(r + dy) * g->cols + c + dx] = true;
		}
	}
}

/* The first gap that fits, reading band by band, top to bottom, left to
 * right */
static bool place_first(struct grid *g, int cw, int ch, int *pc, int *pr) {
	for (int band = 0; band * BAND_CELLS < g->cols; band++) {
		for (int r = 0; r + ch <= g->rows; r++) {
			for (int c = band * BAND_CELLS;
					c + cw <= (band + 1) * BAND_CELLS; c++) {
				if (grid_free(g, c, r, cw, ch)) {
					*pc = c;
					*pr = r;
					return true;
				}
			}
		}
	}
	return false;
}

static void tile_cells(struct tile *tile, int rows, int *cw, int *ch) {
	tile_size_cells(tile->size, cw, ch);
	if (*ch > rows) {
		*ch = rows;
	}
}

/* Packs tiles[0..n) in order, setting their col and row; returns the
 * columns used */
static int pack(struct tile **tiles, int n, int rows) {
	/* A band per tile is always enough */
	struct grid grid = { .rows = rows, .cols = BAND_CELLS * (n + 1) };
	grid.occ = calloc((size_t)rows * grid.cols, sizeof(bool));
	int used = 0;
	for (int i = 0; i < n; i++) {
		int cw, ch, c = 0, r = 0;
		tile_cells(tiles[i], rows, &cw, &ch);
		if (place_first(&grid, cw, ch, &c, &r)) {
			grid_fill(&grid, c, r, cw, ch);
		}
		tiles[i]->col = c;
		tiles[i]->row = r;
		if (c + cw > used) {
			used = c + cw;
		}
	}
	free(grid.occ);
	return used;
}

static struct tile **group_array(struct group *group, int *n) {
	*n = wl_list_length(&group->tiles);
	struct tile **tiles = calloc(*n + 1, sizeof(*tiles));
	struct tile *tile;
	int i = 0;
	wl_list_for_each(tile, &group->tiles, link) {
		tiles[i++] = tile;
	}
	return tiles;
}

static void layout_group(struct group *group, int x, int rows, int cell) {
	int pitch = cell + TILE_GAP;
	int n;
	struct tile **tiles = group_array(group, &n);
	int used = pack(tiles, n, rows);
	free(tiles);

	struct tile *tile;
	wl_list_for_each(tile, &group->tiles, link) {
		int cw, ch;
		tile_cells(tile, rows, &cw, &ch);
		int w = cw * cell + (cw - 1) * TILE_GAP;
		int h = ch * cell + (ch - 1) * TILE_GAP;
		if (w != tile->box.width || h != tile->box.height) {
			tile->face_dirty = true;
		}
		tile->box = (struct rect){
			.x = x + tile->col * pitch,
			.y = START_TILES_Y + tile->row * pitch,
			.width = w,
			.height = h,
		};
		if (!tile->placed) {
			tile->cur_x = tile->box.x;
			tile->cur_y = tile->box.y;
			tile->placed = true;
		}
	}
	group->x = x;
	group->width = used > 0 ? used * pitch - TILE_GAP : 0;
}

int tiles_layout(int rows) {
	int cell = tile_cell();
	int x = START_MARGIN_X;
	struct group *group;
	wl_list_for_each(group, &tile_groups, link) {
		layout_group(group, x, rows, cell);
		if (group->width > 0) {
			x += group->width + GROUP_GAP;
		}
	}
	return x - GROUP_GAP + START_MARGIN_X;
}

int tiles_drop_index(struct group *group, struct tile *tile, int rows,
		double left, double top) {
	int pitch = tile_cell() + TILE_GAP;
	int n;
	struct tile **all = group_array(group, &n);
	/* The others, in order, with a slot for it */
	struct tile **tiles = calloc(n + 1, sizeof(*tiles));
	int others = 0, current = -1;
	for (int i = 0; i < n; i++) {
		if (all[i] == tile) {
			current = others;
		} else {
			all[others++] = all[i];
		}
	}
	int best = others;
	double best_d = INFINITY;
	for (int at = 0; at <= others; at++) {
		memcpy(tiles, all, at * sizeof(*tiles));
		tiles[at] = tile;
		memcpy(tiles + at + 1, all + at, (others - at) * sizeof(*tiles));
		pack(tiles, others + 1, rows);
		double dx = group->x + tile->col * pitch - left;
		double dy = START_TILES_Y + tile->row * pitch - top;
		double d = hypot(dx, dy);
		/* Where it is wins a near tie, so it doesn't flicker between two */
		if (at == current) {
			d -= pitch / 4.0;
		}
		if (d < best_d) {
			best_d = d;
			best = at;
		}
	}
	free(tiles);
	free(all);
	return best;
}

void tile_move(struct tile *tile, struct group *group, int index) {
	wl_list_remove(&tile->link);
	struct wl_list *before = &group->tiles;
	struct tile *t;
	int i = 0;
	wl_list_for_each(t, &group->tiles, link) {
		if (i++ == index) {
			before = &t->link;
			break;
		}
	}
	wl_list_insert(before->prev, &tile->link);
	tile->group = group;
}

/* The name of the program a command runs, without its folder or its
 * arguments; *len is how long it is (it isn't terminated) */
static const char *exec_base(const char *exec, size_t *len) {
	size_t end = strcspn(exec, " \t");
	const char *base = exec;
	for (const char *p = exec; p < exec + end; p++) {
		if (*p == '/') {
			base = p + 1;
		}
	}
	*len = end - (base - exec);
	return base;
}

/* Drawing */

static void load_icon(struct tile *tile) {
	if (tile->icon_loaded) {
		return;
	}
	tile->icon_loaded = true;
	const char *theme = shell.appearance.icon_theme;
	tile->icon_image = c8ui_icon_load(theme, tile->icon);
	if (tile->icon_image == NULL && tile->exec && tile->exec[0] != '@') {
		/* The command's name often is an icon's */
		char name[256];
		size_t len;
		const char *base = exec_base(tile->exec, &len);
		if (len < sizeof(name)) {
			memcpy(name, base, len);
			name[len] = '\0';
			tile->icon_image = c8ui_icon_load(theme, name);
		}
	}
}

static void tile_draw_icon(cairo_t *cr, const char *family, struct tile *tile,
		double cx, double cy, double size) {
	load_icon(tile);
	if (tile->icon_image) {
		c8ui_icon_draw_fit(cr, tile->icon_image, cx, cy, size);
		return;
	}
	/* No icon: short icon strings are glyphs, otherwise an initial */
	char glyph[16] = "";
	if (tile->icon && strlen(tile->icon) <= 4 && tile->icon[0] != '/') {
		snprintf(glyph, sizeof(glyph), "%s", tile->icon);
	} else if (tile->name && tile->name[0]) {
		size_t len = 1;
		while (len < 4 && (tile->name[len] & 0xc0) == 0x80) {
			len++;
		}
		memcpy(glyph, tile->name, len);
		glyph[len] = '\0';
	}
	struct c8ui_font font = { size, 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 double icon_size(struct tile *tile, int h) {
	switch (tile->size) {
	case TILE_SMALL:
		return h * 0.55;
	case TILE_LARGE:
		return h * 0.3;
	default:
		return h * 0.4;
	}
}

/* The tile's own picture for its size: the wide one when wide (else the
 * other), loaded once */
static cairo_surface_t *tile_picture(struct tile *tile) {
	if (!tile->image_loaded) {
		tile->image_loaded = true;
		tile->image_s = tile->image ? live_load_image(tile->image) : NULL;
	}
	if (!tile->wide_loaded) {
		tile->wide_loaded = true;
		tile->wide_s = tile->wide_image ? live_load_image(tile->wide_image) :
			NULL;
	}
	if (tile->size == TILE_WIDE && tile->wide_s) {
		return tile->wide_s;
	}
	return tile->image_s ? tile->image_s : tile->wide_s;
}

void tile_restyle(struct tile *tile) {
	c8ui_icon_destroy(tile->icon_image);
	tile->icon_image = NULL;
	tile->icon_loaded = false;
	if (tile->image_s) {
		cairo_surface_destroy(tile->image_s);
		tile->image_s = NULL;
	}
	if (tile->wide_s) {
		cairo_surface_destroy(tile->wide_s);
		tile->wide_s = NULL;
	}
	tile->image_loaded = tile->wide_loaded = false;
	tile->face_dirty = true;
}

static void draw_static(cairo_t *cr, const char *family, struct tile *tile,
		int w, int h) {
	cairo_surface_t *pic = tile_picture(tile);
	if (pic) {
		c8ui_draw_surface_cover(cr, pic, 0, 0, w, h);
		if (tile->label && tile->size != TILE_SMALL) {
			/* So the name reads over a light picture */
			cairo_pattern_t *g = cairo_pattern_create_linear(0, h - 44, 0, h);
			cairo_pattern_add_color_stop_rgba(g, 0, 0, 0, 0, 0);
			cairo_pattern_add_color_stop_rgba(g, 1, 0, 0, 0, 0.55);
			cairo_set_source(cr, g);
			cairo_rectangle(cr, 0, h - 44, w, 44);
			cairo_fill(cr);
			cairo_pattern_destroy(g);
		}
		return;
	}
	double cy = h / 2.0;
	if (tile->label && tile->size != TILE_SMALL) {
		cy -= 8;
	}
	tile_draw_icon(cr, family, tile, w / 2.0, cy, icon_size(tile, h));
}

/* The face for one slide: its colour (none for stats) and content */
static void draw_one_slide(cairo_t *cr, const char *family, struct tile *tile,
		int index, int w, int h) {
	if (!tile_slide_clear(tile, index)) {
		c8ui_set_source(cr, tile_slide_color(tile, index), 1);
		cairo_rectangle(cr, 0, 0, w, h);
		cairo_fill(cr);
	}
	tile_draw_slide(cr, family, tile, index, w, h);
}

/* The name and badge, part of the face so their text isn't laid out
 * again every frame */
static void draw_label(cairo_t *cr, const char *family, struct tile *tile,
		int w, int h) {
	struct live *live = live_find(tile->id);
	const char *badge = live && (tile_is_live(tile) ||
		tile->size == TILE_SMALL) ? live->badge : NULL;
	int slides = tile_slide_count(tile);
	const char *label = tile_label(tile, slides ? tile->slide % slides : 0);
	if (label) {
		int max = w - 2 * 10 - (badge ? 40 : 0);
		cairo_set_source_rgb(cr, 1, 1, 1);
		c8ui_text_draw(cr, family, (struct c8ui_font){ 13,
			C8UI_WEIGHT_NORMAL }, label, 10, h - 26, max, 1);
	}
	if (badge) {
		bool small = tile->size == TILE_SMALL;
		struct c8ui_font font = { small ? 13 : 16, C8UI_WEIGHT_SEMIBOLD };
		double tw, th;
		c8ui_text_size(family, font, badge, 0, 0, &tw, &th);
		cairo_set_source_rgb(cr, 1, 1, 1);
		c8ui_text_draw(cr, family, font, badge, w - tw - (small ? 5 : 10),
			h - th - (small ? 2 : 6), 0, 0);
	}
}

static cairo_surface_t *slide_surface(cairo_t *cr, const char *family,
		struct tile *tile, int index, int w, int h) {
	cairo_surface_t *s = cairo_surface_create_similar(cairo_get_target(cr),
		CAIRO_CONTENT_COLOR_ALPHA, w, h);
	cairo_t *scr = cairo_create(s);
	draw_one_slide(scr, family, tile, index, w, h);
	cairo_destroy(scr);
	return s;
}

static void drop_flip(struct tile *tile) {
	g_clear_pointer(&tile->flip_from, cairo_surface_destroy);
	g_clear_pointer(&tile->flip_to, cairo_surface_destroy);
}

static void draw_face(cairo_t *cr, const char *family, struct tile *tile,
		int w, int h) {
	cairo_save(cr);
	cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
	cairo_paint(cr);
	cairo_restore(cr);
	int slides = tile_slide_count(tile);
	if (slides == 0) {
		c8ui_set_source(cr, tile_color(tile), 1);
		cairo_paint(cr);
		draw_static(cr, family, tile, w, h);
	} else if (tile->flip < 1) {
		/* The next slide pushes the last one up. Both are drawn once,
		 * when the flip starts (or what they show changes), and only
		 * moved for the frames after */
		if (tile->flip_from == NULL) {
			tile->flip_from = slide_surface(cr, family, tile,
				tile->prev_slide % slides, w, h);
			tile->flip_to = slide_surface(cr, family, tile,
				tile->slide % slides, w, h);
		}
		/* By whole pixels, so they are copied, not filtered */
		double sx, sy;
		cairo_surface_get_device_scale(cairo_get_target(cr), &sx, &sy);
		double up = round(h * ease_in_out(tile->flip) * sy) / sy;
		cairo_save(cr);
		cairo_rectangle(cr, 0, 0, w, h);
		cairo_clip(cr);
		cairo_set_source_surface(cr, tile->flip_from, 0, -up);
		cairo_paint(cr);
		cairo_set_source_surface(cr, tile->flip_to, 0, h - up);
		cairo_paint(cr);
		cairo_restore(cr);
	} else {
		draw_one_slide(cr, family, tile, tile->slide % slides, w, h);
	}
	draw_label(cr, family, tile, w, h);
}

/* Over the face: what changes with input, not with content */
static void draw_overlay(cairo_t *cr, struct tile *tile, int w, int h) {
	if (tile->pressed) {
		cairo_set_source_rgba(cr, 0, 0, 0, 0.18);
		cairo_rectangle(cr, 0, 0, w, h);
		cairo_fill(cr);
	}
	if (tile->selected) {
		uint32_t mark = c8ui_shade(shell.appearance.accent, 1.25);
		c8ui_set_source(cr, mark, 1);
		cairo_set_line_width(cr, 4);
		cairo_rectangle(cr, 2, 2, w - 4, h - 4);
		cairo_stroke(cr);
		cairo_move_to(cr, w - 36, 0);
		cairo_line_to(cr, w, 0);
		cairo_line_to(cr, w, 36);
		cairo_close_path(cr);
		cairo_fill(cr);
		cairo_set_source_rgb(cr, 1, 1, 1);
		cairo_set_line_width(cr, 2);
		cairo_move_to(cr, w - 20, 9);
		cairo_line_to(cr, w - 15, 14);
		cairo_line_to(cr, w - 6, 5);
		cairo_stroke(cr);
	} else if (tile->focused) {
		cairo_set_source_rgb(cr, 1, 1, 1);
		cairo_set_line_width(cr, 3);
		cairo_rectangle(cr, 1.5, 1.5, w - 3, h - 3);
		cairo_stroke(cr);
	}
}

void tile_draw(cairo_t *cr, struct c8ui_widget *w, struct tile *tile,
		double x, double y) {
	const char *family = c8ui_widget_font(w);
	int tw = tile->box.width, th = tile->box.height;
	if (tw <= 0 || th <= 0) {
		return;
	}
	/* The face is kept as an image: icons and text cost too much to
	 * redraw every frame of a scroll */
	cairo_surface_t *target = cairo_get_target(cr);
	double sx, sy;
	cairo_surface_get_device_scale(target, &sx, &sy);
	if (tile->face == NULL || tile->face_w != tw || tile->face_h != th ||
			tile->face_scale != sx) {
		if (tile->face) {
			cairo_surface_destroy(tile->face);
		}
		tile->face = cairo_surface_create_similar(target,
			CAIRO_CONTENT_COLOR_ALPHA, tw, th);
		tile->face_w = tw;
		tile->face_h = th;
		tile->face_scale = sx;
		tile->face_dirty = true;
	}
	if (tile->face_dirty) {
		/* Something it shows changed: the flip's slides too */
		drop_flip(tile);
	}
	if (tile->face_dirty || tile->flip_moved) {
		cairo_t *fcr = cairo_create(tile->face);
		draw_face(fcr, family, tile, tw, th);
		cairo_destroy(fcr);
		tile->face_dirty = tile->flip_moved = false;
	}
	/* Pressed, it sinks in (press_tile in start.c) */
	struct c8ui_rect at = { round(x), round(y), tw, th };
	double depth = c8ui_tilt_depth(&tile->tilt, c8ui_now());
	bool tilted = c8ui_tilt_begin(cr, &at, depth);
	cairo_save(cr);
	cairo_translate(cr, round(x), round(y));
	cairo_set_source_surface(cr, tile->face, 0, 0);
	cairo_paint_with_alpha(cr, tile->alpha);
	bool overlay = tile->pressed || tile->selected || tile->focused;
	if (overlay && tile->alpha >= 1) {
		draw_overlay(cr, tile, tw, th);
	} else if (overlay) {
		/* Clipped, or the group is as big as the whole screen */
		cairo_rectangle(cr, 0, 0, tw, th);
		cairo_clip(cr);
		cairo_push_group(cr);
		draw_overlay(cr, tile, tw, th);
		cairo_pop_group_to_source(cr);
		cairo_paint_with_alpha(cr, tile->alpha);
	}
	cairo_restore(cr);
	if (tilted) {
		c8ui_tilt_end(cr, &tile->tilt, &at, depth);
	}
}

/* Rotation through live content */

void tile_reset_rotation(struct tile *tile, int64_t now, int index) {
	tile->flip = 1;
	tile->next_rotate = now + 3000 + (index * 1300) % ROTATE_MS;
}

bool tile_tick(struct tile *tile, int64_t now) {
	if (tile->flip < 1) {
		tile->flip = (double)(now - tile->flip_start) / FLIP_MS;
		if (tile->flip >= 1) {
			tile->flip = 1;
			tile->face_dirty = true; // settled: drawn whole once more
		} else {
			tile->flip_moved = true;
		}
		return true;
	}
	int slides = tile_slide_count(tile);
	if (slides <= 1) {
		if (tile->slide != 0) {
			tile->slide = 0;
			tile->face_dirty = true;
		}
		return false;
	}
	if (now >= tile->next_rotate) {
		tile->prev_slide = tile->slide;
		tile->slide = (tile->slide + 1) % slides;
		tile->flip = 0;
		tile->flip_start = now;
		tile->next_rotate = now + ROTATE_MS;
		tile->face_dirty = true;
		return true;
	}
	return false;
}

/* Title bars wear the colour and icon of the app's tile */

/* What an app's desktop entry (named after its app id) says, read once:
 * toasts ask while they're drawn */
struct app_entry {
	char *exec; // its program's name, without the folder
	char *icon;
	bool has_color; // X-Cont8nuum-Color=: the app's own tile colour
	uint32_t color;
};

/* Programs that only start the real one: every Flatpak app's entry runs
 * "flatpak", so going by it gave each the first Flatpak tile's colour
 * and icon (VacuumTube wore Signal's) */
static bool runs_others(const char *program) {
	static const char *const names[] = { "flatpak", "snap", "env", "sh",
		"bash", "gtk-launch", "xdg-open", "steam", "lutris", "wine",
		"python", "python3", "java", "electron" };
	for (size_t i = 0; i < G_N_ELEMENTS(names); i++) {
		if (strcmp(program, names[i]) == 0) {
			return true;
		}
	}
	return false;
}

static struct app_entry *app_entry(const char *app_id) {
	static GHashTable *entries; // app id -> struct app_entry
	if (entries == NULL) {
		entries = g_hash_table_new(g_str_hash, g_str_equal);
	}
	struct app_entry *e = g_hash_table_lookup(entries, app_id);
	if (e) {
		return e;
	}
	e = g_new0(struct app_entry, 1);
	char *file = g_strconcat(app_id, ".desktop", NULL);
	GDesktopAppInfo *info = g_desktop_app_info_new(file);
	g_free(file);
	if (info) {
		const char *exe = g_app_info_get_executable(G_APP_INFO(info));
		e->exec = exe && exe[0] ? g_path_get_basename(exe) : NULL;
		if (e->exec && runs_others(e->exec)) {
			g_clear_pointer(&e->exec, g_free);
		}
		e->icon = g_desktop_app_info_get_string(info, "Icon");
		if (e->icon && e->icon[0] == '\0') {
			g_clear_pointer(&e->icon, g_free);
		}
		char *color = g_desktop_app_info_get_string(info, "X-Cont8nuum-Color");
		e->has_color = color && c8ui_parse_color(color, &e->color);
		g_free(color);
		g_object_unref(info);
	} else {
		/* Not an app's id: a live tile's, from a .widget file, which may
		 * say its colour too (tiles pinned before colours were said have
		 * none of their own) */
		char *name = g_strconcat("cont8nuum/widgets/", app_id, ".widget", NULL);
		GKeyFile *kf = g_key_file_new();
		bool found = g_key_file_load_from_data_dirs(kf, name, NULL,
			G_KEY_FILE_NONE, NULL);
		if (!found) {
			/* Ours, even when the prefix isn't in XDG_DATA_DIRS */
			char *path = g_build_filename(C8_DATADIR, name, NULL);
			found = g_key_file_load_from_file(kf, path, G_KEY_FILE_NONE, NULL);
			g_free(path);
		}
		char *color = found ? g_key_file_get_string(kf, "Widget", "Color",
			NULL) : NULL;
		e->has_color = color && c8ui_parse_color(color, &e->color);
		g_free(color);
		g_key_file_free(kf);
		g_free(name);
	}
	g_hash_table_insert(entries, g_strdup(app_id), e);
	return e;
}

static bool entry_color(const char *id, uint32_t *rgb) {
	struct app_entry *e = app_entry(id);
	*rgb = e->color;
	return e->has_color;
}

const char *app_entry_icon(const char *app_id) {
	return app_id ? app_entry(app_id)->icon : NULL;
}

/* The colour for an app's things (its window's title bar, its toasts):
 * its tile's, else what its desktop entry says, else the accent */
uint32_t app_color(const char *app_id) {
	struct tile *tile = tile_for_app(app_id);
	if (tile) {
		return tile_color(tile);
	}
	struct app_entry *e = app_id ? app_entry(app_id) : NULL;
	return e && e->has_color ? e->color : shell.appearance.accent;
}

/* The tile whose command runs the program name (of len bytes) */
static struct tile *tile_running(const char *name, size_t len) {
	struct group *group;
	struct tile *tile;
	for_each_tile(group, tile) {
		if (tile->exec == NULL || tile->exec[0] == '@') {
			continue;
		}
		size_t blen;
		const char *base = exec_base(tile->exec, &blen);
		if (len == blen && strncasecmp(name, base, blen) == 0) {
			return tile;
		}
	}
	return NULL;
}

struct tile *tile_for_app(const char *app_id) {
	if (app_id == NULL) {
		return NULL;
	}
	struct tile *tile = tile_find(app_id);
	if (tile == NULL) {
		/* Else a tile running the program: named like the app id, or
		 * as its desktop entry says (org.cont8nuum.Files is c8-files) */
		tile = tile_running(app_id, strlen(app_id));
	}
	const char *exec = tile ? NULL : app_entry(app_id)->exec;
	return exec ? tile_running(exec, strlen(exec)) : tile;
}

const char *app_icon_name(const char *app_id) {
	struct tile *tile = tile_for_app(app_id);
	const char *icon = tile && tile->icon ? tile->icon :
		app_entry_icon(app_id);
	return icon ? icon : app_id ? app_id : "";
}

void tiles_style_windows(void) {
	struct window *win;
	wl_list_for_each(win, &shell.windows, link) {
		uint32_t rgb = app_color(win->app_id);
		const char *icon = app_icon_name(win->app_id);
		if (win->styled && win->style_rgb == rgb && win->style_icon &&
				strcmp(win->style_icon, icon) == 0) {
			continue;
		}
		win->styled = true;
		win->style_rgb = rgb;
		free(win->style_icon);
		win->style_icon = strdup(icon);
		c8_shell_window_v1_set_style(win->proto, rgb, icon);
	}
}
