/*
 * The Monado path of XR ([glasses] runtime, compositor/MONADO-XR.md):
 * Monado drives the glasses and c8 draws its space as an OpenXR overlay
 * (xrclient.c), so VR games run in the same space as the windows.
 *
 * In XR with the glasses plugged in, c8 starts monado-service (the one
 * build.sh --xr installs beside c8, with our driver for the glasses'
 * sensors) as a private Wayland client, offers it the glasses' display
 * for lease (lease.c; only it sees the lease global then) and connects
 * to it as an overlay. Granting the lease destroys the display's
 * wlr_output, so XR goes on without it while server->xr.leased. Our own
 * IMU connection is let go first: the driver opens its own, and the
 * glasses take only one (XR.md).
 *
 * monado-service exiting ends the lease and the display comes back; it
 * is started again after a pause, five times, and after that the
 * builtin path draws XR for the rest of the session.
 */
#define _GNU_SOURCE // pidfd via syscall
#include <dlfcn.h>
#include <errno.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <wlr/render/gles2.h>
#include <wlr/types/wlr_drm_lease_v1.h>
#include <wlr/util/log.h>
#include "server.h"

#define RESTARTS 5
#define RESTART_MS 3000
#define CONNECT_MS 250 // between tries to reach the runtime
#define KILL_MS 3000 // after asking it to stop, before SIGKILL
#define CONNECT_WAIT 15 // s: a connection it took but never answered
#define CONNECTS 20 // tries once it listens, before giving up on it

struct c8_xr_monado {
	struct c8_server *server;
	struct wl_client *client;
	struct wl_listener client_destroy;
	pid_t pid;
	struct wl_event_source *exited; // its pidfd
	int pidfd;
	int stop_fd; // its stdin: anything on it, or its end, stops it
	/* Its finished frames, when we ask (our Monado commit): our end
	 * of a SOCK_SEQPACKET pair, the other its C8_SHARE_FD */
	int share_fd;
	struct wl_event_source *share_source;
	struct wl_event_source *timer; // restarting, or reaching it
	int restarts;
	int connects; // failed tries since it began listening
	struct timespec started; // when we ran it: older sockets are stale
	struct wl_event_source *reaper; // SIGKILL, if stopping didn't do
	struct wl_event_source *draining; // frames done while it stops
	time_t connect_since; // the overlay's try in progress began
	bool failed; // gave up for this session: builtin draws
	bool waiting; // the timer is a restart's pause
	bool stopping; // we ended it: not a failure
	bool sbs_asked; // the glasses were asked for their 3D mode
	struct c8_xrclient *xr; // our overlay in it
	struct wlr_output *offered;
	/* What it was started for, offered or not (nested there's no
	 * lease): another output there means the lease has ended */
	struct wlr_output *target;
	char *service, *json; // where ours is
	bool looked;
};

static void runtime_kill(struct c8_xr_monado *rt);

/* What its renderer sends with each frame's memfd (our Monado fork) */
struct share_msg {
	uint32_t width, height, stride;
	uint64_t frame_id;
};

static void share_close(struct c8_xr_monado *rt) {
	if (rt->share_source) {
		wl_event_source_remove(rt->share_source);
		rt->share_source = NULL;
	}
	if (rt->share_fd >= 0) {
		close(rt->share_fd);
		rt->share_fd = -1;
	}
	rt->server->xr.view_streaming = false;
}

static int share_readable(int fd, uint32_t mask, void *data) {
	struct c8_xr_monado *rt = data;
	if (mask & (WL_EVENT_HANGUP | WL_EVENT_ERROR)) {
		share_close(rt);
		return 0;
	}
	struct share_msg msg;
	char control[CMSG_SPACE(sizeof(int))];
	struct iovec iov = { &msg, sizeof(msg) };
	struct msghdr mh = {
		.msg_iov = &iov, .msg_iovlen = 1,
		.msg_control = control, .msg_controllen = sizeof(control),
	};
	ssize_t n = recvmsg(fd, &mh, MSG_CMSG_CLOEXEC | MSG_DONTWAIT);
	if (n == 0) {
		share_close(rt); // it ended
		return 0;
	}
	int mem = -1;
	struct cmsghdr *cm = n > 0 ? CMSG_FIRSTHDR(&mh) : NULL;
	if (cm && cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_RIGHTS) {
		memcpy(&mem, CMSG_DATA(cm), sizeof(int));
	}
	if (n != (ssize_t)sizeof(msg) || mem < 0) {
		if (mem >= 0) {
			close(mem);
		}
		return 0;
	}
	size_t size = (size_t)msg.stride * msg.height;
	bool sane = msg.width > 0 && msg.height > 0 && msg.width <= 16384 &&
		msg.height <= 16384 && msg.stride >= msg.width * 4;
	void *pixels = sane ? mmap(NULL, size, PROT_READ, MAP_SHARED, mem, 0) :
		MAP_FAILED;
	close(mem);
	if (pixels != MAP_FAILED) {
		c8_xr_share_frame(rt->server, pixels, (int)msg.width,
			(int)msg.height, (int)msg.stride);
		munmap(pixels, size);
	}
	/* Done with it: the next may come */
	ssize_t w = send(fd, "R", 1, MSG_NOSIGNAL | MSG_DONTWAIT);
	(void)w;
	return 0;
}

bool c8_xr_runtime_share(struct c8_server *server, char cmd) {
	struct c8_xr_monado *rt = server->xr.runtime;
	if (rt == NULL || rt->share_fd < 0 || rt->xr == NULL ||
			!c8_xrclient_ready(rt->xr)) {
		return false; // not running, or not drawing yet
	}
	return send(rt->share_fd, &cmd, 1, MSG_NOSIGNAL | MSG_DONTWAIT) == 1;
}

static char *exists(const char *path) {
	return access(path, R_OK) == 0 ? strdup(path) : NULL;
}

/* Ours, beside c8: only it has the glasses' driver */
static bool runtime_found(struct c8_xr_monado *rt) {
	if (!rt->looked) {
		rt->looked = true;
		rt->service = exists(C8_BINDIR "/monado-service");
		rt->json = exists(C8_DATADIR "/openxr/1/openxr_monado.json");
		void *loader = dlopen("libopenxr_loader.so.1", RTLD_LAZY);
		if (loader == NULL || rt->service == NULL || rt->json == NULL) {
			wlr_log(WLR_INFO, "XR: no Monado of ours (%s%s%s%s%s), so c8 "
				"drives the glasses itself",
				rt->service ? "" : C8_BINDIR "/monado-service",
				rt->service || rt->json ? "" : ", ",
				rt->json ? "" : "its runtime file",
				loader || (rt->service && rt->json) ? "" : ", ",
				loader ? "" : "the OpenXR loader");
			free(rt->service);
			free(rt->json);
			rt->service = rt->json = NULL;
		}
		if (loader) {
			dlclose(loader);
		}
	}
	return rt->service != NULL;
}

static bool runtime_wanted(struct c8_xr_monado *rt) {
	struct c8_server *server = rt->server;
	if (rt->failed || server->config.glasses.runtime == C8_XR_RUNTIME_BUILTIN ||
			!wlr_renderer_is_gles2(server->renderer)) {
		return false;
	}
	return runtime_found(rt);
}

static void schedule(struct c8_xr_monado *rt, int ms, bool restart) {
	rt->waiting = restart;
	wl_event_source_timer_update(rt->timer, ms);
}

static void client_gone(struct wl_listener *listener, void *data) {
	struct c8_xr_monado *rt = wl_container_of(listener, rt, client_destroy);
	wl_list_remove(&rt->client_destroy.link);
	rt->client = NULL;
}

/* For the rest of the session: builtin draws the glasses */
static void give_up(struct c8_xr_monado *rt, const char *why) {
	rt->failed = true;
	wlr_log(WLR_ERROR, "XR: %s; c8 drives the glasses itself until the "
		"next session", why);
	c8_exec("notify-send -a cont8nuum -i input-gaming "
		"'VR games aren’t available' "
		"'Monado couldn’t drive the glasses, so XR goes on without "
		"it. More is in the session’s log.'");
}

static int reap(void *data) {
	struct c8_xr_monado *rt = data;
	if (rt->pid > 0 && rt->stopping) {
		wlr_log(WLR_ERROR, "XR: Monado didn't stop; killing it");
		kill(rt->pid, SIGKILL);
	}
	return 0;
}

/* Stopping, it presents its last frames and only then lets go: nested
 * into a window of ours, which nobody draws once XR is left, so its
 * present waited on a frame callback for good and so did its exit
 * (gdb: teardown_all joining the compositor, in vkQueuePresentKHR,
 * 2026-12-02). Every window is told its frame is done meanwhile. */
static int drain(void *data) {
	struct c8_xr_monado *rt = data;
	if (rt->pid > 0 && rt->stopping) {
		c8_xr_windows_done(rt->server);
		wl_event_source_timer_update(rt->draining, 16);
	}
	return 0;
}

static int exited(int fd, uint32_t mask, void *data) {
	struct c8_xr_monado *rt = data;
	int status = 0;
	waitpid(rt->pid, &status, WNOHANG);
	wlr_log(WLR_INFO, "XR: monado-service ended (%s %d)",
		WIFSIGNALED(status) ? "signal" : "status",
		WIFSIGNALED(status) ? WTERMSIG(status) : WEXITSTATUS(status));
	rt->pid = -1;
	share_close(rt);
	wl_event_source_remove(rt->exited);
	rt->exited = NULL;
	close(rt->pidfd);
	rt->pidfd = -1;
	if (rt->stop_fd >= 0) {
		close(rt->stop_fd);
		rt->stop_fd = -1;
	}
	runtime_kill(rt); // the overlay, the client and the offer
	if (rt->stopping) {
		rt->stopping = false;
	} else if (++rt->restarts > RESTARTS) {
		give_up(rt, "Monado keeps failing");
	} else {
		schedule(rt, RESTART_MS, true);
	}
	c8_xr_update(rt->server);
	return 0;
}

/* The mode Monado is to take: the one we set from the user's config
 * (`[output NAME] mode`). Left to itself Monado's direct mode takes
 * the most pixels at the highest refresh (comp_window_direct.c in
 * v25.1.0): 120 Hz on a 1 Pro+ set to 90, where the UHD 620 missed
 * nearly every frame by a refresh and the picture's edges opened on
 * every turn (2026-12-02). *index is its place in the output's list,
 * the kernel's order, which is Vulkan's too (XRT_COMPOSITOR_DESIRED_MODE);
 * -1 when it isn't listed */
static struct wlr_output_mode *runtime_mode(struct wlr_output *output,
		int *index) {
	struct wlr_output_mode *m, *best = NULL;
	int i = 0;
	*index = -1;
	wl_list_for_each(m, &output->modes, link) {
		if (m == output->current_mode) {
			*index = i;
			return m;
		}
		long px = (long)m->width * m->height;
		long best_px = best ? (long)best->width * best->height : 0;
		if (best == NULL || px > best_px ||
				(px == best_px && m->refresh > best->refresh)) {
			best = m;
		}
		i++;
	}
	return best; // not set by us (off): Monado's own choice
}

static bool runtime_spawn(struct c8_xr_monado *rt) {
	struct c8_server *server = rt->server;
	rt->connects = 0;
	char *argv[] = { rt->service, NULL };
	/* Straight to the glasses through the lease, when there's DRM to
	 * lease (not nested: a test sets Monado's target itself) */
	static char direct[] = "XRT_COMPOSITOR_FORCE_WAYLAND_DIRECT=1";
	static char connector[96];
	/* Its 140% render scale drew 2688x1512 an eye, twice, at 120 Hz:
	 * more than a laptop's GPU keeps up with. The user's own setting
	 * wins. */
	static char scale[] = "XRT_COMPOSITOR_SCALE_PERCENTAGE=100";
	/* Which of the glasses' modes the driver drives: 3D (two halves)
	 * or 2D (one picture for both eyes), and at what refresh */
	static char mode[64], desired[64];
	/* Its compute compositor (v25.1.0's default off Android) runs
	 * every layer's shader for every pixel of both eyes: with a layer
	 * a window on the glasses' iGPU it missed most frames by ~25 ms
	 * (2026-12-02). The graphics one draws each layer only where it
	 * is, the same picture (compared nested). The user's own setting
	 * wins. */
	static char graphics[] = "XRT_COMPOSITOR_COMPUTE=0";
	/* Its pacer wakes to compose a frame only 20% of a refresh (at
	 * least 3 ms) before it: on the glasses' iGPU the frame took
	 * longer, every one went out a refresh late and it ran at half the
	 * rate (90 Hz: 45 a second, each "missed by 11 ms"; 2026-12-02),
	 * the picture judder and the poses a refresh old, so windows
	 * wobbled on turns. Half a refresh wasn't enough: its GPU took
	 * 8.7 ms a frame (median, worst 10.7; U_PACING_LIVE_STATS). 85%
	 * of one, while that GPU time comes down. The user's own setting
	 * wins. */
	static char comp_time[64];
	/* TEMPORARY (2026-12-02): its frame timings in the log, to size
	 * the above on the glasses */
	static char stats[] = "U_PACING_LIVE_STATS=1";
	char *env[12];
	int n = 0;
	if (getenv("XRT_COMPOSITOR_SCALE_PERCENTAGE") == NULL) {
		env[n++] = scale;
	}
	if (getenv("XRT_COMPOSITOR_COMPUTE") == NULL) {
		env[n++] = graphics;
	}
	int index = -1;
	struct wlr_output_mode *m = rt->target ?
		runtime_mode(rt->target, &index) : NULL;
	if (m) {
		snprintf(mode, sizeof(mode), "C8_GLASSES_MODE=%dx%d@%d",
			m->width, m->height, m->refresh);
		env[n++] = mode;
	} else if (rt->target) {
		/* No modes (a headless output in a test): its size */
		snprintf(mode, sizeof(mode), "C8_GLASSES_MODE=%dx%d@%d",
			rt->target->width, rt->target->height,
			rt->target->refresh > 0 ? rt->target->refresh : 60000);
		env[n++] = mode;
	}
	int mhz = m ? m->refresh : 0;
	if (mhz > 0 && getenv("U_PACING_COMP_MIN_TIME_MS") == NULL) {
		snprintf(comp_time, sizeof(comp_time),
			"U_PACING_COMP_MIN_TIME_MS=%.1f", 850000.0 / mhz);
		env[n++] = comp_time;
	}
	if (getenv("U_PACING_LIVE_STATS") == NULL) {
		env[n++] = stats;
	}
	if (index >= 0 && getenv("XRT_COMPOSITOR_DESIRED_MODE") == NULL) {
		snprintf(desired, sizeof(desired),
			"XRT_COMPOSITOR_DESIRED_MODE=%d", index);
		env[n++] = desired;
	}
	if (server->lease.manager && rt->offered) {
		snprintf(connector, sizeof(connector),
			"XRT_COMPOSITOR_WAYLAND_CONNECTOR=%s", rt->offered->name);
		env[n++] = direct;
		env[n++] = connector;
	}
	env[n] = NULL;
	clock_gettime(CLOCK_REALTIME, &rt->started);
	share_close(rt);
	int share[2] = { -1, -1 };
	if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, share) != 0) {
		wlr_log_errno(WLR_ERROR, "XR: no socket for Monado's frames");
		share[0] = share[1] = -1;
	}
	/* Stopped through its stdin, Monado's own way (its main loop ends on
	 * anything there): it never stopped on SIGTERM, which something in
	 * it catches (2026-12-02: /proc showed SIGTERM caught and SIGINT
	 * ignored, as SDL's quit handler leaves them; on the glasses it sat
	 * on it, nested it crashed). Ending with us closes it too. */
	rt->client = c8_spawn_client_child(server, argv, env, &rt->pid,
		&rt->stop_fd, share[1], "C8_SHARE_FD");
	if (share[1] >= 0) {
		close(share[1]);
	}
	if (share[0] >= 0 && rt->client && rt->pid > 0) {
		rt->share_fd = share[0];
		rt->share_source = wl_event_loop_add_fd(server->loop, share[0],
			WL_EVENT_READABLE, share_readable, rt);
	} else if (share[0] >= 0) {
		close(share[0]);
	}
	if (rt->client == NULL || rt->pid < 0) {
		if (rt->client) {
			wl_client_destroy(rt->client);
			rt->client = NULL;
		}
		return false;
	}
	rt->client_destroy.notify = client_gone;
	wl_client_add_destroy_listener(rt->client, &rt->client_destroy);
	rt->pidfd = (int)syscall(SYS_pidfd_open, rt->pid, 0);
	if (rt->pidfd >= 0) {
		rt->exited = wl_event_loop_add_fd(server->loop, rt->pidfd,
			WL_EVENT_READABLE, exited, rt);
	}
	wlr_log(WLR_INFO, "XR: monado-service started (pid %d)", rt->pid);
	return true;
}

/* Monado listening: its socket (XRT_IPC_MSG_SOCK_FILENAME) is there.
 * Until then the loader would only print errors at every try. */
/* Its socket is there, and made by this one: a Monado that died
 * without cleaning up leaves its file behind */
static bool listening(struct c8_xr_monado *rt) {
	const char *run = getenv("XDG_RUNTIME_DIR");
	char sock[4096];
	struct stat st;
	snprintf(sock, sizeof(sock), "%s/monado_comp_ipc", run ? run : "/tmp");
	if (stat(sock, &st) != 0) {
		return false;
	}
	return st.st_ctim.tv_sec > rt->started.tv_sec ||
		(st.st_ctim.tv_sec == rt->started.tv_sec &&
		st.st_ctim.tv_nsec >= rt->started.tv_nsec);
}

/* Reaching it: our overlay connects once it is listening */
static int tick(void *data) {
	struct c8_xr_monado *rt = data;
	struct c8_server *server = rt->server;
	if (rt->waiting) {
		rt->waiting = false;
		c8_xr_update(server); // starts it again, if XR still wants it
		return 0;
	}
	if (rt->pid < 0 || rt->stopping) {
		return 0; // not there, or going: nothing to connect to
	}
	bool failed = false;
	if (rt->xr && c8_xrclient_lost(rt->xr)) {
		failed = !c8_xrclient_ready(rt->xr);
		c8_xrclient_destroy(rt->xr);
		rt->xr = NULL;
	}
	if (rt->xr && !c8_xrclient_ready(rt->xr) &&
			time(NULL) - rt->connect_since > CONNECT_WAIT) {
		give_up(rt, "Monado took the overlay's connection but never "
			"answered");
		runtime_kill(rt); // ends the wait, and the thread with it
		c8_xr_update(server);
		return 0;
	}
	if (rt->xr && c8_xrclient_ready(rt->xr)) {
		rt->restarts = 0; // it works
		rt->connects = 0;
	}
	if (rt->xr == NULL && listening(rt)) {
		rt->xr = c8_xrclient_create(server); // connects on a thread
		rt->connect_since = time(NULL);
		failed |= rt->xr == NULL;
	}
	if (failed && ++rt->connects >= CONNECTS) {
		/* It runs but won't take us (an extension missing, say): no
		 * point in retrying every quarter second */
		rt->connects = 0;
		give_up(rt, "the overlay can't start on Monado");
		runtime_kill(rt);
		c8_xr_update(server);
		return 0;
	}
	schedule(rt, rt->xr ? 1000 : CONNECT_MS, false);
	return 0;
}

static void runtime_kill(struct c8_xr_monado *rt) {
	struct c8_server *server = rt->server;
	if (rt->xr) {
		c8_xrclient_destroy(rt->xr);
		rt->xr = NULL;
	}
	c8_tracker_set_external(server->xr.tracker, NULL);
	if (rt->offered && server->lease.manager) {
		wlr_drm_lease_v1_manager_withdraw_output(server->lease.manager,
			rt->offered);
	}
	rt->offered = NULL;
	rt->target = NULL;
	if (rt->pid > 0 && rt->exited) {
		/* Its connection, and lease, end as it goes; the reaper
		 * makes sure it does. Not cut from here: its compositor lost
		 * its surface mid-frame and it crashed (SIGSEGV, nested,
		 * 2026-12-02) */
		if (rt->stop_fd >= 0) {
			ssize_t w = write(rt->stop_fd, "\n", 1);
			(void)w;
			close(rt->stop_fd);
			rt->stop_fd = -1;
		} else {
			kill(rt->pid, SIGTERM);
		}
		rt->stopping = true;
		wl_event_source_timer_update(rt->reaper, KILL_MS);
		wl_event_source_timer_update(rt->draining, 1);
	}
	if (rt->client && rt->pid <= 0) {
		wl_client_destroy(rt->client); // client_gone clears it
	}
}

/* xrizer (OpenVR on OpenXR) for SteamVR's games, where it was unpacked:
 * ~/.local/share/xrizer or our prefix's share/xrizer. OpenVR wants its
 * paths file to exist, so one naming xrizer is written if there's none
 * (SteamVR's, if it was ever run, is left alone; VR_OVERRIDE wins). */
static void find_xrizer(void) {
	if (getenv("VR_OVERRIDE")) {
		return; // the user's choice
	}
	char path[4096] = "";
	const char *data = getenv("XDG_DATA_HOME"), *home = getenv("HOME");
	if (data && *data) {
		snprintf(path, sizeof(path), "%s/xrizer", data);
	} else if (home) {
		snprintf(path, sizeof(path), "%s/.local/share/xrizer", home);
	}
	if (!*path || access(path, R_OK) != 0) {
		snprintf(path, sizeof(path), "%s/xrizer", C8_DATADIR);
		if (access(path, R_OK) != 0) {
			return;
		}
	}
	setenv("VR_OVERRIDE", path, true);
	wlr_log(WLR_INFO, "XR: SteamVR's games go through xrizer (%s)", path);
	const char *config = getenv("XDG_CONFIG_HOME");
	char dir[4096], file[4200];
	if (config && *config) {
		snprintf(dir, sizeof(dir), "%s/openvr", config);
	} else if (home) {
		snprintf(dir, sizeof(dir), "%s/.config/openvr", home);
	} else {
		return;
	}
	snprintf(file, sizeof(file), "%s/openvrpaths.vrpath", dir);
	if (access(file, F_OK) == 0) {
		return;
	}
	mkdir(dir, 0755);
	FILE *f = fopen(file, "w");
	if (f) {
		fprintf(f, "{\n\t\"version\": 1,\n\t\"runtime\": [\"%s\"]\n}\n", path);
		fclose(f);
	}
}

void c8_xr_runtime_init(struct c8_server *server) {
	struct c8_xr_monado *rt = calloc(1, sizeof(*rt));
	rt->server = server;
	rt->pid = -1;
	rt->pidfd = -1;
	rt->stop_fd = -1;
	rt->share_fd = -1;
	rt->timer = wl_event_loop_add_timer(server->loop, tick, rt);
	rt->reaper = wl_event_loop_add_timer(server->loop, reap, rt);
	rt->draining = wl_event_loop_add_timer(server->loop, drain, rt);
	server->xr.runtime = rt;
	/* Our overlay finds our Monado; so do games started from here,
	 * unless the user chose a runtime of their own (session.c) */
	if (runtime_wanted(rt) && getenv("XR_RUNTIME_JSON") == NULL) {
		setenv("XR_RUNTIME_JSON", rt->json, true);
		/* Steam's container (Proton 6 on): the host's runtime, and
		 * Monado's socket, which it doesn't see otherwise */
		setenv("PRESSURE_VESSEL_IMPORT_OPENXR_1_RUNTIMES", "1", false);
		const char *run = getenv("XDG_RUNTIME_DIR");
		if (run && getenv("PRESSURE_VESSEL_FILESYSTEMS_RW") == NULL) {
			char sock[4096];
			snprintf(sock, sizeof(sock), "%s/monado_comp_ipc", run);
			setenv("PRESSURE_VESSEL_FILESYSTEMS_RW", sock, true);
		}
		find_xrizer();
	}
}

void c8_xr_runtime_finish(struct c8_server *server) {
	struct c8_xr_monado *rt = server->xr.runtime;
	if (rt == NULL) {
		return;
	}
	runtime_kill(rt);
	if (rt->sbs_asked) {
		c8_glasses_set_sbs(server, false, false);
	}
	if (rt->exited) {
		wl_event_source_remove(rt->exited);
		struct pollfd pfd = { .fd = rt->pidfd, .events = POLLIN };
		if (poll(&pfd, 1, 2000) <= 0) {
			kill(rt->pid, SIGKILL); // asked to stop, but still there
		}
		close(rt->pidfd);
		waitpid(rt->pid, NULL, 0);
	}
	share_close(rt);
	wl_event_source_remove(rt->reaper);
	wl_event_source_remove(rt->draining);
	wl_event_source_remove(rt->timer);
	free(rt->service);
	free(rt->json);
	free(rt);
	server->xr.runtime = NULL;
}

bool c8_xr_runtime_update(struct c8_server *server, bool xr,
		struct c8_output *glasses) {
	struct c8_xr_monado *rt = server->xr.runtime;
	if (rt == NULL) {
		return false;
	}
	if (!xr || !runtime_wanted(rt) || (glasses == NULL && !server->xr.leased)) {
		if (rt->pid > 0) {
			wlr_log(WLR_INFO, "XR: stopping Monado");
			runtime_kill(rt);
		}
		if (rt->sbs_asked) {
			rt->sbs_asked = false;
			c8_glasses_set_sbs(server, false, false);
		}
		return false;
	}
	if (rt->waiting) {
		return false; // a restart's pause: ours meanwhile
	}
	if (glasses && rt->pid < 0 && !rt->sbs_asked &&
			server->config.glasses.sbs_switch &&
			glasses->wlr_output->width < 3840) {
		/* Two eyes need their 3D mode; their display changes, then is
		 * offered (ours meanwhile) */
		rt->sbs_asked = true;
		c8_glasses_set_sbs(server, true, true);
		schedule(rt, RESTART_MS, true);
		return false;
	}
	if (glasses && rt->target != glasses->wlr_output) {
		/* Offered before it starts, so the connector is there to name */
		if (rt->pid > 0) {
			/* Back while Monado runs: the glasses went and came back
			 * (their 3D button changes the display), so the lease
			 * Monado had is gone and it can't get it back. Started
			 * again for the new display (exited() does it); until then
			 * nobody draws and our IMU connection stays shut, or the
			 * driver's and ours would both read the glasses. */
			if (!rt->stopping) {
				wlr_log(WLR_INFO, "XR: the glasses came back; starting "
					"Monado again for them");
				runtime_kill(rt);
			}
			return true;
		}
		if (c8_lease_offer(server, glasses->wlr_output)) {
			rt->offered = glasses->wlr_output;
		} else if (server->lease.manager) {
			return false; // DRM, but not leasable: ours
		}
		rt->target = glasses->wlr_output;
	}
	if (rt->pid < 0) {
		/* Our IMU connection goes first: the driver opens its own */
		c8_tracker_set_wanted(server->xr.tracker, false);
		if (!runtime_spawn(rt)) {
			rt->failed = true;
			return false;
		}
		schedule(rt, CONNECT_MS, false);
	}
	return true;
}

void c8_xr_runtime_output_gone(struct c8_server *server,
		struct wlr_output *output) {
	struct c8_xr_monado *rt = server->xr.runtime;
	if (rt && rt->offered == output) {
		rt->offered = NULL;
	}
	if (rt && rt->target == output) {
		rt->target = NULL;
	}
}

bool c8_xr_runtime_is_client(struct c8_server *server,
		const struct wl_client *client) {
	struct c8_xr_monado *rt = server->xr.runtime;
	return rt && rt->client && rt->client == client;
}

bool c8_xr_runtime_has_client(struct c8_server *server) {
	struct c8_xr_monado *rt = server->xr.runtime;
	return rt && rt->client;
}
