/*
 * xdg-output, as wlroots' but for outputs out of the layout too.
 *
 * In XR the glasses are out of the layout (glasses.c) yet
 * have a wl_output, so screen sharing can capture what they show. The
 * portal asks every wl_output it sees for its xdg_output, and wlroots'
 * manager asserts the output is in the layout: c8 went down. Here one
 * out of the layout is just past the layout's right edge, at its own size. Only the portal and its
 * picker (c8-share) see such a wl_output at all
 * (c8_output_global_visible), so no app or Xwayland takes it for a
 * screen to put things on.
 */
#define _POSIX_C_SOURCE 200809L
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <wlr/types/wlr_output.h>
#include <wlr/types/wlr_output_layout.h>
#include "server.h"
#include "xdg-output-unstable-v1-protocol.h"

#define MANAGER_VERSION 3
#define DONE_DEPRECATED_SINCE 3
#define DESCRIPTION_MUTABLE_SINCE 3

/* One per zxdg_output_v1 */
struct xdg_out {
	struct wl_resource *resource;
	struct wlr_output *output; // NULL once gone
	struct c8_server *server;
	bool sent;
	int x, y, width, height;
	struct wl_listener output_destroy;
	struct wl_listener commit;
	struct wl_listener description;
	struct wl_list link; // xdg_outs
};

static struct wl_list xdg_outs;
static struct wl_listener layout_change, layout_destroy;

static void out_forget(struct xdg_out *xo) {
	if (xo->output == NULL) {
		return;
	}
	xo->output = NULL;
	wl_list_remove(&xo->output_destroy.link);
	wl_list_remove(&xo->commit.link);
	wl_list_remove(&xo->description.link);
}

/* Send where and how big, when that changed (or never was sent) */
static void out_update(struct xdg_out *xo) {
	struct wlr_output *output = xo->output;
	if (output == NULL) {
		return;
	}
	struct wlr_output_layout_output *lo =
		wlr_output_layout_get(xo->server->output_layout, output);
	int x, y, width, height;
	if (lo) {
		x = lo->x;
		y = lo->y;
	} else {
		/* Out of the layout: just past its right edge, so a tool that
		 * captures by region (grim -o) doesn't find the layout's
		 * screen at 0,0 over it (XR-1 hid XR-VIEW, 2026-12-03) */
		struct wlr_box box;
		wlr_output_layout_get_box(xo->server->output_layout, NULL, &box);
		x = box.x + box.width;
		y = box.y;
	}
	wlr_output_effective_resolution(output, &width, &height);
	if (xo->sent && x == xo->x && y == xo->y && width == xo->width &&
			height == xo->height) {
		return;
	}
	bool first = !xo->sent;
	xo->sent = true;
	xo->x = x;
	xo->y = y;
	xo->width = width;
	xo->height = height;
	zxdg_output_v1_send_logical_position(xo->resource, x, y);
	zxdg_output_v1_send_logical_size(xo->resource, width, height);
	if (wl_resource_get_version(xo->resource) < DONE_DEPRECATED_SINCE) {
		zxdg_output_v1_send_done(xo->resource);
	} else if (!first) {
		wlr_output_schedule_done(output);
	}
}

static void handle_output_destroy(struct wl_listener *listener, void *data) {
	struct xdg_out *xo = wl_container_of(listener, xo, output_destroy);
	out_forget(xo);
}

static void handle_commit(struct wl_listener *listener, void *data) {
	struct xdg_out *xo = wl_container_of(listener, xo, commit);
	struct wlr_output_event_commit *event = data;
	if (event->state->committed & (WLR_OUTPUT_STATE_MODE |
			WLR_OUTPUT_STATE_SCALE | WLR_OUTPUT_STATE_TRANSFORM)) {
		out_update(xo);
	}
}

static void handle_description(struct wl_listener *listener, void *data) {
	struct xdg_out *xo = wl_container_of(listener, xo, description);
	if (xo->output->description && wl_resource_get_version(xo->resource) >=
			DESCRIPTION_MUTABLE_SINCE) {
		zxdg_output_v1_send_description(xo->resource,
			xo->output->description);
	}
}

static void handle_layout_change(struct wl_listener *listener, void *data) {
	struct xdg_out *xo;
	wl_list_for_each(xo, &xdg_outs, link) {
		out_update(xo);
	}
}

static void out_handle_destroy(struct wl_client *client,
		struct wl_resource *resource) {
	wl_resource_destroy(resource);
}

static const struct zxdg_output_v1_interface out_impl = {
	.destroy = out_handle_destroy,
};

static void out_resource_destroy(struct wl_resource *resource) {
	struct xdg_out *xo = wl_resource_get_user_data(resource);
	out_forget(xo);
	wl_list_remove(&xo->link);
	free(xo);
}

static void manager_handle_destroy(struct wl_client *client,
		struct wl_resource *resource) {
	wl_resource_destroy(resource);
}

static void manager_get_xdg_output(struct wl_client *client,
		struct wl_resource *resource, uint32_t id,
		struct wl_resource *output_resource) {
	struct xdg_out *xo = calloc(1, sizeof(*xo));
	if (xo == NULL) {
		wl_client_post_no_memory(client);
		return;
	}
	xo->resource = wl_resource_create(client, &zxdg_output_v1_interface,
		wl_resource_get_version(resource), id);
	if (xo->resource == NULL) {
		free(xo);
		wl_client_post_no_memory(client);
		return;
	}
	xo->server = wl_resource_get_user_data(resource);
	wl_resource_set_implementation(xo->resource, &out_impl, xo,
		out_resource_destroy);
	wl_list_insert(&xdg_outs, &xo->link);

	struct wlr_output *output = wlr_output_from_resource(output_resource);
	if (output == NULL) {
		return; // inert: the output is gone already
	}
	xo->output = output;
	c8_listen(&xo->output_destroy, &output->events.destroy,
		handle_output_destroy);
	c8_listen(&xo->commit, &output->events.commit, handle_commit);
	c8_listen(&xo->description, &output->events.description,
		handle_description);

	uint32_t version = wl_resource_get_version(xo->resource);
	if (version >= ZXDG_OUTPUT_V1_NAME_SINCE_VERSION) {
		zxdg_output_v1_send_name(xo->resource, output->name);
	}
	if (version >= ZXDG_OUTPUT_V1_DESCRIPTION_SINCE_VERSION &&
			output->description) {
		zxdg_output_v1_send_description(xo->resource, output->description);
	}
	out_update(xo);
	if (version >= DONE_DEPRECATED_SINCE && wl_resource_get_version(
			output_resource) >= WL_OUTPUT_DONE_SINCE_VERSION) {
		wl_output_send_done(output_resource);
	}
}

static const struct zxdg_output_manager_v1_interface manager_impl = {
	.destroy = manager_handle_destroy,
	.get_xdg_output = manager_get_xdg_output,
};

static void manager_bind(struct wl_client *client, void *data,
		uint32_t version, uint32_t id) {
	struct wl_resource *resource = wl_resource_create(client,
		&zxdg_output_manager_v1_interface, version, id);
	if (resource == NULL) {
		wl_client_post_no_memory(client);
		return;
	}
	wl_resource_set_implementation(resource, &manager_impl, data, NULL);
}

/* The layout wants its listeners gone before it goes */
static void handle_layout_destroy(struct wl_listener *listener, void *data) {
	wl_list_remove(&layout_change.link);
	wl_list_remove(&layout_destroy.link);
}

void c8_xdg_output_init(struct c8_server *server) {
	wl_list_init(&xdg_outs);
	wl_global_create(server->display, &zxdg_output_manager_v1_interface,
		MANAGER_VERSION, server, manager_bind);
	c8_listen(&layout_change, &server->output_layout->events.change,
		handle_layout_change);
	c8_listen(&layout_destroy, &server->output_layout->events.destroy,
		handle_layout_destroy);
}

/* Is this client xdg-desktop-portal-wlr, the screen-sharing portal, or
 * c8-share, the picker it runs? */
static bool is_portal(const struct wl_client *client) {
	pid_t pid;
	wl_client_get_credentials((struct wl_client *)client, &pid, NULL, NULL);
	char path[64], exe[PATH_MAX];
	snprintf(path, sizeof(path), "/proc/%d/exe", (int)pid);
	ssize_t n = readlink(path, exe, sizeof(exe) - 1);
	if (n <= 0) {
		return false;
	}
	exe[n] = '\0';
	const char *base = strrchr(exe, '/');
	base = base ? base + 1 : exe;
	return strcmp(base, "xdg-desktop-portal-wlr") == 0 ||
		strcmp(base, "c8-share") == 0;
}

bool c8_output_global_visible(struct c8_server *server,
		const struct wl_client *client, const struct wl_global *global) {
	if (wl_global_get_interface(global) != &wl_output_interface) {
		return true;
	}
	/* By its data, not wlr_output.global: that's set only after
	 * wl_global_create, which announces it (through here) first */
	struct wlr_output *wo = wl_global_get_user_data(global);
	struct c8_output *output;
	wl_list_for_each(output, &server->outputs, link) {
		if (wo && output->wlr_output == wo) {
			/* Out of the layout an output has no global (output.c
			 * layout_remove) but the glasses' own, made for capturing
			 * while they're hidden: no app is told of it */
			return !output->capture_global || is_portal(client);
		}
	}
	return true;
}
