/*
 * Displays, through wlr-output-management: the same protocol wlr-randr and
 * kanshi use. Changes apply straight away and revert unless kept, like
 * Windows does; kept ones are saved as [output NAME] sections.
 */
#define _GNU_SOURCE
#include <glib.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "settings.h"
#include "wlr-output-management-unstable-v1-client-protocol.h"

#define KEEP_SECONDS 15
#define CANVAS_HEIGHT 240

struct mode {
	struct wl_list link; // head.modes
	struct zwlr_output_mode_v1 *wlr;
	struct head *head;
	int width, height, refresh; // mHz
	bool preferred;
};

struct state {
	bool enabled;
	int width, height, refresh;
	int x, y;
	int transform;
	double scale;
};

struct head {
	struct wl_list link; // disp.heads
	struct zwlr_output_head_v1 *wlr;
	char *name, *description, *make, *model;
	struct wl_list modes;
	struct mode *current;
	struct state now; // as the compositor says
	struct state edit; // as shown
	struct state saved; // before applying, for reverting
};

enum purpose {
	APPLY,
	REVERT,
};

static struct {
	struct zwlr_output_manager_v1 *manager;
	uint32_t serial;
	struct wl_list heads;
	bool dirty;
	struct head *selected;
	struct c8ui_widget *canvas, *controls, *apply;
	struct c8ui_widget *project; // the Second screen choice's box
	int project_shown; // which choices it has: 0 none, 1 screens, 2 glasses
	/* Dragging a display about */
	struct head *drag;
	double grab_x, grab_y;
	double fit, ox, oy, min_x, min_y; // the view, fixed while dragging
	/* Keep or revert */
	struct c8ui_widget *dialog;
	void *timer;
	int seconds;
} disp;

static void update_ui(void);

/* Geometry */

static void logical_size(const struct state *s, double *w, double *h) {
	double scale = s->scale > 0 ? s->scale : 1;
	*w = s->width / scale;
	*h = s->height / scale;
	if (s->transform % 2 == 1) {
		double t = *w;
		*w = *h;
		*h = t;
	}
}

static int head_index(struct head *h) {
	int i = 0;
	struct head *it;
	wl_list_for_each(it, &disp.heads, link) {
		if (it == h) {
			return i;
		}
		i++;
	}
	return -1;
}

/* The arrangement view: fit every display on into the canvas; ones that
 * are off sit in a row to the right */
static void compute_view(struct c8ui_widget *w) {
	double min_x = INFINITY, min_y = INFINITY, max_x = -INFINITY, max_y = -INFINITY;
	struct head *h;
	wl_list_for_each(h, &disp.heads, link) {
		if (!h->edit.enabled) {
			continue;
		}
		double lw, lh;
		logical_size(&h->edit, &lw, &lh);
		min_x = fmin(min_x, h->edit.x);
		min_y = fmin(min_y, h->edit.y);
		max_x = fmax(max_x, h->edit.x + lw);
		max_y = fmax(max_y, h->edit.y + lh);
	}
	if (!isfinite(min_x)) {
		min_x = min_y = 0;
		max_x = 1920;
		max_y = 1080;
	}
	double extra = 0;
	wl_list_for_each(h, &disp.heads, link) {
		if (!h->edit.enabled) {
			double lw, lh;
			logical_size(&h->edit, &lw, &lh);
			extra += (lw > 0 ? lw : 1920) * 0.5 + 200;
			max_y = fmax(max_y, min_y + (lh > 0 ? lh : 1080) * 0.5);
		}
	}
	double bw = max_x - min_x + extra, bh = max_y - min_y;
	double fit = fmin((w->rect.width - 40) / bw, (w->rect.height - 40) / bh);
	disp.fit = fit > 0 ? fit : 0.05;
	disp.min_x = min_x;
	disp.min_y = min_y;
	disp.ox = w->rect.x + (w->rect.width - bw * disp.fit) / 2;
	disp.oy = w->rect.y + (w->rect.height - bh * disp.fit) / 2;
}

static struct c8ui_rect head_rect(struct head *h) {
	double lw, lh;
	logical_size(&h->edit, &lw, &lh);
	if (h->edit.enabled) {
		return (struct c8ui_rect){
			disp.ox + (h->edit.x - disp.min_x) * disp.fit,
			disp.oy + (h->edit.y - disp.min_y) * disp.fit,
			lw * disp.fit, lh * disp.fit,
		};
	}
	/* Off: half size, after the ones that are on */
	double x = -INFINITY;
	struct head *it;
	wl_list_for_each(it, &disp.heads, link) {
		if (it->edit.enabled) {
			double w, hh;
			logical_size(&it->edit, &w, &hh);
			x = fmax(x, it->edit.x + w);
		}
	}
	x = isfinite(x) ? x + 200 : disp.min_x;
	wl_list_for_each(it, &disp.heads, link) {
		if (it == h) {
			break;
		}
		if (!it->edit.enabled) {
			double w, hh;
			logical_size(&it->edit, &w, &hh);
			x += (w > 0 ? w : 1920) * 0.5 + 200;
		}
	}
	lw = (lw > 0 ? lw : 1920) * 0.5;
	lh = (lh > 0 ? lh : 1080) * 0.5;
	return (struct c8ui_rect){ disp.ox + (x - disp.min_x) * disp.fit,
		disp.oy, lw * disp.fit, lh * disp.fit };
}

static void canvas_draw(struct c8ui_widget *w, cairo_t *cr, void *data) {
	struct c8ui_colors c = c8ui_widget_colors(w);
	if (disp.drag == NULL) {
		compute_view(w);
	}
	const char *font = c8ui_widget_font(w);
	struct head *h;
	wl_list_for_each(h, &disp.heads, link) {
		struct c8ui_rect r = head_rect(h);
		bool sel = h == disp.selected;
		if (h->edit.enabled) {
			c8ui_set_source(cr, sel ? c.accent : 0x808080, sel ? 1 : 0.55);
			cairo_rectangle(cr, r.x + 1, r.y + 1, r.width - 2, r.height - 2);
			cairo_fill(cr);
		} else {
			c8ui_set_source(cr, sel ? c.accent : c.fg, sel ? 1 : 0.4);
			double dash[] = { 4, 3 };
			cairo_set_dash(cr, dash, 2, 0);
			cairo_set_line_width(cr, 2);
			cairo_rectangle(cr, r.x + 2, r.y + 2, r.width - 4, r.height - 4);
			cairo_stroke(cr);
			cairo_set_dash(cr, NULL, 0, 0);
		}
		char number[16];
		snprintf(number, sizeof(number), "%d", head_index(h) + 1);
		struct c8ui_font big = c8ui_text_font(C8UI_TEXT_HEADER);
		double tw, th;
		c8ui_text_size(font, big, number, 0, 0, &tw, &th);
		if (h->edit.enabled) {
			cairo_set_source_rgb(cr, 1, 1, 1);
		} else {
			c8ui_set_source(cr, c.fg, 0.6);
		}
		c8ui_text_draw(cr, font, big, number, r.x + (r.width - tw) / 2,
			r.y + (r.height - th) / 2 - 6, 0, 0);
		struct c8ui_font small = c8ui_text_font(C8UI_TEXT_CAPTION);
		c8ui_text_size(font, small, h->name, 0, 0, &tw, &th);
		c8ui_text_draw(cr, font, small, h->name, r.x + (r.width - tw) / 2,
			r.y + r.height - th - 6, r.width - 8, 1);
	}
}

static struct head *head_at(double x, double y) {
	struct head *h, *found = NULL;
	wl_list_for_each(h, &disp.heads, link) {
		struct c8ui_rect r = head_rect(h);
		if (c8ui_rect_contains(&r, x, y)) {
			found = h;
		}
	}
	return found;
}

/* Let go: make the display touch the nearest other one, lined up with
 * its edges when close */
static void snap(struct head *d) {
	double dw, dh;
	logical_size(&d->edit, &dw, &dh);
	double best = INFINITY, bx = d->edit.x, by = d->edit.y;
	struct head *o;
	wl_list_for_each(o, &disp.heads, link) {
		if (o == d || !o->edit.enabled) {
			continue;
		}
		double ow, oh;
		logical_size(&o->edit, &ow, &oh);
		double ox = o->edit.x, oy = o->edit.y;
		struct { double x, y; bool horizontal; } spots[] = {
			{ ox - dw, d->edit.y, true }, { ox + ow, d->edit.y, true },
			{ d->edit.x, oy - dh, false }, { d->edit.x, oy + oh, false },
		};
		for (int i = 0; i < 4; i++) {
			double x = spots[i].x, y = spots[i].y;
			double threshold;
			if (spots[i].horizontal) {
				/* Keep some overlap, and line up edges that are close */
				y = fmin(fmax(y, oy - dh + 1), oy + oh - 1);
				threshold = oh * 0.1;
				if (fabs(y - oy) < threshold) {
					y = oy;
				} else if (fabs(y + dh - oy - oh) < threshold) {
					y = oy + oh - dh;
				}
			} else {
				x = fmin(fmax(x, ox - dw + 1), ox + ow - 1);
				threshold = ow * 0.1;
				if (fabs(x - ox) < threshold) {
					x = ox;
				} else if (fabs(x + dw - ox - ow) < threshold) {
					x = ox + ow - dw;
				}
			}
			double dist = hypot(x - d->edit.x, y - d->edit.y);
			if (dist < best) {
				best = dist;
				bx = x;
				by = y;
			}
		}
	}
	d->edit.x = (int)lround(bx);
	d->edit.y = (int)lround(by);

	/* The top-left display sits at 0,0 */
	int min_x = INT32_MAX, min_y = INT32_MAX;
	wl_list_for_each(o, &disp.heads, link) {
		if (o->edit.enabled) {
			min_x = o->edit.x < min_x ? o->edit.x : min_x;
			min_y = o->edit.y < min_y ? o->edit.y : min_y;
		}
	}
	wl_list_for_each(o, &disp.heads, link) {
		if (o->edit.enabled && min_x != INT32_MAX) {
			o->edit.x -= min_x;
			o->edit.y -= min_y;
		}
	}
}

static void set_dirty(void) {
	disp.dirty = true;
	if (disp.apply) {
		c8ui_widget_set_disabled(disp.apply, false);
	}
	if (disp.canvas) {
		c8ui_widget_queue_draw(disp.canvas);
	}
}

static bool canvas_event(struct c8ui_widget *w, const struct c8ui_event *ev,
		void *data) {
	switch (ev->type) {
	case C8UI_EVENT_PRESS: {
		if (ev->button != C8UI_BUTTON_LEFT) {
			return false;
		}
		struct head *h = head_at(ev->x, ev->y);
		if (h == NULL) {
			return false;
		}
		if (h != disp.selected) {
			disp.selected = h;
			update_ui();
		}
		if (h->edit.enabled) {
			compute_view(w);
			disp.drag = h;
			disp.grab_x = (ev->x - disp.ox) / disp.fit + disp.min_x - h->edit.x;
			disp.grab_y = (ev->y - disp.oy) / disp.fit + disp.min_y - h->edit.y;
		}
		c8ui_widget_queue_draw(w);
		return true;
	}
	case C8UI_EVENT_MOTION:
		if (disp.drag) {
			struct head *h = disp.drag;
			h->edit.x = (int)lround((ev->x - disp.ox) / disp.fit + disp.min_x -
				disp.grab_x);
			h->edit.y = (int)lround((ev->y - disp.oy) / disp.fit + disp.min_y -
				disp.grab_y);
			set_dirty();
		}
		return true;
	case C8UI_EVENT_RELEASE:
		if (disp.drag) {
			snap(disp.drag);
			disp.drag = NULL;
			set_dirty();
		}
		return true;
	default:
		return false;
	}
}

/* Choosing modes */

static int size_cmp(const void *a, const void *b) {
	const int *x = a, *y = b;
	return (y[0] * y[1]) - (x[0] * x[1]) ?: y[0] - x[0];
}

static int int_desc(const void *a, const void *b) {
	return *(const int *)b - *(const int *)a;
}

/* The distinct sizes, largest first, as width, height pairs */
static int head_sizes(struct head *h, int *out, int max) {
	int n = 0;
	struct mode *m;
	wl_list_for_each(m, &h->modes, link) {
		bool dup = false;
		for (int i = 0; i < n && !dup; i++) {
			dup = out[2 * i] == m->width && out[2 * i + 1] == m->height;
		}
		if (!dup && n < max) {
			out[2 * n] = m->width;
			out[2 * n + 1] = m->height;
			n++;
		}
	}
	qsort(out, n, 2 * sizeof(int), size_cmp);
	return n;
}

static int head_rates(struct head *h, int width, int height, int *out, int max) {
	int n = 0;
	struct mode *m;
	wl_list_for_each(m, &h->modes, link) {
		if (m->width == width && m->height == height && n < max) {
			bool dup = false;
			for (int i = 0; i < n; i++) {
				dup |= out[i] == m->refresh;
			}
			if (!dup) {
				out[n++] = m->refresh;
			}
		}
	}
	qsort(out, n, sizeof(int), int_desc);
	return n;
}

static bool size_preferred(struct head *h, int width, int height) {
	struct mode *m;
	wl_list_for_each(m, &h->modes, link) {
		if (m->preferred && m->width == width && m->height == height) {
			return true;
		}
	}
	return false;
}

static int best_rate(struct head *h, int width, int height) {
	int best = 0;
	struct mode *m;
	wl_list_for_each(m, &h->modes, link) {
		if (m->width == width && m->height == height) {
			if (m->preferred) {
				return m->refresh;
			}
			best = m->refresh > best ? m->refresh : best;
		}
	}
	return best;
}

static struct mode *find_mode(struct head *h, const struct state *s) {
	struct mode *m, *best = NULL;
	wl_list_for_each(m, &h->modes, link) {
		if (m->width == s->width && m->height == s->height &&
				(best == NULL ||
				abs(m->refresh - s->refresh) < abs(best->refresh - s->refresh))) {
			best = m;
		}
	}
	return best;
}

/* Applying */

static void config_succeeded(void *data,
		struct zwlr_output_configuration_v1 *config);
static void config_failed(void *data,
		struct zwlr_output_configuration_v1 *config);
static void config_cancelled(void *data,
		struct zwlr_output_configuration_v1 *config);

static const struct zwlr_output_configuration_v1_listener config_listener = {
	.succeeded = config_succeeded,
	.failed = config_failed,
	.cancelled = config_cancelled,
};

static void send_config(bool use_saved, enum purpose purpose) {
	struct zwlr_output_configuration_v1 *config =
		zwlr_output_manager_v1_create_configuration(disp.manager, disp.serial);
	struct head *h;
	wl_list_for_each(h, &disp.heads, link) {
		const struct state *s = use_saved ? &h->saved : &h->edit;
		if (!s->enabled) {
			zwlr_output_configuration_v1_disable_head(config, h->wlr);
			continue;
		}
		struct zwlr_output_configuration_head_v1 *ch =
			zwlr_output_configuration_v1_enable_head(config, h->wlr);
		struct mode *m = find_mode(h, s);
		if (m) {
			zwlr_output_configuration_head_v1_set_mode(ch, m->wlr);
		} else if (s->width > 0 && s->height > 0) {
			zwlr_output_configuration_head_v1_set_custom_mode(ch, s->width,
				s->height, s->refresh);
		}
		zwlr_output_configuration_head_v1_set_position(ch, s->x, s->y);
		zwlr_output_configuration_head_v1_set_transform(ch, s->transform);
		zwlr_output_configuration_head_v1_set_scale(ch,
			wl_fixed_from_double(s->scale > 0 ? s->scale : 1));
	}
	zwlr_output_configuration_v1_add_listener(config, &config_listener,
		(void *)(uintptr_t)purpose);
	zwlr_output_configuration_v1_apply(config);
}

static const char *transform_names[] = {
	"normal", "90", "180", "270",
	"flipped", "flipped-90", "flipped-180", "flipped-270",
};

static void persist(void) {
	struct head *h;
	wl_list_for_each(h, &disp.heads, link) {
		char section[300], value[64];
		snprintf(section, sizeof(section), "output %s", h->name);
		const struct state *s = &h->now;
		setting_queue_set(section, "enabled", s->enabled ? "true" : "false");
		if (!s->enabled) {
			continue;
		}
		if (s->width > 0) {
			snprintf(value, sizeof(value), "%dx%d@%.3f", s->width, s->height,
				s->refresh / 1000.0);
			setting_queue_set(section, "mode", value);
		}
		snprintf(value, sizeof(value), "%d,%d", s->x, s->y);
		setting_queue_set(section, "position", value);
		snprintf(value, sizeof(value), "%g", s->scale > 0 ? s->scale : 1);
		setting_queue_set(section, "scale", value);
		setting_queue_set(section, "transform",
			transform_names[s->transform & 7]);
	}
	setting_commit();
}

static void keep_choice(int choice, void *data) {
	if (disp.timer) {
		c8ui_root_timer_remove(app.root, disp.timer);
		disp.timer = NULL;
	}
	disp.dialog = NULL;
	if (choice == 0) {
		persist();
	} else {
		send_config(true, REVERT);
	}
}

static void countdown_text(char *buf, size_t len) {
	snprintf(buf, len, "Going back to the old settings in %d second%s.",
		disp.seconds, disp.seconds == 1 ? "" : "s");
}

static int countdown(void *data) {
	if (--disp.seconds <= 0) {
		disp.timer = NULL;
		c8ui_dialog_close(disp.dialog); /* reverts */
		return 0;
	}
	char text[128];
	countdown_text(text, sizeof(text));
	c8ui_dialog_set_message(disp.dialog, text);
	return 1000;
}

static void config_succeeded(void *data,
		struct zwlr_output_configuration_v1 *config) {
	enum purpose purpose = (uintptr_t)data;
	zwlr_output_configuration_v1_destroy(config);
	disp.dirty = false;
	if (purpose != APPLY || app.root == NULL) {
		update_ui();
		return;
	}
	disp.seconds = KEEP_SECONDS;
	char text[128];
	countdown_text(text, sizeof(text));
	const char *buttons[] = { "Keep changes", "Revert" };
	disp.dialog = c8ui_dialog_show(app.root, "Keep these display settings?",
		text, buttons, 2, keep_choice, NULL);
	disp.timer = c8ui_root_timer_add(app.root, 1000, countdown, NULL);
}

static void config_failed(void *data,
		struct zwlr_output_configuration_v1 *config) {
	zwlr_output_configuration_v1_destroy(config);
	show_error("Couldn't use these settings",
		"The display didn't accept them. Nothing has changed.");
}

static void config_cancelled(void *data,
		struct zwlr_output_configuration_v1 *config) {
	zwlr_output_configuration_v1_destroy(config);
	show_error("The displays changed",
		"A display was connected or changed while applying. Try again.");
}

/* Controls */

static void apply_clicked(struct c8ui_widget *w, void *data) {
	struct head *h;
	bool any = false;
	wl_list_for_each(h, &disp.heads, link) {
		h->saved = h->now;
		any |= h->edit.enabled;
	}
	if (!any) {
		show_error("One display has to stay on", "Turn another display on "
			"before turning this one off.");
		return;
	}
	send_config(false, APPLY);
}

static void cancel_clicked(struct c8ui_widget *w, void *data) {
	struct head *h;
	wl_list_for_each(h, &disp.heads, link) {
		h->edit = h->now;
	}
	disp.dirty = false;
	update_ui();
}

static void enabled_changed(struct c8ui_widget *w, void *data) {
	struct head *h = disp.selected;
	if (h == NULL) {
		return;
	}
	h->edit.enabled = c8ui_toggle_get(w);
	if (h->edit.enabled && h->edit.width == 0) {
		struct mode *m;
		wl_list_for_each(m, &h->modes, link) {
			if (m->preferred) {
				h->edit.width = m->width;
				h->edit.height = m->height;
				h->edit.refresh = m->refresh;
			}
		}
	}
	if (h->edit.enabled) {
		/* Back on: put it to the right of the others */
		int right = 0;
		struct head *o;
		wl_list_for_each(o, &disp.heads, link) {
			if (o != h && o->edit.enabled) {
				double ow, oh;
				logical_size(&o->edit, &ow, &oh);
				int r = o->edit.x + (int)ceil(ow);
				right = r > right ? r : right;
			}
		}
		h->edit.x = right;
		h->edit.y = 0;
	}
	set_dirty();
	update_ui();
}

static void size_changed(struct c8ui_widget *w, void *data) {
	struct head *h = disp.selected;
	int sizes[128];
	int n = head_sizes(h, sizes, 64);
	int i = c8ui_combo_get(w);
	if (h == NULL || i < 0 || i >= n) {
		return;
	}
	h->edit.width = sizes[2 * i];
	h->edit.height = sizes[2 * i + 1];
	h->edit.refresh = best_rate(h, h->edit.width, h->edit.height);
	set_dirty();
	update_ui();
}

static void rate_changed(struct c8ui_widget *w, void *data) {
	struct head *h = disp.selected;
	int rates[64];
	int n = head_rates(h, h->edit.width, h->edit.height, rates, 64);
	int i = c8ui_combo_get(w);
	if (i >= 0 && i < n) {
		h->edit.refresh = rates[i];
		set_dirty();
	}
}

static const double scales[] = { 1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 3 };
#define SCALE_COUNT (int)(sizeof(scales) / sizeof(scales[0]))

static void scale_changed(struct c8ui_widget *w, void *data) {
	struct head *h = disp.selected;
	int i = c8ui_combo_get(w);
	if (i >= 0 && i < SCALE_COUNT) {
		h->edit.scale = scales[i];
		set_dirty();
	}
}

static const char *orientations[] = {
	"Landscape", "Portrait", "Landscape (flipped)", "Portrait (flipped)",
};

static void orientation_changed(struct c8ui_widget *w, void *data) {
	struct head *h = disp.selected;
	int i = c8ui_combo_get(w);
	if (i >= 0 && i < 4) {
		h->edit.transform = i;
		set_dirty();
	}
}

static void build_controls(void) {
	c8ui_widget_clear(disp.controls);
	disp.apply = NULL;
	struct head *h = disp.selected;
	if (h == NULL) {
		return;
	}
	char title[512];
	const char *what = h->description && h->description[0] ? h->description :
		h->model && h->model[0] ? h->model : h->name;
	snprintf(title, sizeof(title), "%d. %s", head_index(h) + 1, what);
	struct c8ui_widget *label = c8ui_label_new(title, C8UI_TEXT_TITLE);
	add(disp.controls, label);

	int enabled_count = 0;
	struct head *o;
	wl_list_for_each(o, &disp.heads, link) {
		enabled_count += o->edit.enabled;
	}
	struct c8ui_widget *toggle = c8ui_toggle_new("Use this display", NULL,
		h->edit.enabled, enabled_changed, NULL);
	c8ui_widget_set_disabled(toggle, h->edit.enabled && enabled_count <= 1);
	add(disp.controls, toggle);

	if (h->edit.enabled) {
		/* Resolution */
		int sizes[128];
		int n = head_sizes(h, sizes, 64), selected = -1;
		char **labels = calloc(n + 2, sizeof(char *));
		for (int i = 0; i < n; i++) {
			if (sizes[2 * i] == h->edit.width && sizes[2 * i + 1] == h->edit.height) {
				selected = i;
			}
			labels[i] = g_strdup_printf("%d × %d%s", sizes[2 * i],
				sizes[2 * i + 1], size_preferred(h, sizes[2 * i],
				sizes[2 * i + 1]) ? " (recommended)" : "");
		}
		if (n == 0) {
			/* A window on another desktop has no list of modes */
			labels[n++] = g_strdup_printf("%d × %d", h->edit.width,
				h->edit.height);
			selected = 0;
		}
		struct c8ui_widget *combo = c8ui_combo_new("Resolution",
			(const char *const *)labels, n, selected, size_changed, NULL);
		c8ui_widget_set_disabled(combo, wl_list_empty(&h->modes));
		add(disp.controls, combo);
		g_strfreev(labels);

		/* Refresh rate */
		int rates[64];
		n = head_rates(h, h->edit.width, h->edit.height, rates, 64);
		selected = -1;
		labels = calloc(n + 2, sizeof(char *));
		for (int i = 0; i < n; i++) {
			if (abs(rates[i] - h->edit.refresh) < 10) {
				selected = i;
			}
			labels[i] = g_strdup_printf("%.2f Hz", rates[i] / 1000.0);
		}
		if (n > 0) {
			struct c8ui_widget *rate = c8ui_combo_new("Refresh rate",
				(const char *const *)labels, n, selected, rate_changed, NULL);
			add(disp.controls, rate);
		}
		g_strfreev(labels);

		/* Scale */
		const char *scale_labels[SCALE_COUNT + 1];
		char custom[32];
		selected = -1;
		int count = SCALE_COUNT;
		static char names[SCALE_COUNT][16];
		for (int i = 0; i < SCALE_COUNT; i++) {
			snprintf(names[i], sizeof(names[i]), "%.0f%%", scales[i] * 100);
			scale_labels[i] = names[i];
			if (fabs(scales[i] - h->edit.scale) < 0.001) {
				selected = i;
			}
		}
		if (selected < 0) {
			snprintf(custom, sizeof(custom), "%.0f%%", h->edit.scale * 100);
			scale_labels[count] = custom;
			selected = count++;
		}
		add(disp.controls, c8ui_combo_new("Make everything bigger",
			scale_labels, count, selected, scale_changed, NULL));

		/* Orientation */
		int t = h->edit.transform;
		const char *o_labels[5];
		for (int i = 0; i < 4; i++) {
			o_labels[i] = orientations[i];
		}
		count = 4;
		if (t >= 4) {
			o_labels[count++] = "Mirrored";
		}
		add(disp.controls, c8ui_combo_new("Orientation", o_labels, count,
			t < 4 ? t : 4, orientation_changed, NULL));
	}

	struct c8ui_widget *buttons = c8ui_box_new(C8UI_HORIZONTAL, 10);
	add(disp.controls, c8ui_spacer_new(1, 8));
	disp.apply = c8ui_button_new("Apply", apply_clicked, NULL);
	c8ui_button_set_primary(disp.apply, true);
	c8ui_widget_set_disabled(disp.apply, !disp.dirty);
	add(buttons, disp.apply);
	add(buttons, c8ui_button_new("Cancel", cancel_clicked, NULL));
	add(disp.controls, buttons);
}

/* XR glasses: XREAL's EDID says MRG, its name XREAL … */
static bool head_is_glasses(struct head *h) {
	return (h->make && (strcmp(h->make, "MRG") == 0 ||
			strstr(h->make, "XREAL"))) ||
		(h->model && strstr(h->model, "XREAL"));
}

/* What the screens show with another plugged in: the same choice as the
 * shell's Second screen flyout (Super+P), saved as [display] project */
static void build_project(void) {
	int heads = 0, glasses = 0;
	struct head *h;
	wl_list_for_each(h, &disp.heads, link) {
		heads++;
		glasses += head_is_glasses(h);
	}
	int shown = glasses ? 2 : heads > 1 ? 1 : 0;
	if (shown == disp.project_shown) {
		return;
	}
	disp.project_shown = shown;
	c8ui_widget_clear(disp.project);
	if (shown == 0) {
		return;
	}
	static const char *const values[] = { "auto", "pc", "duplicate",
		"second", "xr" };
	static const char *const labels[] = { "Automatic", "PC screen only",
		"Duplicate", "Second screen only", "XR" };
	add(disp.project, bound_choice("display", "project", "Second screen",
		values, labels, shown == 2 ? 5 : 4, 0));
	add(disp.project, caption(shown == 2 ?
		"Automatic puts everything in your glasses, in XR: apps "
		"stay where you put them in the space around you. Super+P changes "
		"it from anywhere." :
		"Automatic shows things on every screen, side by side. Super+P "
		"changes it from anywhere."));
}

static void update_ui(void) {
	if (disp.controls == NULL) {
		return;
	}
	build_project();
	if (disp.selected == NULL && !wl_list_empty(&disp.heads)) {
		disp.selected = wl_container_of(disp.heads.next, disp.selected, link);
	}
	build_controls();
	c8ui_widget_queue_draw(disp.canvas);
}

static void displays_gone(struct c8ui_widget *w, void *data) {
	disp.canvas = disp.controls = disp.apply = disp.project = NULL;
	disp.project_shown = 0;
	disp.drag = NULL;
}

static void displays_build(struct c8ui_widget *box) {
	if (disp.manager == NULL) {
		add(box, caption("The compositor doesn't let apps change displays."));
		night_build(box);
		return;
	}
	disp.project = c8ui_box_new(C8UI_VERTICAL, 8);
	disp.project->fill = true;
	disp.project_shown = 0;
	add(box, disp.project);
	add(box, caption("Drag the displays to arrange them the way they stand "
		"on your desk."));
	disp.canvas = c8ui_canvas_new(0, CANVAS_HEIGHT, canvas_draw, canvas_event,
		NULL);
	disp.canvas->fill = true;
	c8ui_widget_set_background(disp.canvas, 0xf2f2f2);
	add(box, disp.canvas);
	disp.controls = c8ui_box_new(C8UI_VERTICAL, 18);
	disp.controls->fill = true;
	add(box, disp.controls);
	box->on_destroy = displays_gone;
	update_ui();
	night_build(box);
}

const struct page page_displays = {
	.name = "displays",
	.title = "Displays",
	.build = displays_build,
	.refresh = night_refresh,
};

/* Protocol */

static void mode_size(void *data, struct zwlr_output_mode_v1 *wlr,
		int32_t width, int32_t height) {
	struct mode *m = data;
	m->width = width;
	m->height = height;
}

static void mode_refresh(void *data, struct zwlr_output_mode_v1 *wlr,
		int32_t refresh) {
	struct mode *m = data;
	m->refresh = refresh;
}

static void mode_preferred(void *data, struct zwlr_output_mode_v1 *wlr) {
	struct mode *m = data;
	m->preferred = true;
}

static void mode_finished(void *data, struct zwlr_output_mode_v1 *wlr) {
	struct mode *m = data;
	if (m->head && m->head->current == m) {
		m->head->current = NULL;
	}
	wl_list_remove(&m->link);
	if (zwlr_output_mode_v1_get_version(wlr) >= 3) {
		zwlr_output_mode_v1_release(wlr);
	} else {
		zwlr_output_mode_v1_destroy(wlr);
	}
	free(m);
}

static const struct zwlr_output_mode_v1_listener mode_listener = {
	.size = mode_size,
	.refresh = mode_refresh,
	.preferred = mode_preferred,
	.finished = mode_finished,
};

static void head_name(void *data, struct zwlr_output_head_v1 *wlr,
		const char *name) {
	struct head *h = data;
	free(h->name);
	h->name = strdup(name);
}

static void head_description(void *data, struct zwlr_output_head_v1 *wlr,
		const char *description) {
	struct head *h = data;
	free(h->description);
	h->description = strdup(description);
}

static void head_physical_size(void *data, struct zwlr_output_head_v1 *wlr,
		int32_t width, int32_t height) {
}

static void head_mode(void *data, struct zwlr_output_head_v1 *wlr,
		struct zwlr_output_mode_v1 *mode_wlr) {
	struct head *h = data;
	struct mode *m = calloc(1, sizeof(*m));
	m->wlr = mode_wlr;
	m->head = h;
	wl_list_insert(h->modes.prev, &m->link);
	zwlr_output_mode_v1_add_listener(mode_wlr, &mode_listener, m);
}

static void head_enabled(void *data, struct zwlr_output_head_v1 *wlr,
		int32_t enabled) {
	struct head *h = data;
	h->now.enabled = enabled;
}

static void head_current_mode(void *data, struct zwlr_output_head_v1 *wlr,
		struct zwlr_output_mode_v1 *mode_wlr) {
	struct head *h = data;
	struct mode *m;
	wl_list_for_each(m, &h->modes, link) {
		if (m->wlr == mode_wlr) {
			h->current = m;
		}
	}
}

static void head_position(void *data, struct zwlr_output_head_v1 *wlr,
		int32_t x, int32_t y) {
	struct head *h = data;
	h->now.x = x;
	h->now.y = y;
}

static void head_transform(void *data, struct zwlr_output_head_v1 *wlr,
		int32_t transform) {
	struct head *h = data;
	h->now.transform = transform;
}

static void head_scale(void *data, struct zwlr_output_head_v1 *wlr,
		wl_fixed_t scale) {
	struct head *h = data;
	h->now.scale = wl_fixed_to_double(scale);
}

static void head_finished(void *data, struct zwlr_output_head_v1 *wlr) {
	struct head *h = data;
	if (disp.selected == h) {
		disp.selected = NULL;
	}
	if (disp.drag == h) {
		disp.drag = NULL;
	}
	struct mode *m, *tmp;
	wl_list_for_each_safe(m, tmp, &h->modes, link) {
		m->head = NULL;
	}
	wl_list_remove(&h->link);
	if (zwlr_output_head_v1_get_version(wlr) >= 3) {
		zwlr_output_head_v1_release(wlr);
	} else {
		zwlr_output_head_v1_destroy(wlr);
	}
	free(h->name);
	free(h->description);
	free(h->make);
	free(h->model);
	free(h);
}

static void head_make(void *data, struct zwlr_output_head_v1 *wlr,
		const char *make) {
	struct head *h = data;
	free(h->make);
	h->make = strdup(make);
}

static void head_model(void *data, struct zwlr_output_head_v1 *wlr,
		const char *model) {
	struct head *h = data;
	free(h->model);
	h->model = strdup(model);
}

static void head_serial(void *data, struct zwlr_output_head_v1 *wlr,
		const char *serial) {
}

static void head_adaptive_sync(void *data, struct zwlr_output_head_v1 *wlr,
		uint32_t state) {
}

static const struct zwlr_output_head_v1_listener head_listener = {
	.name = head_name,
	.description = head_description,
	.physical_size = head_physical_size,
	.mode = head_mode,
	.enabled = head_enabled,
	.current_mode = head_current_mode,
	.position = head_position,
	.transform = head_transform,
	.scale = head_scale,
	.finished = head_finished,
	.make = head_make,
	.model = head_model,
	.serial_number = head_serial,
	.adaptive_sync = head_adaptive_sync,
};

static void manager_head(void *data, struct zwlr_output_manager_v1 *manager,
		struct zwlr_output_head_v1 *wlr) {
	struct head *h = calloc(1, sizeof(*h));
	h->wlr = wlr;
	h->now.scale = 1;
	wl_list_init(&h->modes);
	wl_list_insert(disp.heads.prev, &h->link);
	zwlr_output_head_v1_add_listener(wlr, &head_listener, h);
}

static void manager_done(void *data, struct zwlr_output_manager_v1 *manager,
		uint32_t serial) {
	disp.serial = serial;
	struct head *h;
	wl_list_for_each(h, &disp.heads, link) {
		if (h->current) {
			h->now.width = h->current->width;
			h->now.height = h->current->height;
			h->now.refresh = h->current->refresh;
		}
		if (!disp.dirty) {
			h->edit = h->now;
		}
	}
	if (!disp.dirty && disp.drag == NULL) {
		update_ui();
	}
}

static void manager_finished(void *data, struct zwlr_output_manager_v1 *manager) {
	zwlr_output_manager_v1_destroy(manager);
	disp.manager = NULL;
}

static const struct zwlr_output_manager_v1_listener manager_listener = {
	.head = manager_head,
	.done = manager_done,
	.finished = manager_finished,
};

void displays_init(void) {
	wl_list_init(&disp.heads);
	disp.manager = c8ui_app_bind(app.ui, &zwlr_output_manager_v1_interface, 4);
	if (disp.manager) {
		zwlr_output_manager_v1_add_listener(disp.manager, &manager_listener, NULL);
	}
}
