/*
 * c8-tiles, Tile maker: make your own Start tiles. A page list down the
 * side like PC settings: My tiles (each opens the editor: name, command,
 * icon, colour, size and a picture to fill it), Games (what Steam, Lutris
 * and the Game desktop entries have installed, each a tile in one click,
 * with art from SteamGridDB) and Settings (the SteamGridDB API key).
 *
 * Tiles go to Start through RequestPin as an app's own (secondary)
 * tiles: Start asks before pinning, and again whenever the command
 * changes; changes to the face alone are sent as they're made.
 */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include <c8ui/c8ui.h>
#include <c8ui/c8ui-charms.h>
#include <c8ui/c8ui-files.h>
#include <c8ui/c8ui-wayland.h>
#include "stealth.h"
#include "tiles.h"

#define PANE_WIDTH 300 // the page list, wide
#define ROW_H 72
#define CELL 70 // Start's tile cell and gap
#define GAP 8
#define SAVE_MS 500
#define PUSH_MS 700
#define ART_MAX 30 // per kind
#define KEY_URL "https://www.steamgriddb.com/profile/preferences/api"

enum page { PAGE_TILES, PAGE_GAMES, PAGE_SETTINGS, PAGE_COUNT };
static const char *const page_titles[PAGE_COUNT] = {
	"My tiles", "Games", "Settings",
};

static const uint32_t palette[] = {
	0xa4c400, 0x60a917, 0x008a00, 0x00aba9, 0x1ba1e2, 0x0050ef, 0x6a00ff,
	0xaa00ff, 0xf472d0, 0xd80073, 0xa20025, 0xe51400, 0xfa6800, 0xf0a30a,
	0xe3c800, 0x825a2c, 0x6d8764, 0x647687, 0x76608a, 0x87794e, 0xd24726,
	0x1e1e1e,
};

static struct {
	struct c8ui_app *app;
	struct c8ui_window *win;
	struct c8ui_root *root;
	struct c8ui_widget *pages; // the list of pages and the one showing
	struct c8ui_widget *content; // that page, until it's built again
	struct c8ui_widget *appbar;
	struct c8ui_charms *charms;
	GDBusConnection *bus;
	enum page page;
	bool page_given; // --page: open on it, narrow too

	/* My tiles */
	struct c8ui_widget *tiles_list;

	/* Games */
	GPtrArray *games; // struct tm_game, games.c's
	GPtrArray *shown; // the ones the search box lets through
	char *filter;
	bool scanning;
	struct c8ui_widget *games_list;

	/* The editor */
	char *edit; // the tile's id, NULL when not editing (a page over g.page)
	bool pinned;
	struct c8ui_widget *preview, *pin_button, *unpin_button, *note;
	struct c8ui_widget *app_entry, *sgdb_note, *sgdb_games;
	struct c8ui_widget *art_list[TM_ART_COUNT], *art_head[TM_ART_COUNT];
	GPtrArray *art[TM_ART_COUNT]; // struct tm_art_item
	GPtrArray *found; // struct tm_sgdb_game, the search's
	int art_serial; // drops answers for a tile no longer shown
	guint save_timer, push_timer;
	bool downloading;

	GPtrArray *apps; // GAppInfo, for "Start from an app"
	GPtrArray *suggestions; // strings, the app box's
	GHashTable *icons; // name -> struct c8ui_icon
	char *start_edit; // --edit ID: open on that tile
} g;

static void show(bool enter);
static void rebuild(void);

static struct c8ui_widget *row(void) {
	struct c8ui_widget *r = c8ui_box_new(C8UI_HORIZONTAL, 12);
	c8ui_box_set_wrap(r, true);
	return r;
}

/* A link in a row of buttons, centred on them */
static struct c8ui_widget *row_link(const char *text, c8ui_action_fn fn,
		void *data) {
	struct c8ui_widget *l = c8ui_link_new(text, fn, data);
	l->align = C8UI_ALIGN_CENTER;
	return l;
}
static void open_editor(struct tm_tile *t);
static void update_buttons(void);
static void load_art(struct tm_tile *t);

/* Saying things */

static void show_message(const char *title, const char *message) {
	c8ui_dialog_message(g.root, title, message);
}

static struct c8ui_widget *caption(const char *text) {
	struct c8ui_widget *l = c8ui_label_new(text, C8UI_TEXT_BODY);
	c8ui_label_set_color(l, C8UI_COLOR_SECONDARY);
	return l;
}

static struct c8ui_widget *section_title(const char *text) {
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 0);
	c8ui_box_set_padding(box, 0, 18, 0, 0);
	c8ui_widget_add(box, c8ui_label_new(text, C8UI_TEXT_SUBHEADER));
	return box;
}

static void open_link(struct c8ui_widget *w, void *data) {
	if (g.win && data) {
		c8ui_window_open_uri(g.win, data);
	}
}

static struct tm_tile *editing(void) {
	return g.edit ? tm_tile_find(g.edit) : NULL;
}

/* Drawing a tile as Start does */

static struct c8ui_icon *icon_for(const char *name) {
	if (name == NULL || name[0] == '\0') {
		return NULL;
	}
	if (g.icons == NULL) {
		g.icons = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
			(GDestroyNotify)c8ui_icon_destroy);
	}
	gpointer found;
	if (g_hash_table_lookup_extended(g.icons, name, NULL, &found)) {
		return found;
	}
	struct c8ui_icon *icon = c8ui_icon_load(NULL, name);
	g_hash_table_insert(g.icons, g_strdup(name), icon);
	return icon;
}

static void tile_px(enum tm_size size, double *w, double *h) {
	int cw = size == TM_SMALL ? 1 : size == TM_MEDIUM ? 2 : 4;
	int ch = size == TM_SMALL ? 1 : size == TM_LARGE ? 4 : 2;
	*w = cw * CELL + (cw - 1) * GAP;
	*h = ch * CELL + (ch - 1) * GAP;
}

static cairo_surface_t *tile_picture(struct tm_tile *t) {
	const char *ref = t->size == TM_WIDE && t->wide_image ? t->wide_image :
		t->image ? t->image : t->wide_image;
	return tm_picture(ref, 640);
}

/* At x, y, its real size times k */
static void draw_tile(cairo_t *cr, const char *family, struct tm_tile *t,
		double x, double y, double k) {
	double w, h;
	tile_px(t->size, &w, &h);
	cairo_save(cr);
	cairo_translate(cr, x, y);
	cairo_scale(cr, k, k);
	cairo_rectangle(cr, 0, 0, w, h);
	cairo_clip(cr);
	c8ui_set_source(cr, t->color, 1);
	cairo_paint(cr);
	cairo_surface_t *pic = tile_picture(t);
	bool labelled = t->label && t->size != TM_SMALL && t->name && t->name[0];
	if (pic) {
		c8ui_draw_surface_cover(cr, pic, 0, 0, w, h);
		if (labelled) {
			cairo_pattern_t *p = cairo_pattern_create_linear(0, h - 44, 0, h);
			cairo_pattern_add_color_stop_rgba(p, 0, 0, 0, 0, 0);
			cairo_pattern_add_color_stop_rgba(p, 1, 0, 0, 0, 0.55);
			cairo_set_source(cr, p);
			cairo_rectangle(cr, 0, h - 44, w, 44);
			cairo_fill(cr);
			cairo_pattern_destroy(p);
		}
	} else {
		double size = t->size == TM_SMALL ? h * 0.55 : t->size == TM_LARGE ?
			h * 0.3 : h * 0.4;
		double cy = h / 2 - (labelled ? 8 : 0);
		struct c8ui_icon *icon = icon_for(t->icon);
		if (icon) {
			c8ui_icon_draw_fit(cr, icon, w / 2, cy, size);
		} else if (t->name && t->name[0]) {
			char glyph[8] = "";
			const char *next = g_utf8_next_char(t->name);
			memcpy(glyph, t->name, MIN((size_t)(next - t->name), 7));
			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, w / 2 - tw / 2, cy - th / 2,
				0, 0);
		}
	}
	if (labelled) {
		cairo_set_source_rgb(cr, 1, 1, 1);
		c8ui_text_draw(cr, family, (struct c8ui_font){ 13,
			C8UI_WEIGHT_NORMAL }, t->name, 10, h - 26, w - 20, 1);
	}
	cairo_restore(cr);
}

static void draw_preview(struct c8ui_widget *w, cairo_t *cr, void *data) {
	struct tm_tile *t = editing();
	if (t == NULL) {
		return;
	}
	double tw, th;
	tile_px(t->size, &tw, &th);
	double k = fmin(1, w->rect.width / tw);
	draw_tile(cr, c8ui_widget_font(w), t, w->rect.x, w->rect.y, k);
}

static void preview_fit(void) {
	struct tm_tile *t = editing();
	if (g.preview && t) {
		double tw, th;
		tile_px(t->size, &tw, &th);
		g.preview->fixed_width = tw;
		g.preview->fixed_height = th;
		c8ui_widget_queue_layout(g.preview);
	}
}

/* Talking to Start */

static void pin_send(struct tm_tile *t, bool quiet);

static gboolean push_now(gpointer data) {
	g.push_timer = 0;
	struct tm_tile *t = editing();
	if (t && g.pinned && t->pinned_exec && g_strcmp0(t->exec,
			t->pinned_exec) == 0) {
		pin_send(t, true);
	}
	return G_SOURCE_REMOVE;
}

static gboolean save_now(gpointer data) {
	g.save_timer = 0;
	tm_save();
	return G_SOURCE_REMOVE;
}

/* Something about the tile changed: show it, keep it, and if Start has
 * it with this command, give it the new face */
static void changed(void) {
	if (g.preview) {
		c8ui_widget_queue_draw(g.preview);
	}
	if (g.save_timer) {
		g_source_remove(g.save_timer);
	}
	g.save_timer = g_timeout_add(SAVE_MS, save_now, NULL);
	if (g.push_timer) {
		g_source_remove(g.push_timer);
	}
	g.push_timer = g_timeout_add(PUSH_MS, push_now, NULL);
	update_buttons();
}

struct pin_call {
	char *id, *exec;
	bool quiet;
};

static void pin_replied(GObject *src, GAsyncResult *res, gpointer data) {
	struct pin_call *c = data;
	GError *e = NULL;
	GVariant *r = g_dbus_connection_call_finish(G_DBUS_CONNECTION(src), res,
		&e);
	gboolean pinned = FALSE;
	if (r) {
		g_variant_get(r, "(b)", &pinned);
		g_variant_unref(r);
	}
	struct tm_tile *t = tm_tile_find(c->id);
	if (t && pinned) {
		g_free(t->pinned_exec);
		t->pinned_exec = g_strdup(c->exec);
		tm_save();
		/* Start has this tile's pictures now; older ones can go */
		tm_pictures_prune();
	}
	if (t && t == editing()) {
		g.pinned = pinned || (g.pinned && c->quiet);
		update_buttons();
		if (g.note && !c->quiet) {
			c8ui_label_set_text(g.note, e ? e->message : pinned ?
				"It's on Start." : "Not pinned.");
		}
	} else if (e && !c->quiet) {
		show_message("Start didn't take the tile", e->message);
	}
	if (g.tiles_list) {
		c8ui_list_redraw(g.tiles_list);
	}
	if (e) {
		g_error_free(e);
	}
	g_free(c->id);
	g_free(c->exec);
	g_free(c);
}

static void pin_send(struct tm_tile *t, bool quiet) {
	if (g.bus == NULL) {
		return;
	}
	GVariantBuilder b;
	g_variant_builder_init(&b, G_VARIANT_TYPE("a{ss}"));
	char color[16];
	snprintf(color, sizeof(color), "#%06x", t->color & 0xffffff);
	g_variant_builder_add(&b, "{ss}", "name", t->name);
	g_variant_builder_add(&b, "{ss}", "exec", t->exec);
	g_variant_builder_add(&b, "{ss}", "icon", t->icon ? t->icon : "");
	g_variant_builder_add(&b, "{ss}", "color", color);
	g_variant_builder_add(&b, "{ss}", "size", tm_size_names[t->size]);
	g_variant_builder_add(&b, "{ss}", "image", t->image ? t->image : "");
	g_variant_builder_add(&b, "{ss}", "wide_image",
		t->wide_image ? t->wide_image : "");
	g_variant_builder_add(&b, "{ss}", "label", t->label ? "true" : "false");
	struct pin_call *c = g_new0(struct pin_call, 1);
	c->id = g_strdup(t->id);
	c->exec = g_strdup(t->exec);
	c->quiet = quiet;
	/* The question waits for an answer: long enough for one */
	g_dbus_connection_call(g.bus, "org.cont8nuum.Tiles", "/org/cont8nuum/Tiles",
		"org.cont8nuum.Tiles1", "RequestPin",
		g_variant_new("(sa{ss})", t->id, &b), G_VARIANT_TYPE("(b)"),
		G_DBUS_CALL_FLAGS_NONE, 60000, NULL, pin_replied, c);
}

static void got_tile(GObject *src, GAsyncResult *res, gpointer data) {
	char *id = data;
	GVariant *r = g_dbus_connection_call_finish(G_DBUS_CONNECTION(src), res,
		NULL);
	if (r) {
		gboolean pinned;
		const char *size;
		g_variant_get(r, "(b&s)", &pinned, &size);
		if (g_strcmp0(id, g.edit) == 0) {
			g.pinned = pinned;
			update_buttons();
		}
		g_variant_unref(r);
	}
	g_free(id);
}

static void ask_pinned(struct tm_tile *t) {
	if (g.bus) {
		g_dbus_connection_call(g.bus, "org.cont8nuum.Tiles",
			"/org/cont8nuum/Tiles", "org.cont8nuum.Tiles1", "GetTile",
			g_variant_new("(s)", t->id), G_VARIANT_TYPE("(bs)"),
			G_DBUS_CALL_FLAGS_NONE, 5000, NULL, got_tile, g_strdup(t->id));
	}
}

static void unpin(struct tm_tile *t) {
	if (g.bus) {
		g_dbus_connection_call(g.bus, "org.cont8nuum.Tiles",
			"/org/cont8nuum/Tiles", "org.cont8nuum.Tiles1", "Unpin",
			g_variant_new("(s)", t->id), NULL, G_DBUS_CALL_FLAGS_NONE, 5000,
			NULL, NULL, NULL);
	}
	g_clear_pointer(&t->pinned_exec, g_free);
	tm_save();
}

/* The editor */

static void update_buttons(void) {
	struct tm_tile *t = editing();
	if (t == NULL || g.pin_button == NULL) {
		return;
	}
	bool same = t->pinned_exec && g_strcmp0(t->exec, t->pinned_exec) == 0;
	c8ui_button_set_label(g.pin_button, !g.pinned ? "Pin to Start" :
		same ? "Pinned" : "Update on Start");
	c8ui_widget_set_disabled(g.pin_button, g.pinned && same);
	c8ui_widget_set_hidden(g.unpin_button, !g.pinned);
}

static void name_changed(struct c8ui_widget *w, void *data) {
	struct tm_tile *t = editing();
	if (t) {
		g_free(t->name);
		t->name = g_strdup(c8ui_entry_get(w));
		changed();
	}
}

static void exec_changed(struct c8ui_widget *w, void *data) {
	struct tm_tile *t = editing();
	if (t) {
		g_free(t->exec);
		const char *s = c8ui_entry_get(w);
		t->exec = s[0] ? g_strdup(s) : NULL;
		changed();
	}
}

static void icon_changed(struct c8ui_widget *w, void *data) {
	struct tm_tile *t = editing();
	if (t) {
		g_free(t->icon);
		const char *s = c8ui_entry_get(w);
		t->icon = s[0] ? g_strdup(s) : NULL;
		changed();
	}
}

/* The command and the icon may hold paths in the home folder. With stealth
 * mode on such a box shows the stand-in, greyed and not edited: typing
 * into it would save the stand-in as the real command. */
static struct c8ui_widget *path_entry(struct c8ui_widget *box,
		const char *header, const char *value, c8ui_action_fn changed_fn) {
	char *shown = c8_stealth_text(value ? value : "");
	bool hidden = strcmp(shown, value ? value : "") != 0;
	struct c8ui_widget *e = c8ui_entry_new(header, shown, NULL, NULL);
	g_free(shown);
	e->fixed_width = 600;
	c8ui_widget_add(box, e);
	if (hidden) {
		c8ui_widget_set_disabled(e, true);
		c8ui_widget_add(box, caption("Stealth mode hides this. Turn it off "
			"to change it."));
	} else {
		c8ui_entry_on_change(e, changed_fn, NULL);
	}
	return e;
}

static void label_toggled(struct c8ui_widget *w, void *data) {
	struct tm_tile *t = editing();
	if (t) {
		t->label = c8ui_toggle_get(w);
		changed();
	}
}

static void color_picked(struct c8ui_widget *w, void *data) {
	struct tm_tile *t = editing();
	if (t) {
		t->color = c8ui_swatches_get(w);
		changed();
	}
}

static void size_picked(struct c8ui_widget *w, void *data) {
	struct tm_tile *t = editing();
	if (t && c8ui_combo_get(w) >= 0) {
		t->size = c8ui_combo_get(w);
		preview_fit();
		changed();
	}
}

/* "Start from an app": the name, command and icon of an installed app */

static GAppInfo *app_named(const char *name) {
	for (guint i = 0; g.apps && i < g.apps->len; i++) {
		GAppInfo *a = g.apps->pdata[i];
		if (g_strcmp0(g_app_info_get_name(a), name) == 0) {
			return a;
		}
	}
	return NULL;
}

static void app_typed(struct c8ui_widget *w, void *data) {
	g_ptr_array_set_size(g.suggestions, 0);
	const char *text = c8ui_entry_get(w);
	char *q = text[0] ? g_utf8_casefold(text, -1) : NULL;
	for (guint i = 0; q && g.apps && i < g.apps->len &&
			g.suggestions->len < 8; i++) {
		const char *name = g_app_info_get_name(g.apps->pdata[i]);
		char *n = name ? g_utf8_casefold(name, -1) : NULL;
		if (n && strstr(n, q)) {
			g_ptr_array_add(g.suggestions, g_strdup(name));
		}
		g_free(n);
	}
	g_free(q);
	c8ui_entry_set_suggestions(w, (const char *const *)g.suggestions->pdata,
		g.suggestions->len);
}

static void app_chosen(struct c8ui_widget *w, void *data) {
	struct tm_tile *t = editing();
	GAppInfo *a = app_named(c8ui_entry_get(w));
	if (t == NULL || a == NULL) {
		return;
	}
	g_free(t->name);
	t->name = g_strdup(g_app_info_get_name(a));
	g_free(t->exec);
	const char *cmd = g_app_info_get_commandline(a);
	t->exec = cmd ? tm_strip_codes(cmd) : NULL;
	g_clear_pointer(&t->icon, g_free);
	GIcon *icon = g_app_info_get_icon(a);
	if (G_IS_THEMED_ICON(icon)) {
		const char *const *names = g_themed_icon_get_names(G_THEMED_ICON(icon));
		t->icon = g_strdup(names && names[0] ? names[0] : NULL);
	} else if (G_IS_FILE_ICON(icon)) {
		t->icon = g_file_get_path(g_file_icon_get_file(G_FILE_ICON(icon)));
	}
	changed();
	rebuild(); // the boxes show it
}

/* Pictures the user picks */

struct pick {
	char *id;
	int kind; // 0 square, 1 wide, 2 icon
};

static void picture_picked(char **uris, void *data) {
	struct pick *p = data;
	struct tm_tile *t = tm_tile_find(p->id);
	char *path = uris && uris[0] ? g_filename_from_uri(uris[0], NULL, NULL) :
		NULL;
	if (t && path) {
		static const char *const kinds[] = { "square", "wide", "icon" };
		char *copy = tm_picture_import(t, kinds[p->kind], path);
		if (copy == NULL) {
			show_message("Couldn't use that picture",
				"It couldn't be copied into Tile maker's folder.");
		} else {
			char **field = p->kind == 0 ? &t->image : p->kind == 1 ?
				&t->wide_image : &t->icon;
			g_free(*field);
			*field = copy;
			if (p->kind == 1 && t->size < TM_WIDE) {
				t->size = TM_WIDE;
			}
			changed();
			if (t == editing()) {
				rebuild();
			}
		}
	}
	g_free(path);
	g_free(p->id);
	g_free(p);
}

static void choose_picture(struct c8ui_widget *w, void *data) {
	struct tm_tile *t = editing();
	if (t == NULL) {
		return;
	}
	static const struct c8ui_file_filter filters[] = {
		{ "Pictures", "*.png;*.jpg;*.jpeg;*.svg",
			"image/png;image/jpeg;image/svg+xml" },
	};
	struct pick *p = g_new0(struct pick, 1);
	p->id = g_strdup(t->id);
	p->kind = GPOINTER_TO_INT(data);
	if (c8ui_file_open(g.win, &(struct c8ui_file_options){
			.title = p->kind == 2 ? "Choose an icon" : "Choose a picture",
			.filters = filters,
			.filter_count = 1,
		}, picture_picked, p) == NULL) {
		g_free(p->id);
		g_free(p);
		show_message("No file picker", "There's no file chooser portal to "
			"pick a file with. Type a path in the icon box instead.");
	}
}

static void remove_picture(struct c8ui_widget *w, void *data) {
	struct tm_tile *t = editing();
	if (t) {
		g_clear_pointer(GPOINTER_TO_INT(data) ? &t->wide_image : &t->image,
			g_free);
		changed();
		rebuild();
	}
}

static void pin_clicked(struct c8ui_widget *w, void *data) {
	struct tm_tile *t = editing();
	if (t == NULL) {
		return;
	}
	const char *why = NULL;
	if (t->name == NULL || t->name[0] == '\0') {
		why = "Give the tile a name.";
	} else if (g_utf8_strlen(t->name, -1) > 64) {
		why = "Start takes names of up to 64 characters.";
	} else if (t->exec == NULL || t->exec[0] == '\0') {
		why = "Say what the tile opens: a command, or pick an app.";
	} else if (t->exec[0] == '@') {
		why = "Start keeps commands starting with @ for its own tiles.";
	} else if (strchr(t->exec, '\n')) {
		why = "The command has to be on one line.";
	}
	if (why) {
		c8ui_label_set_text(g.note, why);
		return;
	}
	tm_save();
	c8ui_label_set_text(g.note, "Start is asking whether to pin it…");
	pin_send(t, false);
}

static void unpin_clicked(struct c8ui_widget *w, void *data) {
	struct tm_tile *t = editing();
	if (t) {
		unpin(t);
		g.pinned = false;
		update_buttons();
		c8ui_label_set_text(g.note, "Taken off Start.");
	}
}

static void delete_chosen(int choice, void *data) {
	struct tm_tile *t = editing();
	if (choice != 0 || t == NULL) {
		return;
	}
	if (g.pinned || t->pinned_exec) {
		unpin(t);
	}
	tm_tile_delete(t);
	tm_save();
	c8ui_pages_back(g.pages); // to the page under the editor
}

static void delete_clicked(struct c8ui_widget *w, void *data) {
	static const char *const buttons[] = { "Delete", "Cancel" };
	c8ui_dialog_show(g.root, "Delete this tile?", "It comes off Start too.",
		buttons, 2, delete_chosen, NULL);
}

/* SteamGridDB in the editor */

static void art_redraw(void *data) {
	for (int k = 0; k < TM_ART_COUNT; k++) {
		if (g.art_list[k]) {
			c8ui_list_redraw(g.art_list[k]);
		}
	}
	if (g.games_list) {
		c8ui_list_redraw(g.games_list);
	}
	if (g.tiles_list) {
		c8ui_list_redraw(g.tiles_list);
	}
	if (g.preview) {
		c8ui_widget_queue_draw(g.preview);
	}
}

static void draw_art(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	int kind = GPOINTER_TO_INT(data);
	GPtrArray *a = g.art[kind];
	if (a == NULL || item->index >= (int)a->len) {
		return;
	}
	struct tm_art_item *it = a->pdata[item->index];
	struct c8ui_rect r = item->rect;
	double pad = 4;
	cairo_surface_t *s = tm_picture(it->thumb, 480);
	if (s) {
		c8ui_draw_surface_fit(cr, s, r.x + pad, r.y + pad, r.width - 2 * pad,
			r.height - 2 * pad, 0);
	} else {
		cairo_set_source_rgba(cr, 0, 0, 0, 0.08);
		cairo_rectangle(cr, r.x + pad, r.y + pad, r.width - 2 * pad,
			r.height - 2 * pad);
		cairo_fill(cr);
	}
}

struct art_pick {
	char *id, *dest;
	enum tm_art kind;
};

static void art_downloaded(int status, const char *body, void *data) {
	struct art_pick *p = data;
	g.downloading = false;
	struct tm_tile *t = tm_tile_find(p->id);
	if (status == 200 && t) {
		char **field = p->kind == TM_ART_WIDE ? &t->wide_image :
			p->kind == TM_ART_ICON ? &t->icon : &t->image;
		g_free(*field);
		*field = g_strdup(p->dest);
		if (p->kind == TM_ART_WIDE && t->size < TM_WIDE) {
			t->size = TM_WIDE;
		} else if (p->kind == TM_ART_SQUARE && t->size == TM_SMALL) {
			t->size = TM_MEDIUM;
		}
		changed();
		if (t == editing()) {
			preview_fit();
			if (g.sgdb_note) {
				c8ui_label_set_text(g.sgdb_note, "Picked. Pick another to "
					"change it.");
			}
		}
	} else if (t == editing() && g.sgdb_note) {
		c8ui_label_set_text(g.sgdb_note, "That picture didn't download.");
	}
	g_free(p->id);
	g_free(p->dest);
	g_free(p);
}

static void art_opened(struct c8ui_widget *list, int index, void *data) {
	int kind = GPOINTER_TO_INT(data);
	struct tm_tile *t = editing();
	GPtrArray *a = g.art[kind];
	if (t == NULL || a == NULL || index < 0 || index >= (int)a->len ||
			g.downloading) {
		return;
	}
	struct tm_art_item *it = a->pdata[index];
	static const char *const names[] = { "wide", "square", "icon", "hero" };
	const char *ext = g_str_has_suffix(it->url, ".jpg") ||
		g_str_has_suffix(it->url, ".jpeg") ? ".jpg" : ".png";
	struct art_pick *p = g_new0(struct art_pick, 1);
	p->id = g_strdup(t->id);
	p->kind = kind;
	p->dest = tm_picture_path(t, names[kind], ext);
	g.downloading = true;
	if (g.sgdb_note) {
		c8ui_label_set_text(g.sgdb_note, "Downloading…");
	}
	tm_download(it->url, p->dest, art_downloaded, p);
}

struct art_req {
	int serial;
};

static void art_got(enum tm_art kind, GPtrArray *items, const char *error,
		void *data) {
	int serial = GPOINTER_TO_INT(data);
	if (serial != g.art_serial) {
		return;
	}
	if (g.art[kind] == NULL) {
		g.art[kind] = g_ptr_array_new_with_free_func(tm_art_item_free);
	}
	g_ptr_array_set_size(g.art[kind], 0);
	for (guint i = 0; i < items->len && i < ART_MAX; i++) {
		/* Moved over: items is freed after this */
		g_ptr_array_add(g.art[kind], items->pdata[i]);
		items->pdata[i] = NULL;
	}
	if (g.art_list[kind]) {
		c8ui_list_set_count(g.art_list[kind], g.art[kind]->len);
		c8ui_widget_set_hidden(g.art_list[kind], g.art[kind]->len == 0);
		c8ui_widget_set_hidden(g.art_head[kind], g.art[kind]->len == 0);
	}
	if (error && g.sgdb_note) {
		c8ui_label_set_text(g.sgdb_note, error);
	}
}

static void load_art(struct tm_tile *t) {
	for (int k = 0; k < TM_ART_COUNT; k++) {
		if (g.art[k]) {
			g_ptr_array_set_size(g.art[k], 0);
		}
		if (g.art_list[k]) {
			c8ui_list_set_count(g.art_list[k], 0);
		}
	}
	if (t->sgdb_id <= 0) {
		return;
	}
	if (g.sgdb_note) {
		c8ui_label_set_text(g.sgdb_note, "Pick a picture: wide ones for a "
			"wide tile, square ones for medium and large, icons for small.");
	}
	tm_sgdb_art(t->sgdb_id, TM_ART_WIDE, art_got,
		GINT_TO_POINTER(g.art_serial));
	tm_sgdb_art(t->sgdb_id, TM_ART_SQUARE, art_got,
		GINT_TO_POINTER(g.art_serial));
	tm_sgdb_art(t->sgdb_id, TM_ART_ICON, art_got,
		GINT_TO_POINTER(g.art_serial));
}

static void game_chosen(struct c8ui_widget *w, void *data) {
	struct tm_tile *t = editing();
	int index = GPOINTER_TO_INT(data);
	if (t == NULL || g.found == NULL || index >= (int)g.found->len) {
		return;
	}
	struct tm_sgdb_game *game = g.found->pdata[index];
	t->sgdb_id = game->id;
	changed();
	g.art_serial++;
	load_art(t);
}

static void show_found(void) {
	if (g.sgdb_games == NULL) {
		return;
	}
	c8ui_widget_clear(g.sgdb_games);
	for (guint i = 0; g.found && i < g.found->len && i < 8; i++) {
		struct tm_sgdb_game *game = g.found->pdata[i];
		struct tm_tile *t = editing();
		char *text = game->year ? g_strdup_printf("%s%s (%d)",
			t && t->sgdb_id == game->id ? "✓ " : "", game->name, game->year) :
			g_strdup_printf("%s%s", t && t->sgdb_id == game->id ? "✓ " : "",
			game->name);
		/* The link keeps its own copy of the text */
		c8ui_widget_add(g.sgdb_games, c8ui_link_new(text, game_chosen,
			GINT_TO_POINTER(i)));
		g_free(text);
	}
}

static void games_found(GPtrArray *games, const char *error, void *data) {
	int serial = GPOINTER_TO_INT(data);
	if (serial != g.art_serial) {
		return;
	}
	if (g.found == NULL) {
		g.found = g_ptr_array_new_with_free_func(tm_sgdb_game_free);
	}
	g_ptr_array_set_size(g.found, 0);
	for (guint i = 0; i < games->len; i++) {
		g_ptr_array_add(g.found, games->pdata[i]);
		games->pdata[i] = NULL;
	}
	struct tm_tile *t = editing();
	if (error) {
		if (g.sgdb_note) {
			c8ui_label_set_text(g.sgdb_note, error);
		}
	} else if (g.found->len == 0) {
		if (g.sgdb_note) {
			c8ui_label_set_text(g.sgdb_note, "SteamGridDB found nothing by "
				"that name. Try fewer words.");
		}
	} else if (t && t->sgdb_id == 0) {
		/* The best match, until told otherwise */
		struct tm_sgdb_game *first = g.found->pdata[0];
		t->sgdb_id = first->id;
		changed();
		load_art(t);
	}
	show_found();
}

static void sgdb_search(struct c8ui_widget *w, void *data) {
	struct tm_tile *t = editing();
	const char *q = c8ui_entry_get(w);
	if (t == NULL || q[0] == '\0') {
		return;
	}
	t->sgdb_id = 0; // a new search picks again
	g.art_serial++;
	if (g.sgdb_note) {
		c8ui_label_set_text(g.sgdb_note, "Searching…");
	}
	tm_sgdb_search(q, games_found, GINT_TO_POINTER(g.art_serial));
}

/* First look: by its Steam id when it has one, else by name */
static void sgdb_start(struct tm_tile *t) {
	if (tm_key() == NULL) {
		return;
	}
	if (t->sgdb_id > 0) {
		load_art(t);
		tm_sgdb_search(t->name, games_found, GINT_TO_POINTER(g.art_serial));
	} else if (t->steam_appid) {
		tm_sgdb_steam(t->steam_appid, games_found,
			GINT_TO_POINTER(g.art_serial));
	} else if (t->name && t->name[0] && t->exec) {
		tm_sgdb_search(t->name, games_found, GINT_TO_POINTER(g.art_serial));
	}
}

static void go_settings(struct c8ui_widget *w, void *data) {
	c8ui_pages_open(g.pages, PAGE_SETTINGS);
}

static void editor_page(struct c8ui_widget *box, struct tm_tile *t) {
	g.preview = c8ui_canvas_new(0, 0, draw_preview, NULL, NULL);
	c8ui_widget_add(box, g.preview);
	preview_fit();

	struct c8ui_widget *buttons = row();
	g.pin_button = c8ui_button_new("Pin to Start", pin_clicked, NULL);
	c8ui_button_set_primary(g.pin_button, true);
	c8ui_widget_add(buttons, g.pin_button);
	g.unpin_button = c8ui_button_new("Unpin", unpin_clicked, NULL);
	c8ui_widget_add(buttons, g.unpin_button);
	c8ui_widget_add(buttons, c8ui_button_new("Delete", delete_clicked, NULL));
	c8ui_widget_add(box, buttons);
	g.note = caption("");
	c8ui_widget_add(box, g.note);

	struct c8ui_widget *e = c8ui_entry_new("Name", t->name ? t->name : "",
		NULL, NULL);
	c8ui_entry_on_change(e, name_changed, NULL);
	e->fixed_width = 440;
	c8ui_widget_add(box, e);
	c8ui_widget_add(box, c8ui_toggle_new("Show the name", NULL, t->label,
		label_toggled, NULL));

	c8ui_widget_add(box, section_title("What it opens"));
	g.app_entry = c8ui_entry_new("Start from an app", "", app_chosen, NULL);
	c8ui_entry_set_placeholder(g.app_entry, "Type an app's name");
	c8ui_entry_on_change(g.app_entry, app_typed, NULL);
	g.app_entry->fixed_width = 440;
	c8ui_widget_add(box, g.app_entry);
	e = path_entry(box, "Command", t->exec, exec_changed);
	c8ui_entry_set_placeholder(e, "firefox --private-window");

	c8ui_widget_add(box, section_title("Look"));
	static const char *const sizes[] = { "Small", "Medium", "Wide", "Large" };
	c8ui_widget_add(box, c8ui_combo_new("Size", sizes, 4, t->size,
		size_picked, NULL));
	c8ui_widget_add(box, c8ui_label_new("Colour", C8UI_TEXT_BODY));
	struct c8ui_widget *sw = c8ui_swatches_new(palette, G_N_ELEMENTS(palette),
		t->color, color_picked, NULL);
	sw->max_width = 440;
	c8ui_widget_add(box, sw);
	e = path_entry(box, "Icon", t->icon, icon_changed);
	c8ui_entry_set_placeholder(e, "An icon's name, or a picture's path");
	struct c8ui_widget *r = row();
	c8ui_widget_add(r, c8ui_button_new("Choose an icon…", choose_picture,
		GINT_TO_POINTER(2)));
	c8ui_widget_add(box, r);

	c8ui_widget_add(box, c8ui_label_new("A picture to fill the tile",
		C8UI_TEXT_BODY_STRONG));
	c8ui_widget_add(box, caption("It covers the colour and icon. Start uses "
		"the wide one when the tile is wide, the square one at other sizes."));
	r = row();
	c8ui_widget_add(r, c8ui_button_new(t->image ? "Change square picture…" :
		"Square picture…", choose_picture, GINT_TO_POINTER(0)));
	if (t->image) {
		c8ui_widget_add(r, row_link("Remove", remove_picture,
			GINT_TO_POINTER(0)));
	}
	c8ui_widget_add(box, r);
	r = row();
	c8ui_widget_add(r, c8ui_button_new(t->wide_image ? "Change wide picture…" :
		"Wide picture…", choose_picture, GINT_TO_POINTER(1)));
	if (t->wide_image) {
		c8ui_widget_add(r, row_link("Remove", remove_picture,
			GINT_TO_POINTER(1)));
	}
	c8ui_widget_add(box, r);

	c8ui_widget_add(box, section_title("Art from SteamGridDB"));
	if (tm_key() == NULL) {
		c8ui_widget_add(box, caption("Game art for the tile, from "
			"SteamGridDB. It needs your own API key."));
		c8ui_widget_add(box, c8ui_link_new("Add your key in Settings",
			go_settings, NULL));
		return;
	}
	e = c8ui_entry_new(NULL, "", sgdb_search, NULL);
	c8ui_entry_set_placeholder(e, "Find a game");
	c8ui_entry_set_search(e, true);
	/* After: set_search scrolls to the caret before there's a width */
	c8ui_entry_set(e, t->name ? t->name : "");
	e->fixed_width = 440;
	c8ui_widget_add(box, e);
	g.sgdb_note = caption(t->sgdb_id ? "" : "Search for the game to see "
		"its art.");
	c8ui_widget_add(box, g.sgdb_note);
	g.sgdb_games = row();
	c8ui_widget_add(box, g.sgdb_games);
	show_found();
	static const char *const heads[] = { "Wide", "Square", "Icons" };
	static const double cells[][2] = { { 238, 115 }, { 128, 128 },
		{ 72, 72 } };
	for (int k = 0; k < TM_ART_ICON + 1; k++) {
		g.art_head[k] = c8ui_label_new(heads[k], C8UI_TEXT_TITLE);
		c8ui_widget_add(box, g.art_head[k]);
		g.art_list[k] = c8ui_list_new(C8UI_LIST_GRID, cells[k][0],
			cells[k][1], draw_art, GINT_TO_POINTER(k));
		c8ui_list_set_click_opens(g.art_list[k], true);
		c8ui_list_on_open(g.art_list[k], art_opened, GINT_TO_POINTER(k));
		g.art_list[k]->fill = true;
		int n = g.art[k] ? (int)g.art[k]->len : 0;
		c8ui_list_set_count(g.art_list[k], n);
		c8ui_widget_set_hidden(g.art_list[k], n == 0);
		c8ui_widget_set_hidden(g.art_head[k], n == 0);
		c8ui_widget_add(box, g.art_list[k]);
	}
}

static void open_editor(struct tm_tile *t) {
	/* Over the page it was opened for; back goes there */
	if (c8ui_pages_get(g.pages) != (int)g.page ||
			!c8ui_pages_showing(g.pages)) {
		c8ui_pages_open(g.pages, g.page);
	}
	bool same = g_strcmp0(g.edit, t->id) == 0;
	g_free(g.edit);
	g.edit = g_strdup(t->id);
	if (!same) {
		g.art_serial++;
		g.pinned = t->pinned_exec != NULL;
		for (int k = 0; k < TM_ART_COUNT; k++) {
			if (g.art[k]) {
				g_ptr_array_set_size(g.art[k], 0);
			}
		}
		if (g.found) {
			g_ptr_array_set_size(g.found, 0);
		}
	}
	show(!same);
	if (!same) {
		ask_pinned(t);
		sgdb_start(t);
	}
}

/* My tiles */

#define TILE_CELL_W 170
#define TILE_CELL_H 200

static void draw_tile_item(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	if (item->index >= (int)tm_tiles->len) {
		return;
	}
	struct tm_tile *t = tm_tiles->pdata[item->index];
	const char *family = c8ui_widget_font(list);
	struct c8ui_rect r = item->rect;
	double tw, th, box = r.width - 20;
	tile_px(t->size, &tw, &th);
	double k = fmin(box / tw, box / th);
	draw_tile(cr, family, t, r.x + (r.width - tw * k) / 2,
		r.y + 10 + (box - th * k) / 2, k);
	c8ui_set_source(cr, item->fg, 1);
	c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_BODY),
		t->name && t->name[0] ? t->name : "Untitled", r.x + 10, r.y + box + 14,
		r.width - 20, 1);
	if (t->pinned_exec) {
		c8ui_set_source(cr, item->fg, item->secondary);
		c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_CAPTION),
			"On Start", r.x + 10, r.y + box + 34, r.width - 20, 1);
	}
}

static void tile_opened(struct c8ui_widget *list, int index, void *data) {
	if (index >= 0 && index < (int)tm_tiles->len) {
		open_editor(tm_tiles->pdata[index]);
	}
}

static void new_tile(struct c8ui_widget *w, void *data) {
	struct tm_tile *t = tm_tile_new();
	tm_save();
	g.page = PAGE_TILES;
	open_editor(t);
}

static void go_games(struct c8ui_widget *w, void *data) {
	c8ui_pages_open(g.pages, PAGE_GAMES);
}

static void tiles_page(struct c8ui_widget *box) {
	struct c8ui_widget *r = row();
	c8ui_widget_add(r, c8ui_button_new("New tile", new_tile, NULL));
	c8ui_widget_add(r, row_link("Make one for a game", go_games, NULL));
	c8ui_widget_add(box, r);
	if (tm_tiles->len == 0) {
		c8ui_widget_add(box, caption("Tiles you make show up here. Each one "
			"can open anything: an app with options, a script, a website, "
			"a game."));
		return;
	}
	g.tiles_list = c8ui_list_new(C8UI_LIST_GRID, TILE_CELL_W, TILE_CELL_H,
		draw_tile_item, NULL);
	c8ui_list_set_click_opens(g.tiles_list, true);
	c8ui_list_on_open(g.tiles_list, tile_opened, NULL);
	c8ui_list_set_count(g.tiles_list, tm_tiles->len);
	g.tiles_list->fill = true;
	c8ui_widget_add(box, g.tiles_list);
}

/* Games */

static struct tm_tile *tile_for_exec(const char *exec) {
	for (guint i = 0; i < tm_tiles->len; i++) {
		struct tm_tile *t = tm_tiles->pdata[i];
		if (g_strcmp0(t->exec, exec) == 0) {
			return t;
		}
	}
	return NULL;
}

static void fill_games(void) {
	if (g.shown == NULL) {
		g.shown = g_ptr_array_new();
	}
	g_ptr_array_set_size(g.shown, 0);
	char *q = g.filter && g.filter[0] ? g_utf8_casefold(g.filter, -1) : NULL;
	for (guint i = 0; g.games && i < g.games->len; i++) {
		struct tm_game *game = g.games->pdata[i];
		char *n = g_utf8_casefold(game->name, -1);
		if (q == NULL || strstr(n, q)) {
			g_ptr_array_add(g.shown, game);
		}
		g_free(n);
	}
	g_free(q);
	if (g.games_list) {
		c8ui_list_set_count(g.games_list, g.shown->len);
		c8ui_list_redraw(g.games_list);
	}
}

static void draw_game(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	if (item->index >= (int)g.shown->len) {
		return;
	}
	struct tm_game *game = g.shown->pdata[item->index];
	const char *family = c8ui_widget_font(list);
	struct c8ui_rect r = item->rect;
	double pw = 120, ph = r.height - 12, x = r.x + 8, y = r.y + 6;
	cairo_surface_t *pic = game->wide ? tm_picture(game->wide, 480) : NULL;
	struct c8ui_icon *icon = pic ? NULL : icon_for(game->icon);
	cairo_set_source_rgba(cr, 0, 0, 0, 0.08);
	cairo_rectangle(cr, x, y, pw, ph);
	cairo_fill(cr);
	if (pic) {
		c8ui_draw_surface_cover(cr, pic, x, y, pw, ph);
	} else if (icon) {
		c8ui_icon_draw_fit(cr, icon, x + pw / 2, y + ph / 2, ph * 0.75);
	}
	double tx = x + pw + 16, width = r.x + r.width - tx - 8;
	struct c8ui_font title = { 16, C8UI_WEIGHT_SEMIBOLD };
	struct c8ui_font small = c8ui_text_font(C8UI_TEXT_CAPTION);
	c8ui_set_source(cr, item->fg, 1);
	c8ui_text_draw(cr, family, title, game->name, tx, r.y + 14, width, 1);
	struct tm_tile *t = tile_for_exec(game->exec);
	char *line = g_strdup_printf("%s%s", tm_source_name(game->source),
		t ? t->pinned_exec ? " · on Start" : " · has a tile" : "");
	c8ui_set_source(cr, item->fg, item->secondary);
	c8ui_text_draw(cr, family, small, line, tx, r.y + 40, width, 1);
	g_free(line);
}

static void game_opened(struct c8ui_widget *list, int index, void *data) {
	if (index < 0 || index >= (int)g.shown->len) {
		return;
	}
	struct tm_game *game = g.shown->pdata[index];
	struct tm_tile *t = tile_for_exec(game->exec);
	if (t == NULL) {
		t = tm_tile_new();
		g_free(t->name);
		t->name = g_strndup(game->name, 64 * 4);
		if (g_utf8_strlen(t->name, -1) > 64) {
			char *cut = g_utf8_substring(t->name, 0, 64);
			g_free(t->name);
			t->name = cut;
		}
		t->exec = g_strdup(game->exec);
		t->icon = g_strdup(game->icon);
		t->steam_appid = g_strdup(game->steam_appid);
		t->color = 0x1e1e1e;
		/* The launcher's own picture, until SteamGridDB gives another */
		if (game->wide) {
			t->wide_image = tm_picture_import(t, "wide", game->wide);
		}
		t->size = t->wide_image ? TM_WIDE : TM_MEDIUM;
		t->label = t->wide_image == NULL;
		tm_save();
	}
	open_editor(t);
}

static void games_scanned(GPtrArray *games, void *data) {
	g.games = games;
	g.scanning = false;
	if (g.page == PAGE_GAMES && g.edit == NULL) {
		rebuild();
	}
}

static void rescan(struct c8ui_widget *w, void *data) {
	if (!g.scanning) {
		g.scanning = true;
		tm_games_scan(games_scanned, NULL);
		if (g.page == PAGE_GAMES && g.edit == NULL) {
			rebuild();
		}
	}
}

static void game_filter(struct c8ui_widget *w, void *data) {
	g_free(g.filter);
	g.filter = g_strdup(c8ui_entry_get(w));
	fill_games();
}

static void games_page(struct c8ui_widget *box) {
	if (g.games == NULL) {
		c8ui_widget_add(box, caption(g.scanning ? "Looking for games…" :
			"No games looked for yet."));
		return;
	}
	struct c8ui_widget *r = row();
	struct c8ui_widget *search = c8ui_entry_new(NULL, "", NULL, NULL);
	c8ui_entry_set_placeholder(search, "Find a game");
	c8ui_entry_set_search(search, true);
	c8ui_entry_set(search, g.filter ? g.filter : "");
	c8ui_entry_on_change(search, game_filter, NULL);
	search->min_width = 240;
	c8ui_widget_add(r, search);
	c8ui_widget_add(r, row_link(g.scanning ? "Looking…" : "Look again",
		rescan, NULL));
	c8ui_widget_add(box, r);
	if (g.games->len == 0) {
		c8ui_widget_add(box, caption("No games found. Tile maker looks in "
			"Steam's libraries, Lutris and apps in the Games category. Any "
			"game can still have a tile: make a new one and search "
			"SteamGridDB for its art."));
		c8ui_widget_add(box, c8ui_button_new("New tile", new_tile, NULL));
		return;
	}
	g.games_list = c8ui_list_new(C8UI_LIST_ROWS, 0, ROW_H, draw_game, NULL);
	c8ui_list_set_click_opens(g.games_list, true);
	c8ui_list_on_open(g.games_list, game_opened, NULL);
	g.games_list->fill = true;
	c8ui_widget_add(box, g.games_list);
	fill_games();
}

/* Settings */

static void key_changed(struct c8ui_widget *w, void *data) {
	g_free(tm_sgdb_key);
	const char *s = c8ui_entry_get(w);
	char *trimmed = g_strstrip(g_strdup(s));
	tm_sgdb_key = trimmed[0] ? trimmed : (g_free(trimmed), NULL);
	tm_save();
	if (g.charms) {
		c8ui_charms_changed(g.charms, "options");
	}
}

static void settings_page(struct c8ui_widget *box) {
	c8ui_widget_add(box, section_title("SteamGridDB"));
	c8ui_widget_add(box, caption("Tile maker finds art for games on "
		"SteamGridDB, which asks each user for an API key of their own. "
		"Sign in there, make one on your preferences page and paste it "
		"here."));
	c8ui_widget_add(box, c8ui_link_new("Get an API key", open_link,
		(void *)KEY_URL));
	struct c8ui_widget *e = c8ui_entry_new("API key",
		tm_sgdb_key ? tm_sgdb_key : "", NULL, NULL);
	c8ui_entry_set_password(e, true);
	c8ui_entry_on_change(e, key_changed, NULL);
	e->fixed_width = 440;
	c8ui_widget_add(box, e);
	if (g_getenv("STEAMGRIDDB_API_KEY")) {
		c8ui_widget_add(box, caption("STEAMGRIDDB_API_KEY is set, and is "
			"used instead."));
	}
	c8ui_widget_add(box, caption("It's kept in tilemaker.ini in your "
		"config folder, readable only by you."));
}

/* Pages */

static void forget_page(void) {
	g.content = NULL;
	g.tiles_list = g.games_list = NULL;
	g.preview = g.pin_button = g.unpin_button = g.note = NULL;
	g.app_entry = g.sgdb_note = g.sgdb_games = NULL;
	for (int k = 0; k < TM_ART_COUNT; k++) {
		g.art_list[k] = g.art_head[k] = NULL;
	}
}

static void content_gone(struct c8ui_widget *w, void *data) {
	if (w == g.content) {
		forget_page();
	}
}

/* Leaving the editor (back, or another page picked from the list) */
static void editor_left(void) {
	struct tm_tile *t = editing();
	/* An empty new tile isn't worth keeping */
	if (t && (t->name == NULL || t->name[0] == '\0') && t->exec == NULL &&
			!t->pinned_exec) {
		tm_tile_delete(t);
		tm_save();
	}
	g.art_serial++;
	g_clear_pointer(&g.edit, g_free);
}

static void back_from_editor(struct c8ui_widget *pages, void *data) {
	editor_left();
}

static void build_page(struct c8ui_widget *pages, struct c8ui_widget *content,
		void *data) {
	forget_page();
	g.page = c8ui_pages_get(pages);
	if (g.edit && c8ui_pages_sub(pages) == NULL) {
		editor_left();
	}
	g.content = content;
	content->on_destroy = content_gone;
	struct tm_tile *t = editing();
	content->max_width = t ? 1000 : g.page == PAGE_SETTINGS ? 760 : 1100;
	if (t) {
		editor_page(content, t);
		update_buttons();
		return;
	}
	if (g.page == PAGE_GAMES && g.games == NULL && !g.scanning) {
		g.scanning = true;
		tm_games_scan(games_scanned, NULL);
	}
	switch (g.page) {
	case PAGE_TILES: tiles_page(content); break;
	case PAGE_GAMES: games_page(content); break;
	case PAGE_SETTINGS: settings_page(content); break;
	default: break;
	}
}

/* The page again, the editor under the tile's name; enter: from the top,
 * as a new page */
static void show(bool enter) {
	if (g.pages == NULL) {
		return;
	}
	struct tm_tile *t = editing();
	c8ui_pages_set_sub(g.pages, t == NULL ? NULL : t->name && t->name[0] ?
		t->name : "New tile");
	c8ui_pages_rebuild(g.pages, enter);
}

/* For what it shows */
static void rebuild(void) {
	show(false);
}

static bool keys(const struct c8ui_event *ev, void *data) {
	if (ev->sym == XKB_KEY_Escape && c8ui_pages_back(g.pages)) {
		return true;
	}
	if (ev->sym == XKB_KEY_Menu) {
		c8ui_appbar_toggle(g.appbar);
		return true;
	}
	if ((ev->mods & C8UI_MOD_CTRL) && ev->base_sym == XKB_KEY_n) {
		new_tile(NULL, NULL);
		return true;
	}
	return false;
}

/* Charms */

static void search(struct c8ui_search *s, const char *query, void *data) {
	if (query[0] == '\0') {
		return;
	}
	char *q = g_utf8_casefold(query, -1);
	for (guint i = 0; i < tm_tiles->len; i++) {
		struct tm_tile *t = tm_tiles->pdata[i];
		char *n = g_utf8_casefold(t->name ? t->name : "", -1);
		if (strstr(n, q)) {
			char *id = g_strconcat("t:", t->id, NULL);
			c8ui_search_add(s, id, t->name, "Tile", t->icon);
			g_free(id);
		}
		g_free(n);
	}
	for (guint i = 0; g.games && i < g.games->len; i++) {
		struct tm_game *game = g.games->pdata[i];
		char *n = g_utf8_casefold(game->name, -1);
		if (strstr(n, q)) {
			char *id = g_strdup_printf("g:%s", game->exec);
			c8ui_search_add(s, id, game->name, tm_source_name(game->source),
				game->icon);
			g_free(id);
		}
		g_free(n);
	}
	g_free(q);
}

static void open_result(const char *id, const char *query, void *data) {
	if (g.win == NULL) {
		return;
	}
	if (g_str_has_prefix(id, "t:")) {
		struct tm_tile *t = tm_tile_find(id + 2);
		if (t) {
			open_editor(t);
		}
	} else if (g_str_has_prefix(id, "g:") && g.games) {
		g.page = PAGE_GAMES;
		g_clear_pointer(&g.filter, g_free);
		fill_games();
		for (guint i = 0; i < g.shown->len; i++) {
			struct tm_game *game = g.shown->pdata[i];
			if (strcmp(game->exec, id + 2) == 0) {
				game_opened(NULL, i, NULL);
				break;
			}
		}
	}
	c8ui_window_present(g.win);
}

static void option_key(struct c8ui_setting *s, void *data) {
	g_free(tm_sgdb_key);
	char *trimmed = g_strstrip(g_strdup(c8ui_setting_get_text(s)));
	tm_sgdb_key = trimmed[0] ? trimmed : (g_free(trimmed), NULL);
	tm_save();
	if (g.page == PAGE_SETTINGS && g.edit == NULL) {
		rebuild();
	}
}

static void options_page(struct c8ui_settings_page *page, void *data) {
	c8ui_page_paragraph(page, "Tile maker finds game art on SteamGridDB "
		"with your own API key.");
	struct c8ui_setting *s = c8ui_page_text(page, "key", "SteamGridDB API key",
		tm_sgdb_key ? tm_sgdb_key : "", option_key, NULL);
	c8ui_setting_set_password(s, true); // dots, as on the Settings page
	c8ui_setting_set_placeholder(s, "Paste it here");
}

/* The app */

static void window_gone(struct c8ui_widget *w, void *data) {
	g.win = NULL;
	g.root = NULL;
	g.pages = g.content = g.appbar = NULL;
	forget_page();
	g_clear_pointer(&g.edit, g_free);
}

static void apply_theme(void) {
	if (g.pages && g.app) {
		c8ui_widget_set_background(c8ui_pages_pane(g.pages),
			c8ui_app_theme(g.app)->background);
	}
}

static void make_window(void) {
	g.win = c8ui_window_new(g.app, "Tile maker", 1100, 760);
	g.root = c8ui_window_root(g.win);

	g.pages = c8ui_pages_new("Tile maker", PANE_WIDTH, build_page, NULL);
	g.pages->on_destroy = window_gone;
	for (int i = 0; i < PAGE_COUNT; i++) {
		c8ui_pages_add(g.pages, page_titles[i]);
	}
	c8ui_pages_on_back(g.pages, back_from_editor, NULL);
	apply_theme();
	c8ui_root_set_child(g.root, g.pages);
	c8ui_root_set_key_handler(g.root, keys, NULL);

	g.appbar = c8ui_appbar_new(g.root);
	c8ui_appbar_add(g.appbar, "list-add", "New tile", false, new_tile, NULL);
	c8ui_appbar_add(g.appbar, "view-refresh", "Look for games", true, rescan,
		NULL);
	/* The page is built when the window gets its size (the pages do,
	 * under 760 one at a time); one
	 * asked for by name shows even if that's narrow */
	if (g.page_given) {
		c8ui_pages_open(g.pages, g.page);
	}
}

/* Turned on or off: the editor's command and icon boxes again */
static void stealth_changed(void *data) {
	if (g.edit) {
		rebuild();
	}
}

static void startup(struct c8ui_app *app, void *data) {
	g.app = app;
	c8_stealth_watch(stealth_changed, NULL);
	tm_load();
	g.suggestions = g_ptr_array_new_with_free_func(g_free);
	g.apps = g_ptr_array_new_with_free_func(g_object_unref);
	GList *all = g_app_info_get_all();
	for (GList *l = all; l; l = l->next) {
		if (g_app_info_should_show(l->data)) {
			g_ptr_array_add(g.apps, g_object_ref(l->data));
		}
	}
	g_list_free_full(all, g_object_unref);
	g.bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL);
	tm_pictures_on_ready(art_redraw, NULL);
	g.charms = c8ui_charms_new(app);
	if (g.charms) {
		c8ui_charms_on_search(g.charms, search, open_result, NULL, NULL);
		c8ui_charms_add_page(g.charms, "options", "Options", options_page,
			NULL);
	}
	g.scanning = true;
	tm_games_scan(games_scanned, NULL);
}

static void open(struct c8ui_app *app, char **uris, void *data) {
	if (g.win == NULL) {
		make_window();
	}
	struct tm_tile *t = tm_tile_find(g.start_edit);
	g_clear_pointer(&g.start_edit, g_free);
	if (t) {
		open_editor(t);
	}
	c8ui_window_present(g.win);
}

static void shutdown(struct c8ui_app *app, void *data) {
	if (g.save_timer) {
		g_source_remove(g.save_timer);
	}
	if (g.push_timer) {
		g_source_remove(g.push_timer);
		push_now(NULL);
	}
	tm_save();
	c8ui_charms_destroy(g.charms);
}

int main(int argc, char **argv) {
	for (int i = 1; i + 1 < argc; i++) {
		if (strcmp(argv[i], "--edit") == 0) {
			g.start_edit = g_strdup(argv[i + 1]);
			memmove(&argv[i], &argv[i + 2], (argc - i - 1) * sizeof(*argv));
			argc -= 2;
			i--;
			continue;
		}
		if (strcmp(argv[i], "--page") == 0) {
			static const char *const args[PAGE_COUNT] = { "tiles", "games",
				"settings" };
			for (int p = 0; p < PAGE_COUNT; p++) {
				if (strcmp(argv[i + 1], args[p]) == 0) {
					g.page = p;
					g.page_given = true; // narrow: on the page, not the list
				}
			}
			memmove(&argv[i], &argv[i + 2], (argc - i - 1) * sizeof(*argv));
			argc -= 2;
			break;
		}
	}
	static const struct c8ui_app_info info = {
		.id = APP_ID,
		.startup = startup,
		.open = open,
		.shutdown = shutdown,
	};
	return c8ui_app_main(&info, argc, argv);
}
