/*
 * Smaller Wayland protocols apps and tools expect:
 *
 * - xdg-activation: an app asks to bring a window forward (a link opened
 *   from chat focuses the browser). Granted when the token came from
 *   something the user just did.
 * - xdg-foreign: file choosers and other portal dialogs open over the
 *   window that asked.
 * - gamma control: night light tools (gammastep, wlsunset).
 * - foreign toplevel lists (ext and wlr): window lists in other tools,
 *   and window capture for screen sharing a single app.
 * - ext-image-copy-capture: screenshots and screen sharing, the newer way.
 * - explicit sync, alpha modifier, xdg-dialog.
 */
#define _GNU_SOURCE
#include <stdlib.h>
#include <wlr/render/color.h>
#include <wlr/types/wlr_alpha_modifier_v1.h>
#include <wlr/types/wlr_ext_foreign_toplevel_list_v1.h>
#include <wlr/types/wlr_ext_image_capture_source_v1.h>
#include <wlr/types/wlr_ext_image_copy_capture_v1.h>
#include <wlr/types/wlr_foreign_toplevel_management_v1.h>
#include <wlr/types/wlr_gamma_control_v1.h>
#include <wlr/types/wlr_linux_drm_syncobj_v1.h>
#include <wlr/types/wlr_scene.h>
#include <wlr/types/wlr_xdg_activation_v1.h>
#include <wlr/types/wlr_xdg_dialog_v1.h>
#include <wlr/types/wlr_xdg_foreign_registry.h>
#include <wlr/types/wlr_xdg_foreign_v1.h>
#include <wlr/types/wlr_xdg_foreign_v2.h>
#include <wlr/util/log.h>
#if C8_HAVE_XWAYLAND
#include <wlr/xwayland.h>
#endif
#include "server.h"

static struct {
	struct wlr_ext_foreign_toplevel_list_v1 *ext_list;
	struct wlr_foreign_toplevel_manager_v1 *wlr_manager;
	struct wlr_gamma_control_manager_v1 *gamma;
	struct wlr_xdg_activation_v1 *activation;
} p;

/* Marks the tokens c8_launch_token made */
static char launch_mark;

static struct c8_view *view_from_surface(struct wlr_surface *surface) {
	struct wlr_xdg_toplevel *toplevel =
		wlr_xdg_toplevel_try_from_wlr_surface(surface);
	if (toplevel) {
		return toplevel->base->data;
	}
#if C8_HAVE_XWAYLAND
	struct wlr_xwayland_surface *xs =
		wlr_xwayland_surface_try_from_wlr_surface(surface);
	if (xs) {
		return xs->data;
	}
#endif
	return NULL;
}

/* Activation */

static void request_activate(struct wl_listener *listener, void *data) {
	struct c8_server *server =
		wl_container_of(listener, server, protocols.request_activate);
	struct wlr_xdg_activation_v1_request_activate_event *event = data;
	struct c8_view *view = view_from_surface(event->surface);
	if (view == NULL || !view->mapped || c8_locked(server)) {
		return;
	}
	/* From a click or key press (a link clicked in another app), or from
	 * the shell (a toast clicked); not an app pushing itself forward */
	struct wlr_xdg_activation_token_v1 *token = event->token;
	bool from_shell = token->surface && c8_shell_is_client(server,
		wl_resource_get_client(token->surface->resource));
	bool launched = token->data == &launch_mark;
	if (token->seat == NULL && !from_shell && !launched) {
		wlr_log(WLR_DEBUG, "Activation without user input: ignored");
		return;
	}
	/* The serial has to be from input since focus last moved, or an app
	 * that asks to be activated whenever it loses focus (Electron's
	 * window.focus()) can't be switched away from: the Alt of Alt+Tab
	 * was its own input, and the serial stays valid for a while */
	if (token->seat != NULL && !from_shell && !launched &&
			(int32_t)(token->serial - server->focus_serial) <= 0) {
		wlr_log(WLR_DEBUG, "Activation from before the last focus change: ignored");
		return;
	}
	c8_view_activate(view);
}

const char *c8_launch_token(struct c8_server *server) {
	if (p.activation == NULL) {
		return NULL;
	}
	/* Times out like any other (30 s) if the app never uses it */
	struct wlr_xdg_activation_token_v1 *token =
		wlr_xdg_activation_token_v1_create(p.activation);
	if (token == NULL) {
		return NULL;
	}
	token->data = &launch_mark;
	return wlr_xdg_activation_token_v1_get_name(token);
}

/* Night light tools of others; ours is nightlight.c */

static void set_gamma(struct wl_listener *listener, void *data) {
	struct wlr_gamma_control_manager_v1_set_gamma_event *event = data;
	struct wlr_color_transform *tr =
		wlr_gamma_control_v1_get_color_transform(event->control);
	struct wlr_output_state state;
	wlr_output_state_init(&state);
	wlr_output_state_set_color_transform(&state, tr);
	if (!wlr_output_commit_state(event->output, &state) && event->control) {
		wlr_gamma_control_v1_send_failed_and_destroy(event->control);
	}
	wlr_output_state_finish(&state);
	if (tr) {
		wlr_color_transform_unref(tr);
	}
	/* Theirs while they hold it; ours again when they let go */
	struct c8_server *server =
		wl_container_of(listener, server, protocols.set_gamma);
	c8_nightlight_gamma_client(server, event->output, tr != NULL);
}

/* Window lists */

static void handle_activate(struct wl_listener *listener, void *data) {
	struct c8_view *view = wl_container_of(listener, view, listed.activate);
	if (!c8_locked(view->server)) {
		c8_view_activate(view);
	}
}

static void handle_close(struct wl_listener *listener, void *data) {
	struct c8_view *view = wl_container_of(listener, view, listed.close);
	c8_view_close(view);
}

static void handle_minimize(struct wl_listener *listener, void *data) {
	struct c8_view *view = wl_container_of(listener, view, listed.minimize);
	struct wlr_foreign_toplevel_handle_v1_minimized_event *event = data;
	if (event->minimized) {
		if (!c8_locked(view->server)) {
			c8_view_minimize(view);
		}
	} else if (!c8_locked(view->server)) {
		c8_view_activate(view);
	}
}

static const char *or_empty(const char *s) {
	return s ? s : "";
}

void c8_toplevel_mapped(struct c8_view *view) {
	struct wlr_ext_foreign_toplevel_handle_v1_state state = {
		.title = or_empty(c8_view_title(view)),
		.app_id = or_empty(c8_view_app_id(view)),
	};
	if (p.ext_list) {
		view->listed.ext = wlr_ext_foreign_toplevel_handle_v1_create(
			p.ext_list, &state);
		if (view->listed.ext) {
			view->listed.ext->data = view;
		}
	}
	if (p.wlr_manager) {
		struct wlr_foreign_toplevel_handle_v1 *h =
			wlr_foreign_toplevel_handle_v1_create(p.wlr_manager);
		view->listed.wlr = h;
		if (h) {
			h->data = view;
			wlr_foreign_toplevel_handle_v1_set_title(h, state.title);
			wlr_foreign_toplevel_handle_v1_set_app_id(h, state.app_id);
			c8_listen(&view->listed.activate, &h->events.request_activate,
				handle_activate);
			c8_listen(&view->listed.close, &h->events.request_close,
				handle_close);
			c8_listen(&view->listed.minimize, &h->events.request_minimize,
				handle_minimize);
		}
	}
	c8_toplevels_focus_changed(view->server);
}

static void capture_drop(struct c8_view *view);

void c8_toplevel_unmapped(struct c8_view *view) {
	capture_drop(view);
	if (view->listed.ext) {
		wlr_ext_foreign_toplevel_handle_v1_destroy(view->listed.ext);
		view->listed.ext = NULL;
	}
	if (view->listed.wlr) {
		wl_list_remove(&view->listed.activate.link);
		wl_list_remove(&view->listed.close.link);
		wl_list_remove(&view->listed.minimize.link);
		wlr_foreign_toplevel_handle_v1_destroy(view->listed.wlr);
		view->listed.wlr = NULL;
	}
}

void c8_toplevel_changed(struct c8_view *view) {
	struct wlr_ext_foreign_toplevel_handle_v1_state state = {
		.title = or_empty(c8_view_title(view)),
		.app_id = or_empty(c8_view_app_id(view)),
	};
	if (view->listed.ext) {
		wlr_ext_foreign_toplevel_handle_v1_update_state(view->listed.ext,
			&state);
	}
	if (view->listed.wlr) {
		wlr_foreign_toplevel_handle_v1_set_title(view->listed.wlr,
			state.title);
		wlr_foreign_toplevel_handle_v1_set_app_id(view->listed.wlr,
			state.app_id);
	}
}

void c8_toplevels_focus_changed(struct c8_server *server) {
	struct c8_view *top = server->start_visible ? NULL : c8_top_view(server);
	struct c8_view *view;
	wl_list_for_each(view, &server->views, link) {
		if (view->listed.wlr) {
			wlr_foreign_toplevel_handle_v1_set_activated(view->listed.wlr,
				view == top);
			wlr_foreign_toplevel_handle_v1_set_minimized(view->listed.wlr,
				c8_holo_minimised(view));
		}
	}
}

/* Capturing one window. wlroots' source for a scene node renders the
 * whole scene over the node's box: whatever covers the window (another
 * app, Start, the share picker) was in the picture, and a window not
 * shown (only one app is on screen) gave nothing at all. So each window
 * shared gets a scene of its own holding only its surfaces (a second
 * scene node for the same surfaces, as mirroring does), and the source
 * renders that. It keeps the window drawing while hidden: the capture's
 * output paces its frames then. Popups aren't in it. One source per
 * window, kept until it unmaps (wlroots frees sources only with their
 * node). */

static void capture_gone(struct wl_listener *listener, void *data) {
	/* The surface went (an X11 window's can be swapped); the source went
	 * with its node. The scene itself goes at the next request or unmap */
	struct c8_view *view = wl_container_of(listener, view,
		listed.capture_gone);
	wl_list_remove(&view->listed.capture_gone.link);
	view->listed.capture = NULL;
}

static void capture_drop(struct c8_view *view) {
	if (view->listed.capture) {
		wl_list_remove(&view->listed.capture_gone.link);
		view->listed.capture = NULL;
	}
	if (view->listed.capture_scene) {
		/* Destroys the source too, ending its sessions */
		wlr_scene_node_destroy(&view->listed.capture_scene->tree.node);
		view->listed.capture_scene = NULL;
	}
}

static void capture_request(struct wl_listener *listener, void *data) {
	struct c8_server *server =
		wl_container_of(listener, server, protocols.capture_request);
	struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request
		*request = data;
	struct c8_view *view = request->toplevel_handle->data;
	if (view == NULL || c8_locked(server)) {
		return;
	}
	if (view->listed.capture == NULL) {
		capture_drop(view);
		struct wlr_surface *surface = view->impl->get_surface(view);
		struct wlr_scene *scene = surface ? wlr_scene_create() : NULL;
		struct wlr_scene_tree *tree = scene ?
			wlr_scene_subsurface_tree_create(&scene->tree, surface) : NULL;
		struct wlr_ext_image_capture_source_v1 *source = tree ?
			wlr_ext_image_capture_source_v1_create_with_scene_node(
			&tree->node, server->loop, server->allocator,
			server->renderer) : NULL;
		if (source == NULL) {
			if (scene) {
				wlr_scene_node_destroy(&scene->tree.node);
			}
			wlr_log(WLR_ERROR, "Window capture: no source");
			return;
		}
		view->listed.capture_scene = scene;
		view->listed.capture = source;
		c8_listen(&view->listed.capture_gone, &tree->node.events.destroy,
			capture_gone);
	}
	wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request_accept(
		request, view->listed.capture);
}

void c8_protocols_init(struct c8_server *server) {
	struct wl_display *d = server->display;

	struct wlr_xdg_activation_v1 *activation = wlr_xdg_activation_v1_create(d);
	p.activation = activation;
	c8_listen(&server->protocols.request_activate, &activation->events.request_activate,
		request_activate);

	struct wlr_xdg_foreign_registry *registry =
		wlr_xdg_foreign_registry_create(d);
	wlr_xdg_foreign_v1_create(d, registry);
	wlr_xdg_foreign_v2_create(d, registry);

	p.gamma = wlr_gamma_control_manager_v1_create(d);
	c8_listen(&server->protocols.set_gamma, &p.gamma->events.set_gamma,
		set_gamma);

	p.ext_list = wlr_ext_foreign_toplevel_list_v1_create(d, 1);
	p.wlr_manager = wlr_foreign_toplevel_manager_v1_create(d);

	wlr_ext_image_copy_capture_manager_v1_create(d, 1);
	wlr_ext_output_image_capture_source_manager_v1_create(d, 1);
	struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1 *tcap =
		wlr_ext_foreign_toplevel_image_capture_source_manager_v1_create(d, 1);
	c8_listen(&server->protocols.capture_request, &tcap->events.new_request,
		capture_request);

	/* Explicit sync: what Nvidia and newer Mesa want, when the GPU and
	 * the screens both do timelines */
	int drm_fd = wlr_renderer_get_drm_fd(server->renderer);
	if (drm_fd >= 0 && server->renderer->features.timeline &&
			server->backend->features.timeline) {
		wlr_linux_drm_syncobj_manager_v1_create(d, 1, drm_fd);
	}
	wlr_alpha_modifier_v1_create(d);
	wlr_xdg_wm_dialog_v1_create(d, 1);
}

void c8_protocols_finish(struct c8_server *server) {
	wl_list_remove(&server->protocols.request_activate.link);
	wl_list_remove(&server->protocols.set_gamma.link);
	wl_list_remove(&server->protocols.capture_request.link);
}
