#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <drm_fourcc.h>
#include <xf86drmMode.h>
#include <wlr/backend/drm.h>
#include <wlr/backend/wayland.h>
#include <wlr/config.h>
#include <wlr/types/wlr_output.h>
#include <wlr/types/wlr_output_management_v1.h>
#include <wlr/util/log.h>
#if WLR_HAS_X11_BACKEND
#include <wlr/backend/x11.h>
#endif
#include "server.h"

/* A window on another desktop, rather than a real display */
static bool output_is_nested(struct wlr_output *output) {
#if WLR_HAS_X11_BACKEND
	if (wlr_output_is_x11(output)) {
		return true;
	}
#endif
	return wlr_output_is_wl(output);
}

/* The laptop's own panel. C8_BUILTIN names one for testing headless. */
static bool output_is_builtin(struct wlr_output *output) {
	const char *force = getenv("C8_BUILTIN");
	if (force && *force) {
		return strcmp(force, output->name) == 0;
	}
	const char *name = output->name;
	return strncmp(name, "eDP", 3) == 0 || strncmp(name, "LVDS", 4) == 0 ||
		strncmp(name, "DSI", 3) == 0;
}

/* XR glasses. XREAL's EDID has the PNP id MRG and the product name
 * "XREAL 1 Pro+" (and so on), shown as make and model. C8_GLASSES names an
 * output to treat as glasses, for testing headless. */
static bool output_is_glasses(struct wlr_output *output) {
	const char *force = getenv("C8_GLASSES");
	if (force && *force) {
		return strcmp(force, output->name) == 0;
	}
	return (output->make && (strcmp(output->make, "MRG") == 0 ||
			strstr(output->make, "XREAL"))) ||
		(output->model && strstr(output->model, "XREAL"));
}

/* Second screens */

static const char *const project_names[C8_PROJECT_COUNT] = {
	[C8_PROJECT_AUTO] = "auto",
	[C8_PROJECT_PC] = "pc",
	[C8_PROJECT_DUPLICATE] = "duplicate",
	[C8_PROJECT_SECOND] = "second",
	[C8_PROJECT_XR] = "xr",
};

const char *c8_project_name(enum c8_project project) {
	return project >= 0 && project < C8_PROJECT_COUNT ?
		project_names[project] : "none";
}

bool c8_project_parse(const char *name, enum c8_project *out) {
	for (int i = 0; i < C8_PROJECT_COUNT; i++) {
		if (strcmp(name, project_names[i]) == 0) {
			*out = i;
			return true;
		}
	}
	if (strcmp(name, "mixed-reality") == 0) {
		*out = C8_PROJECT_XR; // its old name, in older config.ini files
		return true;
	}
	return false;
}

/* Which of the choices make sense with the displays plugged in */
static bool project_possible(struct c8_server *server, enum c8_project p) {
	int builtin = 0, external = 0, glasses = 0;
	struct c8_output *output;
	wl_list_for_each(output, &server->outputs, link) {
		if (output_is_nested(output->wlr_output) ||
				c8_output_is_virtual(output)) {
			continue;
		}
		if (output->builtin) {
			builtin++;
		} else {
			external++;
		}
		glasses += output->glasses;
	}
	/* Their output is Monado's meanwhile, but they're still plugged in:
	 * PC screen only must stay possible, or choosing it kept XR on */
	glasses += server->xr.leased;
	external += server->xr.leased;
	switch (p) {
	case C8_PROJECT_AUTO:
		return true;
	case C8_PROJECT_PC:
		return builtin && external;
	case C8_PROJECT_DUPLICATE:
		return builtin + external > 1;
	case C8_PROJECT_SECOND:
		return external && (builtin || glasses);
	case C8_PROJECT_XR:
		return glasses;
	case C8_PROJECT_COUNT:
		break;
	}
	return false;
}

int c8_project_now(struct c8_server *server) {
	enum c8_project p = server->config.project;
	if (p == C8_PROJECT_AUTO || !project_possible(server, p)) {
		p = project_possible(server, C8_PROJECT_XR) ?
			C8_PROJECT_XR : C8_PROJECT_AUTO;
	}
	if (p == C8_PROJECT_AUTO) {
		/* Side by side as they always were, or one screen */
		return C8_PROJECT_NONE;
	}
	return p;
}

void c8_project_choices(struct c8_server *server, char *buf, size_t len) {
	size_t used = 0;
	buf[0] = '\0';
	for (int p = C8_PROJECT_PC; p < C8_PROJECT_COUNT; p++) {
		if (project_possible(server, p) && used < len) {
			used += snprintf(buf + used, len - used, "%s%s",
				used ? "," : "", project_names[p]);
		}
	}
	/* Only one way to show things is no choice */
	if (strchr(buf, ',') == NULL) {
		buf[0] = '\0';
	}
}

/* Whether the Second screen choice turns this display off */
static bool project_hides(struct c8_server *server, struct c8_output *output) {
	if (output_is_nested(output->wlr_output) ||
			c8_output_is_virtual(output)) {
		return false;
	}
	switch (c8_project_now(server)) {
	case C8_PROJECT_PC:
		return !output->builtin;
	case C8_PROJECT_SECOND:
		return output->builtin;
	case C8_PROJECT_XR:
		return !output->glasses; // everything is in the glasses
	default:
		return false;
	}
}

/* The shell's Second screen flyout shows what's possible now */
static void project_tell_shell(struct c8_server *server) {
	char state[sizeof(server->project_sent)];
	char choices[96];
	c8_project_choices(server, choices, sizeof(choices));
	snprintf(state, sizeof(state), "%s|%s|%d",
		c8_project_name(c8_project_now(server)), choices,
		c8_xr_active(server));
	if (strcmp(state, server->project_sent) != 0) {
		snprintf(server->project_sent, sizeof(server->project_sent), "%s",
			state);
		c8_shell_appearance_changed(server);
	}
}


/* The first display that is on: Start and the shell live there */
struct wlr_output *c8_primary_output(struct c8_server *server) {
	struct c8_output *output;
	wl_list_for_each(output, &server->outputs, link) {
		if (output->wlr_output->enabled && output->scene_output) {
			return output->wlr_output; // the virtual one is first
		}
	}
	if (wl_list_empty(&server->outputs)) {
		return NULL;
	}
	output = wl_container_of(server->outputs.next, output, link);
	return output->wlr_output;
}

void c8_output_box(struct c8_server *server, struct wlr_box *box) {
	struct wlr_output *output = c8_primary_output(server);
	*box = (struct wlr_box){ 0 };
	if (output) {
		wlr_output_layout_get_box(server->output_layout, output, box);
	}
}

/* Asks for a frame of the primary output: what's waiting on one (the lock
 * cover, screens coming back on) gets drawn. */
void c8_schedule_tick(struct c8_server *server) {
	struct wlr_output *primary = c8_primary_output(server);
	if (primary && primary->enabled) {
		wlr_output_schedule_frame(primary);
	}
}

static void output_frame(struct wl_listener *listener, void *data) {
	struct c8_output *output = wl_container_of(listener, output, frame);
	struct c8_server *server = output->server;
	if (c8_output_is_sink(output)) {
		c8_xr_sink_frame(output);
		return;
	}
	if (output->scene_output == NULL) {
		return;
	}
	if (server->xr.source == output) {
		c8_xr_source_frame(output);
	} else {
		wlr_scene_output_commit(output->scene_output, NULL);
	}
	if (server->lock.active) {
		c8_lock_output_frame(server, output);
	}
	struct timespec now;
	clock_gettime(CLOCK_MONOTONIC, &now);
	wlr_scene_output_send_frame_done(output->scene_output, &now);
}

static void output_present(struct wl_listener *listener, void *data) {
	struct c8_output *output = wl_container_of(listener, output, present);
	const struct wlr_output_event_present *event = data;
	if (event->presented) {
		output->presented_ns = event->when.tv_sec * 1000000000LL +
			event->when.tv_nsec;
		output->refresh_ns = event->refresh;
	}
}

static void output_request_state(struct wl_listener *listener, void *data) {
	struct c8_output *output = wl_container_of(listener, output, request_state);
	const struct wlr_output_event_request_state *event = data;
	wlr_output_commit_state(output->wlr_output, event->state);
	c8_layers_arrange(output->server);
}

static void update_output_manager(struct c8_server *server);

static void output_destroy(struct wl_listener *listener, void *data) {
	struct c8_output *output = wl_container_of(listener, output, destroy);
	struct c8_server *server = output->server;
	bool nested = output_is_nested(output->wlr_output);
	bool is_virtual = c8_output_is_virtual(output);
	c8_xr_output_gone(output);
	if (output->role == C8_OUTPUT_VIEW) {
		wl_list_remove(&output->needs_frame.link);
	}
	wl_list_remove(&output->frame.link);
	wl_list_remove(&output->present.link);
	wl_list_remove(&output->request_state.link);
	wl_list_remove(&output->destroy.link);
	wl_list_remove(&output->link);
	free(output);
	if (server->terminating) {
		return;
	}
	if (is_virtual) {
		/* XR ended: whoever ended it arranges the rest */
		if (!server->xr.updating) {
			c8_output_apply_config(server);
		}
		return;
	}
	/* Closing the window of a nested session ends it, like Exit does;
	 * a real display going away (unplugged) leaves the session running */
	if (nested && wl_list_empty(&server->outputs)) {
		wlr_log(WLR_INFO, "Nested window closed, exiting");
		c8_run_action(server, C8_ACTION_QUIT, NULL);
		return;
	}
	/* Unplugged: what it turned off comes back */
	c8_output_apply_config(server);
	c8_layers_arrange(server);
	update_output_manager(server);
}

static struct c8_output *find_output(struct c8_server *server,
		struct wlr_output *wlr_output) {
	struct c8_output *output;
	wl_list_for_each(output, &server->outputs, link) {
		if (output->wlr_output == wlr_output) {
			return output;
		}
	}
	return NULL;
}

static struct wlr_output_mode *find_mode(struct wlr_output *output, int width,
		int height, int refresh) {
	struct wlr_output_mode *mode, *best = NULL;
	wl_list_for_each(mode, &output->modes, link) {
		if (mode->width != width || mode->height != height) {
			continue;
		}
		if (refresh == 0) {
			/* Any rate: the fastest, or the preferred one at that size */
			if (best == NULL || mode->preferred ||
					(!best->preferred && mode->refresh > best->refresh)) {
				best = mode;
			}
		} else if (best == NULL ||
				abs(mode->refresh - refresh) < abs(best->refresh - refresh)) {
			best = mode;
		}
	}
	if (best && refresh && abs(best->refresh - refresh) > 500) {
		return NULL;
	}
	return best;
}

/* Its own [output NAME], else for glasses [output glasses]: their
 * connector's name is whichever port they're in (the 1 Pro+ came as
 * DP-2 one day and ran at 120 Hz, its 90 set under DP-1, 2026-12-02) */
static struct c8_output_config *output_config(struct c8_output *output) {
	struct c8_config *config = &output->server->config;
	struct c8_output_config *oc =
		c8_output_config_find(config, output->wlr_output->name);
	if (oc == NULL && output->glasses) {
		oc = c8_output_config_find(config, "glasses");
	}
	return oc;
}

static bool mode_matches(struct wlr_output *output,
		const struct c8_output_config *oc) {
	if (output->width != oc->width || output->height != oc->height) {
		return false;
	}
	return oc->refresh == 0 || abs(output->refresh - oc->refresh) <= 500;
}

/* The changes the output's [output] section asks for; all of it when
 * initial, else only what differs from now */
static void config_state(struct c8_output *output,
		struct wlr_output_state *state, bool initial) {
	struct c8_server *server = output->server;
	struct wlr_output *wlr_output = output->wlr_output;
	struct c8_output_config *oc = output_config(output);
	bool enable = (oc == NULL || oc->enabled != 0) &&
		!project_hides(server, output);
	if (output->idle_off && !initial) {
		/* Off for idleness: it comes back with the others, unless it's
		 * not to be on at all now */
		if (!enable) {
			output->idle_off = false;
		}
		return;
	}
	if (initial || enable != wlr_output->enabled) {
		wlr_output_state_set_enabled(state, enable);
	}
	if (!enable) {
		return;
	}
	if (oc && oc->has_mode && (initial || !mode_matches(wlr_output, oc))) {
		struct wlr_output_mode *mode =
			find_mode(wlr_output, oc->width, oc->height, oc->refresh);
		if (mode) {
			wlr_output_state_set_mode(state, mode);
		} else if (wl_list_empty(&wlr_output->modes)) {
			/* Nested in a window: any size goes */
			wlr_output_state_set_custom_mode(state, oc->width, oc->height,
				oc->refresh);
		}
	} else if (initial || (!wlr_output->enabled && !oc)) {
		struct wlr_output_mode *mode = wlr_output_preferred_mode(wlr_output);
		if (mode && output->glasses) {
			/* Glasses prefer 90 Hz, but the faster the steadier
			 * things stay in space as the head turns */
			mode = find_mode(wlr_output, mode->width, mode->height, 0);
			struct wlr_output_mode *m;
			wl_list_for_each(m, &wlr_output->modes, link) {
				if (m->width == mode->width && m->height == mode->height &&
						m->refresh > mode->refresh) {
					mode = m;
				}
			}
		}
		if (mode) {
			wlr_output_state_set_mode(state, mode);
		}
	}
	if (oc && oc->scale > 0 && (initial || oc->scale != wlr_output->scale)) {
		wlr_output_state_set_scale(state, oc->scale);
	}
	if (oc && oc->transform >= 0 &&
			(initial || (int)wlr_output->transform != oc->transform)) {
		wlr_output_state_set_transform(state, oc->transform);
	}
}

/* Put the output in the layout, at x, y or wherever there's room */
static void layout_place(struct c8_output *output, bool has_pos, int x, int y) {
	struct c8_server *server = output->server;
	struct wlr_output *wlr_output = output->wlr_output;
	struct wlr_output_layout_output *l_output;
	if (has_pos) {
		l_output = wlr_output_layout_add(server->output_layout, wlr_output, x, y);
	} else {
		l_output = wlr_output_layout_get(server->output_layout, wlr_output);
		if (l_output == NULL) {
			l_output = wlr_output_layout_add_auto(server->output_layout,
				wlr_output);
		}
	}
	if (l_output) {
		/* In the layout: a wl_output every client sees (not the one
		 * the glasses had only for capturing) */
		if (output->capture_global) {
			wlr_output_destroy_global(wlr_output);
			output->capture_global = false;
		}
		wlr_output_create_global(wlr_output, server->display);
	}
	if (l_output && output->scene_output == NULL) {
		output->scene_output = wlr_scene_get_scene_output(server->scene,
			wlr_output);
		if (output->scene_output == NULL) {
			output->scene_output =
				wlr_scene_output_create(server->scene, wlr_output);
		}
		wlr_scene_output_layout_add_output(server->scene_layout, l_output,
			output->scene_output);
	}
}

/* Its scene output goes with it. Leaving the layout doesn't destroy
 * that by itself: kept, a display turned off and on again got frames
 * with no scene output of ours and froze. */
static void layout_remove(struct c8_output *output) {
	struct c8_server *server = output->server;
	if (wlr_output_layout_get(server->output_layout, output->wlr_output)) {
		wlr_output_layout_remove(server->output_layout, output->wlr_output);
	}
	/* Out of it, clients are told it's gone. Hiding the global behind
	 * the filter instead killed a client that bound it in between, as
	 * every app does with a screen just announced (the glasses, as
	 * they went in the layout and out again entering XR) */
	if (output->wlr_output->global && !output->capture_global) {
		wlr_output_destroy_global(output->wlr_output);
	}
	struct wlr_scene_output *scene_output =
		wlr_scene_get_scene_output(server->scene, output->wlr_output);
	if (scene_output) {
		wlr_scene_output_destroy(scene_output);
	}
	output->scene_output = NULL;
}

static void layout_from_config(struct c8_output *output) {
	struct c8_output_config *oc = output_config(output);
	if (!output->wlr_output->enabled || c8_output_is_sink(output)) {
		/* Off, or showing another's picture: no part of the layout */
		layout_remove(output);
	} else if (!c8_output_is_virtual(output) && oc && oc->has_pos) {
		/* (the virtual one goes where the layout puts it, whatever
		 * a section of its name says) */
		layout_place(output, true, oc->x, oc->y);
	} else {
		layout_place(output, false, 0, 0);
	}
}

/* Never every display off: a second screen that won't come on, or a
 * choice that left none, gives the built-in panel back */
static bool any_enabled(struct c8_server *server) {
	struct c8_output *output;
	wl_list_for_each(output, &server->outputs, link) {
		if (output->wlr_output->enabled || output->idle_off) {
			return true;
		}
	}
	return wl_list_empty(&server->outputs);
}

/* On, at the mode the display likes best */
static void state_enable_preferred(struct wlr_output_state *state,
		struct wlr_output *wlr_output) {
	wlr_output_state_set_enabled(state, true);
	struct wlr_output_mode *mode = wlr_output_preferred_mode(wlr_output);
	if (mode) {
		wlr_output_state_set_mode(state, mode);
	}
}

static bool rescue_one(struct c8_output *output) {
	wlr_log(WLR_ERROR, "No display on: turning %s back on",
		output->wlr_output->name);
	struct wlr_output_state state;
	wlr_output_state_init(&state);
	state_enable_preferred(&state, output->wlr_output);
	bool ok = wlr_output_commit_state(output->wlr_output, &state);
	wlr_output_state_finish(&state);
	if (ok) {
		layout_place(output, false, 0, 0);
	}
	return ok;
}

/* The built-in panel, else whichever display will come on */
static void rescue(struct c8_server *server) {
	struct c8_output *output;
	wl_list_for_each(output, &server->outputs, link) {
		if (output->builtin && rescue_one(output)) {
			return;
		}
	}
	wl_list_for_each(output, &server->outputs, link) {
		if (!output->builtin && rescue_one(output)) {
			return;
		}
	}
}

void c8_output_apply_config(struct c8_server *server) {
	bool changed = false;
	struct c8_output *output;
	wl_list_for_each(output, &server->outputs, link) {
		if (c8_output_is_virtual(output)) {
			continue;
		}
		struct wlr_output *wlr_output = output->wlr_output;
		struct wlr_output_state state;
		wlr_output_state_init(&state);
		config_state(output, &state, false);
		if (state.committed != 0) {
			if (!wlr_output_commit_state(wlr_output, &state)) {
				wlr_log(WLR_ERROR, "Display %s: settings rejected",
					wlr_output->name);
			}
			changed = true;
		}
		wlr_output_state_finish(&state);
		if (!output->idle_off) {
			layout_from_config(output);
		}
	}
	if (!any_enabled(server)) {
		rescue(server);
		changed = true;
	}
	/* Mirrors and glasses: roles, the virtual output, then their place */
	struct c8_output *shell_before = server->xr.shell;
	c8_xr_update(server);
	changed |= shell_before != server->xr.shell;
	wl_list_for_each(output, &server->outputs, link) {
		if (!output->idle_off) {
			layout_from_config(output);
		}
	}
	if (changed) {
		c8_layers_arrange(server);
	}
	c8_nightlight_outputs(server); // one just turned on, say
	project_tell_shell(server);
}

/* Output management (wlr-randr, kanshi, PC settings) */

static void update_output_manager(struct c8_server *server) {
	if (server->output_manager == NULL) {
		return;
	}
	struct wlr_output_configuration_v1 *config =
		wlr_output_configuration_v1_create();
	struct c8_output *output;
	wl_list_for_each(output, &server->outputs, link) {
		if (c8_output_is_virtual(output)) {
			continue; // not a display anyone can set up
		}
		struct wlr_output_configuration_head_v1 *head =
			wlr_output_configuration_head_v1_create(config, output->wlr_output);
		struct wlr_box box;
		wlr_output_layout_get_box(server->output_layout, output->wlr_output, &box);
		head->state.enabled = (output->wlr_output->enabled || output->idle_off) &&
			!wlr_box_empty(&box);
		head->state.x = box.x;
		head->state.y = box.y;
	}
	wlr_output_manager_v1_set_configuration(server->output_manager, config);
}

static void layout_change(struct wl_listener *listener, void *data) {
	struct c8_server *server = wl_container_of(listener, server, layout_change);
	c8_touch_map(server);
	update_output_manager(server);
}

static void output_manager_config(struct c8_server *server,
		struct wlr_output_configuration_v1 *config, bool test) {
	bool ok = false;
	struct wlr_output_configuration_head_v1 *head;
	wl_list_for_each(head, &config->heads, link) {
		ok |= head->state.enabled; // never every display off
	}
	size_t len = 0;
	struct wlr_backend_output_state *states = NULL;
	if (ok) {
		states = wlr_output_configuration_v1_build_state(config, &len);
		ok = states != NULL;
	}
	if (ok) {
		ok = test ? wlr_backend_test(server->backend, states, len) :
			wlr_backend_commit(server->backend, states, len);
	}
	for (size_t i = 0; i < len; i++) {
		wlr_output_state_finish(&states[i].base);
	}
	free(states);

	if (ok && !test) {
		wl_list_for_each(head, &config->heads, link) {
			struct c8_output *output = find_output(server, head->state.output);
			if (output == NULL) {
				continue;
			}
			if (head->state.enabled) {
				layout_place(output, true, head->state.x, head->state.y);
			} else {
				layout_remove(output);
			}
		}
		c8_layers_arrange(server);
	}
	if (ok) {
		wlr_output_configuration_v1_send_succeeded(config);
	} else {
		wlr_output_configuration_v1_send_failed(config);
	}
	wlr_output_configuration_v1_destroy(config);
	update_output_manager(server);
}

static void output_manager_apply(struct wl_listener *listener, void *data) {
	struct c8_server *server =
		wl_container_of(listener, server, output_manager_apply);
	output_manager_config(server, data, false);
}

static void output_manager_test(struct wl_listener *listener, void *data) {
	struct c8_server *server =
		wl_container_of(listener, server, output_manager_test);
	output_manager_config(server, data, true);
}

/* The glasses take 1920x1080, a TV mode, for which the driver's
 * "Automatic" range is limited: black goes out as 16/255 grey and the
 * whole display glows where it should be clear. Their OLEDs want full. */
static void full_range(struct wlr_output *wlr_output) {
	if (!wlr_output_is_drm(wlr_output)) {
		return;
	}
	int fd = wlr_backend_get_drm_fd(wlr_output->backend);
	uint32_t id = wlr_drm_connector_get_id(wlr_output);
	drmModeObjectProperties *props = fd < 0 ? NULL :
		drmModeObjectGetProperties(fd, id, DRM_MODE_OBJECT_CONNECTOR);
	if (props == NULL) {
		return;
	}
	for (uint32_t i = 0; i < props->count_props; i++) {
		drmModePropertyRes *prop = drmModeGetProperty(fd, props->props[i]);
		if (prop == NULL) {
			continue;
		}
		bool ours = strcmp(prop->name, "Broadcast RGB") == 0;
		for (int e = 0; ours && e < prop->count_enums; e++) {
			if (strcmp(prop->enums[e].name, "Full") == 0 &&
					props->prop_values[i] != prop->enums[e].value) {
				if (drmModeConnectorSetProperty(fd, id, prop->prop_id,
						prop->enums[e].value) == 0) {
					wlr_log(WLR_INFO, "Display %s: full colour range",
						wlr_output->name);
				} else {
					wlr_log_errno(WLR_ERROR, "Display %s: colour range",
						wlr_output->name);
				}
			}
		}
		drmModeFreeProperty(prop);
	}
	drmModeFreeObjectProperties(props);
}

static void new_output(struct wl_listener *listener, void *data) {
	struct c8_server *server = wl_container_of(listener, server, new_output);
	struct wlr_output *wlr_output = data;

	if (wlr_output->non_desktop) {
		/* A VR headset: its runtime's, not a screen of ours */
		c8_lease_offer(server, wlr_output);
		return;
	}
	wlr_output_init_render(wlr_output, server->allocator, server->renderer);

	/* In the list first: whether it's on depends on what else is there */
	struct c8_output *output = calloc(1, sizeof(*output));
	output->wlr_output = wlr_output;
	output->server = server;
	c8_listen(&output->frame, &wlr_output->events.frame, output_frame);
	c8_listen(&output->present, &wlr_output->events.present, output_present);
	c8_listen(&output->request_state, &wlr_output->events.request_state,
		output_request_state);
	c8_listen(&output->destroy, &wlr_output->events.destroy, output_destroy);

	if (c8_xr_is_view(server, wlr_output)) {
		/* What Monado's headset shows, whichever it is, for the
		 * portal only: drawn when a capture asks for a frame, never
		 * in the layout */
		output->role = C8_OUTPUT_VIEW;
		server->xr.view = output;
		wl_list_insert(server->outputs.prev, &output->link);
		wlr_output_set_name(wlr_output, C8_XR_VIEW_NAME);
		wlr_output_set_description(wlr_output, server->xr.headset[0] ?
			server->xr.headset : "Headset");
		c8_listen(&output->needs_frame, &wlr_output->events.needs_frame,
			c8_xr_view_needs_frame);
		struct wlr_output_state state;
		wlr_output_state_init(&state);
		wlr_output_state_set_enabled(&state, true);
		if (!wlr_output_commit_state(wlr_output, &state)) {
			wlr_log(WLR_ERROR, "XR: the view for sharing didn't come on");
		}
		wlr_output_state_finish(&state);
		output->capture_global = true; // before: making it announces it
		wlr_output_create_global(wlr_output, server->display);
		return;
	}
	if (c8_xr_is_virtual(server, wlr_output)) {
		/* The shell's screen in XR: first, so the primary */
		output->role = C8_OUTPUT_VIRTUAL;
		server->xr.shell = output;
		wl_list_insert(&server->outputs, &output->link);
		wlr_output_set_name(wlr_output, C8_XR_NAME);
		wlr_output_set_description(wlr_output, "XR");
		/* The glasses show its frames, so the pointer has to be in them:
		 * never on a cursor plane, and no scanout of a buffer without it */
		wlr_output_lock_software_cursors(wlr_output, true);
		struct wlr_output_state state;
		wlr_output_state_init(&state);
		wlr_output_state_set_enabled(&state, true);
		/* With alpha: what's clear stays clear in the glasses */
		wlr_output_state_set_render_format(&state, DRM_FORMAT_ARGB8888);
		if (!wlr_output_commit_state(wlr_output, &state)) {
			wlr_log(WLR_ERROR, "XR: the virtual output didn't "
				"come on");
		}
		wlr_output_state_finish(&state);
		layout_from_config(output);
		wlr_log(WLR_INFO, "XR: the shell's screen is %dx%d",
			wlr_output->width, wlr_output->height);
		if (!server->xr.updating) {
			/* Announced late (starting up): now it can be the source */
			c8_output_apply_config(server);
			c8_layers_arrange(server);
		}
		return; // else c8_xr_update is making it and arranges the rest
	}
	output->builtin = output_is_builtin(wlr_output);
	output->glasses = output_is_glasses(wlr_output);
	wl_list_insert(server->outputs.prev, &output->link);
	wlr_log(WLR_INFO, "Display %s: %s %s%s%s", wlr_output->name,
		wlr_output->make ? wlr_output->make : "?",
		wlr_output->model ? wlr_output->model : "?",
		output->builtin ? ", built in" : "",
		output->glasses ? ", XR glasses" : "");

	struct wlr_output_state state;
	wlr_output_state_init(&state);
	config_state(output, &state, true);
	if (!wlr_output_commit_state(wlr_output, &state)) {
		/* A mode the display doesn't take: fall back to its own */
		wlr_log(WLR_ERROR, "Display %s: saved settings rejected",
			wlr_output->name);
		wlr_output_state_finish(&state);
		wlr_output_state_init(&state);
		state_enable_preferred(&state, wlr_output);
		wlr_output_commit_state(wlr_output, &state);
	}
	wlr_output_state_finish(&state);
	if (output->glasses) {
		full_range(wlr_output);
	}

	layout_from_config(output);
	/* A second screen can turn the others off (or glasses, on) */
	c8_output_apply_config(server);
	c8_layers_arrange(server);
	update_output_manager(server);
}

void c8_output_init(struct c8_server *server) {
	wl_list_init(&server->outputs);
	server->output_layout = wlr_output_layout_create(server->display);
	server->scene_layout =
		wlr_scene_attach_output_layout(server->scene, server->output_layout);
	c8_listen(&server->new_output, &server->backend->events.new_output,
		new_output);

	c8_listen(&server->layout_change, &server->output_layout->events.change,
		layout_change);
	server->output_manager = wlr_output_manager_v1_create(server->display);
	c8_listen(&server->output_manager_apply, &server->output_manager->events.apply,
		output_manager_apply);
	c8_listen(&server->output_manager_test, &server->output_manager->events.test,
		output_manager_test);
}

void c8_output_finish(struct c8_server *server) {
	wl_list_remove(&server->new_output.link);
	wl_list_remove(&server->layout_change.link);
	wl_list_remove(&server->output_manager_apply.link);
	wl_list_remove(&server->output_manager_test.link);
}
