#define _GNU_SOURCE
#include <ctype.h>
#include <dirent.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <pango/pangocairo.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <c8ui/c8ui-files.h>
#include "background.h"
#include "settings.h"

/* Personalise */

static struct {
	struct c8ui_widget *accent, *background, *pattern;
	struct c8ui_widget *picture_note[2], *picture_remove[2];
	char **patterns;
	int pattern_count;
} personalise;

/* The pictures Photos sets (background.h): not in config.ini, so shown
 * and taken away here as the files they are */

static const char *picture_note(enum c8_background which) {
	bool set = c8_background_set(which);
	if (which == C8_BACKGROUND_START) {
		return set ? "Start shows a picture you chose in Photos. Without "
			"it, Start shows the colour and pattern." :
			"To show a picture instead, open it in Photos and choose "
			"Set as in the app bar.";
	}
	return set ? "The lock screen shows a picture you chose in Photos." :
		"The lock screen shows Start's colour and pattern. To show a "
		"picture instead, open it in Photos and choose Set as.";
}

static void picture_update(enum c8_background which) {
	if (personalise.picture_note[which]) {
		c8ui_label_set_text(personalise.picture_note[which],
			picture_note(which));
	}
	if (personalise.picture_remove[which]) {
		c8ui_widget_set_hidden(personalise.picture_remove[which],
			!c8_background_set(which));
	}
}

static void picture_remove(struct c8ui_widget *w, void *data) {
	enum c8_background which = GPOINTER_TO_INT(data);
	char *path = c8_background_path(which);
	g_unlink(path); // Start sees it go and draws the pattern again
	g_free(path);
	picture_update(which);
}

static void add_picture(struct c8ui_widget *box, enum c8_background which) {
	struct c8ui_widget *note = caption(picture_note(which));
	c8ui_widget_track(note, &personalise.picture_note[which]);
	add(box, note);
	struct c8ui_widget *remove = c8ui_button_new("Remove the picture",
		picture_remove, GINT_TO_POINTER(which));
	remove->align = C8UI_ALIGN_START;
	remove->hidden = !c8_background_set(which);
	c8ui_widget_track(remove, &personalise.picture_remove[which]);
	add(box, remove);
}

static int palette(const char *key, uint32_t *out, int max) {
	const struct entry *e;
	int n = setting_all("palette", key, &e), count = 0;
	for (int i = 0; i < n && count < max; i++) {
		if (c8ui_parse_color(e[i].value, &out[count])) {
			count++;
		}
	}
	return count;
}

static void color_changed(struct c8ui_widget *w, void *data) {
	char value[16];
	snprintf(value, sizeof(value), "#%06x", c8ui_swatches_get(w));
	setting_set("appearance", data, value);
}

static void pattern_changed(struct c8ui_widget *w, void *data) {
	int i = c8ui_choice_get(w);
	if (i >= 0 && i < personalise.pattern_count) {
		setting_set("appearance", "pattern", personalise.patterns[i]);
	}
}

static int pattern_index(void) {
	const char *now = setting_or("appearance", "pattern", "");
	for (int i = 0; i < personalise.pattern_count; i++) {
		if (strcmp(personalise.patterns[i], now) == 0) {
			return i;
		}
	}
	return -1;
}

static void personalise_build(struct c8ui_widget *box) {
	uint32_t colors[64];
	uint32_t current = 0;

	add(box, section_title("Accent colour"));
	add(box, caption("Highlights, selections and the Start screen's text."));
	int n = palette("accent", colors, 64);
	c8ui_parse_color(setting("appearance", "accent"), &current);
	c8ui_widget_track(c8ui_swatches_new(colors, n, current, color_changed,
		"accent"), &personalise.accent);
	add(box, personalise.accent);

	add(box, section_title("Start background"));
	n = palette("background", colors, 64);
	c8ui_parse_color(setting("appearance", "background"), &current);
	c8ui_widget_track(c8ui_swatches_new(colors, n, current, color_changed,
		"background"), &personalise.background);
	add(box, personalise.background);

	if (personalise.patterns == NULL) {
		const struct entry *e;
		int count = setting_all("palette", "pattern", &e);
		personalise.patterns = calloc(count + 1, sizeof(char *));
		for (int i = 0; i < count; i++) {
			personalise.patterns[i] = strdup(e[i].value);
		}
		personalise.pattern_count = count;
	}
	char **labels = calloc(personalise.pattern_count + 1, sizeof(char *));
	for (int i = 0; i < personalise.pattern_count; i++) {
		labels[i] = g_strdup(personalise.patterns[i]);
		labels[i][0] = g_ascii_toupper(labels[i][0]);
	}
	c8ui_widget_track(c8ui_choice_new("Pattern", (const char *const *)labels,
		personalise.pattern_count, pattern_index(), pattern_changed, NULL),
		&personalise.pattern);
	g_strfreev(labels);
	add(box, personalise.pattern);
	add_picture(box, C8_BACKGROUND_START);

	add(box, section_title("Lock screen"));
	add_picture(box, C8_BACKGROUND_LOCK);

	add(box, section_title("Start"));
	add(box, bound_toggle("appearance", "more_tiles", "Show more tiles",
		"Smaller tiles, so more of them fit.", false));
	add(box, bound_toggle("appearance", "live_tiles", "Live tiles",
		"Tiles show what's new in their apps.", true));
}

static void personalise_refresh(void) {
	uint32_t c;
	if (personalise.accent && c8ui_parse_color(setting("appearance", "accent"), &c)) {
		c8ui_swatches_set(personalise.accent, c);
	}
	if (personalise.background &&
			c8ui_parse_color(setting("appearance", "background"), &c)) {
		c8ui_swatches_set(personalise.background, c);
	}
	if (personalise.pattern) {
		c8ui_choice_set(personalise.pattern, pattern_index());
	}
	picture_update(C8_BACKGROUND_START);
	picture_update(C8_BACKGROUND_LOCK);
}

const struct page page_personalise = {
	.name = "personalise",
	.title = "Personalise",
	.build = personalise_build,
	.refresh = personalise_refresh,
};

/* Mouse and touchpad */

static void mouse_build(struct c8ui_widget *box) {
	add(box, section_title("Touchpad"));
	add(box, bound_toggle("touchpad", "tap", "Tap to click",
		"One finger clicks, two right-click, three middle-click.", true));
	add(box, bound_toggle("touchpad", "natural_scroll", "Natural scrolling",
		"Content follows your fingers, as on a touchscreen.", true));
	add(box, bound_toggle("touchpad", "disable_while_typing",
		"Ignore the touchpad while typing", NULL, true));
	struct c8ui_widget *speed = bound_slider("touchpad", "speed",
		"Pointer speed", -1, 1, 0.1, 0, "%.2f");
	c8ui_slider_set_labels(speed, "Slow", "Fast");
	add(box, speed);

	add(box, section_title("Mouse"));
	add(box, bound_toggle("mouse", "left_handed",
		"Swap the left and right buttons", NULL, false));
	add(box, bound_toggle("mouse", "natural_scroll", "Natural scrolling",
		"Turning the wheel down moves the content down.", false));
	speed = bound_slider("mouse", "speed", "Pointer speed", -1, 1, 0.1, 0,
		"%.2f");
	c8ui_slider_set_labels(speed, "Slow", "Fast");
	add(box, speed);
}

const struct page page_mouse = {
	.name = "mouse",
	.title = "Mouse and touchpad",
	.build = mouse_build,
};

/* Keyboard */

struct xkb_item {
	char *code, *desc, *layout; // layout: for variants
};

static struct {
	struct xkb_item *layouts, *variants;
	int layout_count, variant_count;
	bool loaded;
	struct c8ui_widget *layout, *variant;
	/* What the combos list, by index */
	char **layout_codes, **variant_codes;
	int layout_n, variant_n;
} kb;

static int item_cmp(const void *a, const void *b) {
	return g_utf8_collate(((const struct xkb_item *)a)->desc,
		((const struct xkb_item *)b)->desc);
}

static void load_xkb(void) {
	if (kb.loaded) {
		return;
	}
	kb.loaded = true;
	char *text = NULL;
	const char *paths[] = {
		"/usr/share/X11/xkb/rules/evdev.lst",
		"/usr/local/share/X11/xkb/rules/evdev.lst",
	};
	for (size_t i = 0; i < G_N_ELEMENTS(paths) && text == NULL; i++) {
		g_file_get_contents(paths[i], &text, NULL, NULL);
	}
	if (text == NULL) {
		return;
	}
	enum { NONE, LAYOUT, VARIANT } part = NONE;
	char **lines = g_strsplit(text, "\n", -1);
	for (char **l = lines; *l; l++) {
		char *s = *l;
		if (s[0] == '!') {
			part = strstr(s, "! layout") ? LAYOUT :
				strstr(s, "! variant") ? VARIANT : NONE;
			continue;
		}
		if (part == NONE) {
			continue;
		}
		char *line = g_strstrip(s);
		if (line[0] == '\0') {
			continue;
		}
		size_t n = strcspn(line, " \t");
		char *code = g_strndup(line, n);
		char *desc = g_strdup(g_strstrip(line + n));
		struct xkb_item item = { code, desc, NULL };
		if (part == LAYOUT) {
			kb.layouts = realloc(kb.layouts,
				sizeof(*kb.layouts) * (kb.layout_count + 1));
			kb.layouts[kb.layout_count++] = item;
		} else {
			/* "us: English (US, intl.)" */
			char *colon = strchr(desc, ':');
			if (colon) {
				item.layout = g_strndup(desc, colon - desc);
				item.desc = g_strdup(g_strstrip(colon + 1));
				g_free(desc);
			}
			kb.variants = realloc(kb.variants,
				sizeof(*kb.variants) * (kb.variant_count + 1));
			kb.variants[kb.variant_count++] = item;
		}
	}
	g_strfreev(lines);
	g_free(text);
	qsort(kb.layouts, kb.layout_count, sizeof(*kb.layouts), item_cmp);
	qsort(kb.variants, kb.variant_count, sizeof(*kb.variants), item_cmp);
}

static void free_codes(char ***codes, int *n) {
	for (int i = 0; i < *n; i++) {
		g_free((*codes)[i]);
	}
	free(*codes);
	*codes = NULL;
	*n = 0;
}

/* Fill the layout combo; layouts we don't know (several, "us,de") are
 * listed as they are */
static void fill_layouts(void) {
	const char *now = setting_or("keyboard", "layout", "");
	free_codes(&kb.layout_codes, &kb.layout_n);
	int cap = kb.layout_count + 2;
	char **labels = calloc(cap, sizeof(char *));
	kb.layout_codes = calloc(cap, sizeof(char *));
	int n = 0, selected = -1;
	bool known = now[0] == '\0';
	for (int i = 0; i < kb.layout_count; i++) {
		known |= strcmp(kb.layouts[i].code, now) == 0;
	}
	if (now[0] == '\0') {
		labels[n] = g_strdup("Automatic");
		kb.layout_codes[n++] = g_strdup("");
		selected = 0;
	} else if (!known) {
		labels[n] = g_strdup(now);
		kb.layout_codes[n++] = g_strdup(now);
		selected = 0;
	}
	for (int i = 0; i < kb.layout_count; i++) {
		if (strcmp(kb.layouts[i].code, now) == 0) {
			selected = n;
		}
		labels[n] = g_strdup(kb.layouts[i].desc);
		kb.layout_codes[n++] = g_strdup(kb.layouts[i].code);
	}
	kb.layout_n = n;
	c8ui_combo_set_items(kb.layout, (const char *const *)labels, n, selected);
	for (int i = 0; i < n; i++) {
		g_free(labels[i]);
	}
	free(labels);
}

static void fill_variants(void) {
	const char *layout = setting_or("keyboard", "layout", "");
	const char *now = setting_or("keyboard", "variant", "");
	free_codes(&kb.variant_codes, &kb.variant_n);
	int cap = kb.variant_count + 2;
	char **labels = calloc(cap, sizeof(char *));
	kb.variant_codes = calloc(cap, sizeof(char *));
	int n = 0, selected = 0;
	labels[n] = g_strdup("Standard");
	kb.variant_codes[n++] = g_strdup("");
	bool known = now[0] == '\0';
	for (int i = 0; i < kb.variant_count; i++) {
		if (kb.variants[i].layout == NULL ||
				strcmp(kb.variants[i].layout, layout) != 0) {
			continue;
		}
		if (strcmp(kb.variants[i].code, now) == 0) {
			selected = n;
			known = true;
		}
		labels[n] = g_strdup(kb.variants[i].desc);
		kb.variant_codes[n++] = g_strdup(kb.variants[i].code);
	}
	if (!known) {
		selected = n;
		labels[n] = g_strdup(now);
		kb.variant_codes[n++] = g_strdup(now);
	}
	kb.variant_n = n;
	c8ui_combo_set_items(kb.variant, (const char *const *)labels, n, selected);
	c8ui_widget_set_disabled(kb.variant, n <= 1);
	for (int i = 0; i < n; i++) {
		g_free(labels[i]);
	}
	free(labels);
}

static void layout_changed(struct c8ui_widget *w, void *data) {
	int i = c8ui_combo_get(w);
	if (i < 0 || i >= kb.layout_n) {
		return;
	}
	/* A new layout starts from its standard variant */
	setting_queue_set("keyboard", "layout", kb.layout_codes[i]);
	setting_queue_set("keyboard", "variant", "");
	setting_commit();
}

static void variant_changed(struct c8ui_widget *w, void *data) {
	int i = c8ui_combo_get(w);
	if (i >= 0 && i < kb.variant_n) {
		setting_set("keyboard", "variant", kb.variant_codes[i]);
	}
}

static void keyboard_build(struct c8ui_widget *box) {
	load_xkb();
	add(box, section_title("Layout"));
	c8ui_widget_track(c8ui_combo_new("Keyboard layout", NULL, 0, -1,
		layout_changed, NULL), &kb.layout);
	add(box, kb.layout);
	c8ui_widget_track(c8ui_combo_new("Variant", NULL, 0, -1, variant_changed,
		NULL), &kb.variant);
	add(box, kb.variant);
	fill_layouts();
	fill_variants();
	add(box, bound_entry("keyboard", "options", "Options", "caps:escape"));
	add(box, caption("XKB options, separated by commas. Several layouts can "
		"be given as one, like us,de, with grp:alt_shift_toggle to switch."));

	add(box, section_title("Repeating keys"));
	struct c8ui_widget *delay = bound_slider("keyboard", "repeat_delay",
		"Delay before a held key repeats", 150, 1000, 10, 600, "%.0f");
	c8ui_slider_set_labels(delay, "Short", "Long");
	add(box, delay);
	struct c8ui_widget *rate = bound_slider("keyboard", "repeat_rate",
		"Repeat rate", 5, 60, 1, 25, "%.0f");
	c8ui_slider_set_labels(rate, "Slow", "Fast");
	add(box, rate);
	struct c8ui_widget *test = c8ui_entry_new("Try it here", "", NULL, NULL);
	add(box, test);
}

static void keyboard_refresh(void) {
	if (kb.layout && !kb.layout->focused) {
		fill_layouts();
	}
	if (kb.variant && !kb.variant->focused) {
		fill_variants();
	}
}

const struct page page_keyboard = {
	.name = "keyboard",
	.title = "Keyboard",
	.build = keyboard_build,
	.refresh = keyboard_refresh,
};

/* Power */

static const int idle_minutes[] = {
	1, 2, 3, 5, 10, 15, 20, 25, 30, 45, 60, 120, 180, 240, 300, 0,
};
#define IDLE_COUNT (int)(sizeof(idle_minutes) / sizeof(idle_minutes[0]))

static void idle_changed(struct c8ui_widget *w, void *data) {
	int i = c8ui_combo_get(w);
	if (i >= 0 && i < IDLE_COUNT) {
		char value[16];
		snprintf(value, sizeof(value), "%d", idle_minutes[i]);
		setting_set("power", data, value);
	}
}

static struct c8ui_widget *idle_combo(const char *key, const char *header,
		int def) {
	static char labels[IDLE_COUNT][24];
	const char *items[IDLE_COUNT];
	int current = (int)setting_double("power", key, def), selected = -1;
	for (int i = 0; i < IDLE_COUNT; i++) {
		int m = idle_minutes[i];
		if (m == 0) {
			snprintf(labels[i], sizeof(labels[i]), "Never");
		} else if (m >= 60) {
			snprintf(labels[i], sizeof(labels[i]), "%d hour%s", m / 60,
				m == 60 ? "" : "s");
		} else {
			snprintf(labels[i], sizeof(labels[i]), "%d minute%s", m,
				m == 1 ? "" : "s");
		}
		items[i] = labels[i];
		if (m == (current > 0 ? current : 0)) {
			selected = i;
		}
	}
	return c8ui_combo_new(header, items, IDLE_COUNT, selected, idle_changed,
		(void *)key);
}

static void power_build(struct c8ui_widget *box) {
	add(box, power_mode_new());
	add(box, section_title("When I'm not using the PC"));
	add(box, idle_combo("screen_off_after", "Turn off the screen after", 10));
	add(box, idle_combo("sleep_after", "Put the PC to sleep after", 30));
	add(box, caption("Apps that play video or presentations keep the screen "
		"on while they need it."));

	add(box, section_title("Power menu"));
	add(box, caption("The commands behind the power menu on Start. Leave one "
		"empty to take it off the menu."));
	add(box, bound_entry("power", "lock", "Lock", NULL));
	add(box, bound_entry("power", "sleep", "Sleep", NULL));
	add(box, bound_entry("power", "restart", "Restart", NULL));
	add(box, bound_entry("power", "shutdown", "Shut down", NULL));
}

const struct page page_power = {
	.name = "power",
	.title = "Power",
	.build = power_build,
};

/* XR: XR glasses, [glasses]. Defaults as the compositor's */

static struct {
	struct c8ui_widget *neck_up, *neck_ahead;
	struct c8ui_widget *background; // the picture's name
} xr;

#define NECK_UP 0.075
#define NECK_AHEAD 0.08

/* neck is one key, "up ahead": both sliders write it */
static void neck_read(double *up, double *ahead) {
	*up = NECK_UP;
	*ahead = NECK_AHEAD;
	const char *v = setting("glasses", "neck");
	double u, a;
	if (v && sscanf(v, "%lf %lf", &u, &a) == 2) {
		*up = u;
		*ahead = a;
	}
}

static void neck_changed(struct c8ui_widget *w, void *data) {
	if (c8ui_slider_is_live(w) || !xr.neck_up || !xr.neck_ahead) {
		return;
	}
	char value[64];
	snprintf(value, sizeof(value), "%.3f %.3f", c8ui_slider_get(xr.neck_up),
		c8ui_slider_get(xr.neck_ahead));
	setting_set("glasses", "neck", value);
}

static struct c8ui_widget *neck_slider(const char *header, double value,
		struct c8ui_widget **slot) {
	struct c8ui_widget *w = c8ui_slider_new(header, 0, 0.15, 0.005, value,
		neck_changed, NULL);
	c8ui_slider_set_format(w, "%.3f m");
	c8ui_widget_track(w, slot);
	return w;
}

static const char *const xr_keys[] = { "runtime", "fov", "distance",
	"start_distance", "ipd", "screen",
	"latency", "scanout", "tilt", "neck", "steady", "outlines",
	"background", "background_horizon" };

static void xr_reset_answered(int choice, void *data) {
	if (choice != 0) {
		return;
	}
	/* Taken out of config.ini, each key falls back to the default */
	for (size_t i = 0; i < sizeof(xr_keys) / sizeof(xr_keys[0]); i++) {
		setting_queue_remove("glasses", xr_keys[i]);
	}
	setting_commit();
}

static void xr_reset(struct c8ui_widget *w, void *data) {
	static const char *const buttons[] = { "Reset", "Cancel" };
	c8ui_dialog_show(app.root, "Reset XR settings?",
		"Everything on this page goes back to how it came, including "
		"anything you've fitted to your glasses or your head.", buttons,
		2, xr_reset_answered, NULL);
}

static struct c8ui_widget *slider(const char *key, const char *header,
		double min, double max, double step, double def, const char *save,
		const char *shown, const char *low, const char *high) {
	struct c8ui_widget *w = bound_slider("glasses", key, header, min, max,
		step, def, save);
	c8ui_slider_set_format(w, shown);
	if (low || high) {
		c8ui_slider_set_labels(w, low, high);
	}
	return w;
}

/* The 360 picture round you, [glasses] background */

static char *background_name(void) {
	const char *path = setting_or("glasses", "background", "");
	return path[0] ? g_path_get_basename(path) : g_strdup("None");
}

static void background_chosen(char **uris, void *data) {
	char *path = uris && uris[0] ? g_filename_from_uri(uris[0], NULL, NULL) :
		NULL;
	if (path) {
		setting_set("glasses", "background", path);
	}
	g_free(path);
}

static void background_choose(struct c8ui_widget *w, void *data) {
	static const struct c8ui_file_filter filters[] = {
		{ "Pictures", "*.jpg;*.jpeg;*.png;*.webp;*.tif;*.tiff",
			"image/jpeg;image/png;image/webp;image/tiff" },
		{ "All files", "*", NULL },
	};
	c8ui_file_open(app.window, &(struct c8ui_file_options){
		.title = "Choose a 360 picture", .filters = filters,
		.filter_count = 2,
	}, background_chosen, NULL);
}

static void background_none(struct c8ui_widget *w, void *data) {
	setting_queue_remove("glasses", "background");
	setting_commit();
}

static void xr_build(struct c8ui_widget *box) {
	add(box, caption("For XR glasses, when the Second screen flyout (Super+P) "
		"is on XR."));

	add(box, section_title("Glasses"));
	static const char *const runtimes[] = { "auto", "monado", "builtin" };
	static const char *const runtime_labels[] = {
		"Monado when it's installed (automatic)", "Monado", "Built in" };
	add(box, bound_choice("glasses", "runtime", "Drawn by", runtimes,
		runtime_labels, 3, 0));
	add(box, caption("Monado draws the glasses and runs VR games in them, "
		"with your apps over the game when you want them. Built in draws "
		"your apps only, without Monado. Changing it while in XR "
		"switches at once."));
	add(box, slider("fov", "Field of view", 30, 90, 1, 57, "%.0f", "%.0f°",
		NULL, NULL));
	add(box, caption("Your glasses' own, measured corner to corner (57° for "
		"XREAL One Pro). If windows slide about as you turn your head, "
		"this doesn't match them. Set the glasses to Follow, not Anchor: "
		"anchored, they pin the whole picture in place as a screen of "
		"its own."));

	add(box, section_title("Your space"));
	add(box, slider("distance", "Distance to the windows", 0.5, 5, 0.1, 2.5,
		"%.1f", "%.1f m", "Near", "Far"));
	add(box, caption("They keep their size in your view: further away "
		"moves them less as your head moves, and in 3D your eyes meet "
		"further off. Windows you've brought nearer or further keep "
		"their own distance."));
	add(box, slider("start_distance", "Distance to Start", 0.5, 8, 0.1, 2.5,
		"%.1f", "%.1f m", "Near", "Far"));
	add(box, caption("Start opens this far away and as wide as your groups "
		"run, so you look along it instead of scrolling. Further off, "
		"its tiles look smaller."));
	static const char *const screens[] = { "1280x720", "1600x900",
		"1920x1080", "2560x1440", "3840x2160" };
	static const char *const screen_labels[] = { "1280 × 720",
		"1600 × 900", "1920 × 1080 (fills the view)", "2560 × 1440",
		"3840 × 2160" };
	add(box, bound_choice("glasses", "screen", "Start's screen", screens,
		screen_labels, 5, 2));
	add(box, caption("The size of the screen Start, the charms and "
		"notifications are on. Bigger than the view, you look around it."));

	add(box, section_title("Background"));
	char *name = background_name();
	c8ui_widget_track(c8ui_label_new(name, C8UI_TEXT_BODY_STRONG),
		&xr.background);
	g_free(name);
	add(box, xr.background);
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 10);
	c8ui_box_set_wrap(row, true);
	add(row, c8ui_button_new("Choose a picture", background_choose, NULL));
	add(row, c8ui_button_new("None", background_none, NULL));
	add(box, row);
	add(box, caption("A 360 picture all round you, behind your apps: a "
		"full panorama (twice as wide as high), or a wider one, which "
		"goes round you at the horizon. Without one you see the room. "
		"It's most of what the graphics do in XR, so if things stutter, "
		"try None."));
	add(box, slider("background_horizon", "Horizon in the picture", 0, 100,
		1, 50, "%.0f", "%.0f%%", "Top", "Bottom"));
	add(box, caption("For a picture wider than a full panorama: how far "
		"down it the horizon is, so that's level with your eyes."));

	add(box, section_title("Head tracking"));
	add(box, caption("Drawn by Monado, these take effect the next time you "
		"go into XR."));
	add(box, bound_toggle("glasses", "steady", "Steady a still head",
		"While you hold your head still, windows don't shimmer with its "
		"tiny sway. As soon as it turns, they follow at full speed.",
		true));
	add(box, slider("latency", "Look ahead", 0, 60, 1, 15, "%.0f",
		"%.0f ms", "Less", "More"));
	add(box, caption("How far ahead to guess where your head will be when a "
		"picture shows. Too little and windows trail a turn; too much and "
		"they swing past where they should stop."));
	static const char *const scans[] = { "auto", "0" };
	static const char *const scan_labels[] = {
		"Row by row, one refresh (automatic)", "Off" };
	add(box, bound_choice("glasses", "scanout", "Lighting the rows", scans,
		scan_labels, 2, 0));
	add(box, caption("The glasses light the picture from the top down. Row "
		"by row, each is drawn for where your head is then, so a window's "
		"bottom doesn't lag its top as you turn."));
	add(box, slider("tilt", "Sensor tilt", -10, 70, 1, 40, "%.0f", "%.0f°",
		NULL, NULL));
	add(box, caption("How far up the glasses' sensor points from your line "
		"of sight (40° on the One Pro). If tilting your head to one side "
		"swings the view sideways, this is off."));
	double up, ahead;
	neck_read(&up, &ahead);
	add(box, neck_slider("Eyes above the neck's pivot", up, &xr.neck_up));
	add(box, neck_slider("Eyes in front of the neck's pivot", ahead,
		&xr.neck_ahead));
	add(box, caption("Your eyes swing round your neck as you turn or nod, "
		"so the windows should stay put. An average head's is the "
		"default."));
	add(box, caption("Super+Ctrl+Space puts in front of you whatever "
		"you're looking at."));

	add(box, section_title("3D"));
	add(box, slider("ipd", "Distance between your eyes", 45, 85, 0.5, 63,
		"%.1f", "%.1f mm", NULL, NULL));
	add(box, caption("Only in the glasses' 3D mode (side by side), for your "
		"apps and VR games alike. An optician can measure it; 63 mm is "
		"about average."));

	add(box, section_title("Recording"));
	add(box, bound_toggle("glasses", "outlines", "Show the space as outlines",
		"A floor grid, a frame round every app and a line from each down "
		"to the floor, so a recording of what the glasses show (OBS, "
		"screen capture) makes sense to someone not wearing them. You "
		"see them too, and drawn by Monado they cost some smoothness.",
		false));

	add(box, section_title("Defaults"));
	add(box, c8ui_button_new("Reset all to defaults", xr_reset, NULL));
}

static void xr_refresh(void) {
	if (xr.background) {
		char *name = background_name();
		c8ui_label_set_text(xr.background, name);
		g_free(name);
	}
	double up, ahead;
	neck_read(&up, &ahead);
	if (xr.neck_up && !xr.neck_up->focused) {
		c8ui_slider_set(xr.neck_up, up);
	}
	if (xr.neck_ahead && !xr.neck_ahead->focused) {
		c8ui_slider_set(xr.neck_ahead, ahead);
	}
}

const struct page page_xr = {
	.name = "xr",
	.title = "XR",
	.build = xr_build,
	.refresh = xr_refresh,
};

/* General */

static struct {
	char **fonts, **themes, **cursors;
	int font_n, theme_n, cursor_n;
} general;

/* Pointer sizes offered, as XCURSOR_SIZE */
static const int cursor_sizes[] = { 24, 32, 48, 64 };
static const char *const cursor_size_names[] = {
	"Standard", "Large", "Extra large", "Huge",
};
#define CURSOR_SIZE_N 4

static const char *const corner_values[] = { "top-right", "top-left",
	"bottom-right", "bottom-left" };
static const char *const corner_names[] = { "Top right", "Top left",
	"Bottom right", "Bottom left" };

static int corner_index(void) {
	const char *now = setting_or("notifications", "corner", "top-right");
	for (int i = 0; i < 4; i++) {
		if (strcmp(now, corner_values[i]) == 0) {
			return i;
		}
	}
	return 0;
}

static void corner_changed(struct c8ui_widget *w, void *data) {
	int i = c8ui_combo_get(w);
	if (i >= 0 && i < 4) {
		setting_set("notifications", "corner", corner_values[i]);
	}
}

static const char *const clock_values[] = { "auto", "12", "24" };
static const char *const clock_names[] = { "As my language does",
	"12-hour", "24-hour" };

static int clock_index(void) {
	const char *now = setting_or("general", "clock", "auto");
	for (int i = 0; i < 3; i++) {
		if (strcmp(now, clock_values[i]) == 0) {
			return i;
		}
	}
	return 0;
}

static void clock_changed(struct c8ui_widget *w, void *data) {
	int i = c8ui_combo_get(w);
	if (i >= 0 && i < 3) {
		setting_set("general", "clock", clock_values[i]);
	}
}

static int str_cmp(const void *a, const void *b) {
	return g_utf8_collate(*(char *const *)a, *(char *const *)b);
}

static void load_fonts(void) {
	if (general.fonts) {
		return;
	}
	PangoFontMap *map = pango_cairo_font_map_get_default();
	PangoFontFamily **families;
	int n;
	pango_font_map_list_families(map, &families, &n);
	general.fonts = calloc(n + 2, sizeof(char *));
	general.fonts[general.font_n++] = g_strdup("Selawik (standard)");
	char **names = calloc(n + 1, sizeof(char *));
	for (int i = 0; i < n; i++) {
		names[i] = g_strdup(pango_font_family_get_name(families[i]));
	}
	qsort(names, n, sizeof(char *), str_cmp);
	for (int i = 0; i < n; i++) {
		general.fonts[general.font_n++] = names[i];
	}
	free(names);
	g_free(families);
}

static void add_unique(GPtrArray *found, const char *name) {
	for (guint i = 0; i < found->len; i++) {
		if (strcmp(g_ptr_array_index(found, i), name) == 0) {
			return;
		}
	}
	g_ptr_array_add(found, g_strdup(name));
}

/* A cursor theme is any folder with a cursors/ folder in it */
static void add_cursors_in(const char *dir, GPtrArray *found) {
	DIR *d = opendir(dir);
	if (d == NULL) {
		return;
	}
	struct dirent *ent;
	while ((ent = readdir(d))) {
		if (ent->d_name[0] == '.' || strcmp(ent->d_name, "default") == 0) {
			continue;
		}
		char *cursors = g_build_filename(dir, ent->d_name, "cursors", NULL);
		if (g_file_test(cursors, G_FILE_TEST_IS_DIR)) {
			add_unique(found, ent->d_name);
		}
		g_free(cursors);
	}
	closedir(d);
}

static void add_themes_in(const char *dir, GPtrArray *found) {
	DIR *d = opendir(dir);
	if (d == NULL) {
		return;
	}
	struct dirent *ent;
	while ((ent = readdir(d))) {
		if (ent->d_name[0] == '.' || strcmp(ent->d_name, "hicolor") == 0 ||
				strcmp(ent->d_name, "default") == 0) {
			continue;
		}
		char *index = g_build_filename(dir, ent->d_name, "index.theme", NULL);
		GKeyFile *kf = g_key_file_new();
		/* Cursor themes have an index but no icon directories */
		if (g_key_file_load_from_file(kf, index, G_KEY_FILE_NONE, NULL) &&
				g_key_file_has_key(kf, "Icon Theme", "Directories", NULL)) {
			add_unique(found, ent->d_name);
		}
		g_key_file_free(kf);
		g_free(index);
	}
	closedir(d);
}

/* "Automatic" and then the themes add_in finds in every icon folder,
 * sorted */
static char **find_themes(void (*add_in)(const char *, GPtrArray *), int *n) {
	GPtrArray *found = g_ptr_array_new();
	char *home = g_build_filename(g_get_home_dir(), ".icons", NULL);
	add_in(home, found);
	g_free(home);
	char *user = g_build_filename(g_get_user_data_dir(), "icons", NULL);
	add_in(user, found);
	g_free(user);
	for (const char *const *d = g_get_system_data_dirs(); *d; d++) {
		char *dir = g_build_filename(*d, "icons", NULL);
		add_in(dir, found);
		g_free(dir);
	}
	qsort(found->pdata, found->len, sizeof(char *), str_cmp);
	char **themes = calloc(found->len + 2, sizeof(char *));
	*n = 0;
	themes[(*n)++] = g_strdup("Automatic");
	for (guint i = 0; i < found->len; i++) {
		themes[(*n)++] = g_ptr_array_index(found, i);
	}
	g_ptr_array_free(found, FALSE);
	return themes;
}

static void load_themes(void) {
	if (general.themes == NULL) {
		general.themes = find_themes(add_themes_in, &general.theme_n);
	}
	if (general.cursors == NULL) {
		general.cursors = find_themes(add_cursors_in, &general.cursor_n);
	}
}

static int font_index(void) {
	const char *now = setting_or("general", "font", "");
	/* "Selawik, sans-serif": the first family is the choice */
	char *first = g_strndup(now, strcspn(now, ","));
	g_strstrip(first);
	int index = 0;
	if (strcmp(first, "Selawik") != 0) {
		for (int i = 1; i < general.font_n; i++) {
			if (g_ascii_strcasecmp(general.fonts[i], first) == 0) {
				index = i;
			}
		}
	}
	g_free(first);
	return index;
}

static int theme_index(void) {
	const char *now = setting_or("general", "icon_theme", "");
	for (int i = 1; i < general.theme_n; i++) {
		if (strcmp(general.themes[i], now) == 0) {
			return i;
		}
	}
	return 0;
}

static int cursor_index(void) {
	const char *now = setting_or("general", "cursor_theme", "");
	for (int i = 1; i < general.cursor_n; i++) {
		if (strcmp(general.cursors[i], now) == 0) {
			return i;
		}
	}
	return 0;
}

/* The nearest offered size, for one typed into config.ini */
static int cursor_size_index(void) {
	int size = atoi(setting_or("general", "cursor_size", "24"));
	int best = 0;
	for (int i = 1; i < CURSOR_SIZE_N; i++) {
		if (abs(cursor_sizes[i] - size) < abs(cursor_sizes[best] - size)) {
			best = i;
		}
	}
	return best;
}

static void font_changed(struct c8ui_widget *w, void *data) {
	int i = c8ui_combo_get(w);
	if (i == 0) {
		setting_set("general", "font", "");
	} else if (i > 0) {
		char value[256];
		snprintf(value, sizeof(value), "%s, sans-serif", general.fonts[i]);
		setting_set("general", "font", value);
	}
}

static void theme_changed(struct c8ui_widget *w, void *data) {
	int i = c8ui_combo_get(w);
	if (i >= 0) {
		setting_set("general", "icon_theme", i == 0 ? "" : general.themes[i]);
	}
}

static void cursor_changed(struct c8ui_widget *w, void *data) {
	int i = c8ui_combo_get(w);
	if (i >= 0) {
		setting_set("general", "cursor_theme", i == 0 ? "" : general.cursors[i]);
	}
}

static void cursor_size_changed(struct c8ui_widget *w, void *data) {
	int i = c8ui_combo_get(w);
	if (i >= 0 && i < CURSOR_SIZE_N) {
		char value[16];
		snprintf(value, sizeof(value), "%d", cursor_sizes[i]);
		setting_set("general", "cursor_size", value);
	}
}

static void stealth_changed(struct c8ui_widget *w, void *data) {
	setting_set("stealth", "on", c8ui_toggle_get(w) ? "true" : "false");
}

static void general_build(struct c8ui_widget *box) {
	load_fonts();
	load_themes();
	add(box, section_title("Apps"));
	add(box, bound_entry("general", "terminal", "Terminal", "foot"));
	add(box, caption("Super+Enter and the Terminal tile run this."));

	add(box, section_title("Appearance"));
	add(box, bound_combo(c8ui_combo_new("Font",
		(const char *const *)general.fonts, general.font_n, font_index(),
		font_changed, NULL), font_index));
	add(box, bound_combo(c8ui_combo_new("Icons",
		(const char *const *)general.themes, general.theme_n, theme_index(),
		theme_changed, NULL), theme_index));
	add(box, bound_combo(c8ui_combo_new("Pointer",
		(const char *const *)general.cursors, general.cursor_n,
		cursor_index(), cursor_changed, NULL), cursor_index));
	add(box, bound_combo(c8ui_combo_new("Pointer size", cursor_size_names,
		CURSOR_SIZE_N, cursor_size_index(), cursor_size_changed, NULL),
		cursor_size_index));
	add(box, caption("Apps that draw their own pointer pick a new one up "
		"when they're opened again."));

	add(box, section_title("Clock"));
	add(box, bound_combo(c8ui_combo_new("Show the time as", clock_names, 3,
		clock_index(), clock_changed, NULL), clock_index));
	add(box, caption("On the charms bar, the lock screen and the clock "
		"tiles. The sign-in screen has its own setting."));

	add(box, section_title("Notifications"));
	add(box, bound_combo(c8ui_combo_new("Show notifications in",
		corner_names, 4, corner_index(), corner_changed, NULL),
		corner_index));
	add(box, caption("Swipe one towards the edge to dismiss it."));

	add(box, section_title("X11 apps"));
	add(box, bound_toggle("general", "xwayland", "Run X11 apps",
		"Through Xwayland, started when the first one opens. Takes effect "
		"the next time you sign in.", true));

	/* Not in the snapshot (the compositor doesn't use it), so read
	 * through c8-base, which every program showing it uses */
	add(box, section_title("Screenshots and recordings"));
	add(box, c8ui_toggle_new("Stealth mode", "Show a made-up name, picture, "
		"PC name, networks, places and addresses instead of yours, on the "
		"desktop and in the apps. Only what's shown changes.", c8_stealth(),
		stealth_changed, NULL));
}

const struct page page_general = {
	.name = "general",
	.title = "General",
	.build = general_build,
};
