#include <stdlib.h>
#include "server.h"

#if C8_HAVE_XWAYLAND

#include <wlr/types/wlr_buffer.h>
#include <wlr/util/log.h>
#include <wlr/xwayland.h>
#include <xcb/xproto.h>

/* A managed X11 window: tiles, snaps and floats like an xdg toplevel */
struct c8_xview {
	struct c8_view base;
	struct wlr_xwayland_surface *xsurface;
	struct wlr_scene_tree *surface_tree;
	bool associated, activated, fullscreen;

	struct wl_listener destroy, associate, dissociate, map, unmap,
		request_configure, request_fullscreen, request_activate, set_title,
		set_class;
};

/* Override-redirect windows: menus, tooltips, drag icons */
struct c8_unmanaged {
	struct c8_server *server;
	struct wlr_xwayland_surface *xsurface;
	struct wlr_scene_tree *tree;
	struct c8_node_desc desc;
	bool associated;

	struct wl_listener destroy, associate, dissociate, map, unmap,
		request_configure, set_geometry;
};

static struct c8_xview *xview_from_view(struct c8_view *view) {
	struct c8_xview *xview = wl_container_of(view, xview, base);
	return xview;
}

static struct wlr_surface *x_get_surface(struct c8_view *view) {
	return xview_from_view(view)->xsurface->surface;
}

static const char *x_get_title(struct c8_view *view) {
	return xview_from_view(view)->xsurface->title;
}

static const char *x_get_app_id(struct c8_view *view) {
	return xview_from_view(view)->xsurface->class;
}

static struct c8_view *x_get_parent(struct c8_view *view) {
	struct wlr_xwayland_surface *parent = xview_from_view(view)->xsurface->parent;
	return parent && !parent->override_redirect ? parent->data : NULL;
}

static bool x_wants_fullscreen(struct c8_view *view) {
	return xview_from_view(view)->xsurface->fullscreen;
}

/* Where X is told a window is: where it's drawn, but in XR
 * that's a slot a million pixels off the screen, past X's 16 bits, and
 * Xwayland turns the pointer's place on the surface into one on its
 * root window (the layout), where the X server keeps the pointer: the
 * app never saw it. So there X has every window at the shell's screen's
 * corner, overlapping (x_raise_pointed sorts out which gets the pointer) */
static void x_origin(struct c8_view *view, int x, int y, int *xo, int *yo) {
	*xo = x;
	*yo = y;
	if (c8_xr_active(view->server)) {
		struct wlr_box out;
		c8_output_box(view->server, &out);
		*xo = out.x;
		*yo = out.y;
	}
}

static void x_configure(struct c8_view *view, struct wlr_box box, bool fullscreen) {
	struct c8_xview *xview = xview_from_view(view);
	struct wlr_xwayland_surface *xs = xview->xsurface;
	wlr_scene_node_set_position(&view->tree->node, box.x, box.y);
	if (view->geo.x == box.x && view->geo.y == box.y &&
			view->geo.width == box.width && view->geo.height == box.height &&
			xview->fullscreen == fullscreen) {
		return;
	}
	view->geo = box;
	xview->fullscreen = fullscreen;
	wlr_xwayland_surface_set_maximized(xs, !fullscreen, !fullscreen);
	wlr_xwayland_surface_set_fullscreen(xs, fullscreen);
	int x, y;
	x_origin(view, box.x, box.y, &x, &y);
	wlr_xwayland_surface_configure(xs, x, y, box.width, box.height);
}

static void x_place(struct c8_view *view, struct wlr_box area) {
	struct wlr_xwayland_surface *xs = xview_from_view(view)->xsurface;
	int x = area.x + (area.width - xs->width) / 2;
	int y = area.y + (area.height - xs->height) / 2;
	if (y < area.y) {
		y = area.y;
	}
	view->geo = (struct wlr_box){ x, y, xs->width, xs->height };
	wlr_scene_node_set_position(&view->tree->node, x, y);
	int xx, xy;
	x_origin(view, x, y, &xx, &xy);
	if (xs->x != xx || xs->y != xy) {
		wlr_xwayland_surface_configure(xs, xx, xy, xs->width, xs->height);
	}
}

/* In XR every X window is at the same place in X (x_origin),
 * and X gives the pointer to the one on top there, not to the surface
 * it's on: the one it's on goes on top */
static void x_raise_pointed(struct c8_server *server, struct wlr_surface *surface) {
	if (surface == NULL || !c8_xr_active(server)) {
		return;
	}
	struct wlr_xwayland_surface *xs =
		wlr_xwayland_surface_try_from_wlr_surface(surface);
	if (xs) {
		wlr_xwayland_surface_restack(xs, NULL, XCB_STACK_MODE_ABOVE);
	}
}

static void x_activate(struct c8_view *view, bool activated) {
	struct c8_xview *xview = xview_from_view(view);
	if (xview->activated == activated) {
		return;
	}
	xview->activated = activated;
	wlr_xwayland_surface_activate(xview->xsurface, activated);
	if (activated) {
		wlr_xwayland_surface_restack(xview->xsurface, NULL, XCB_STACK_MODE_ABOVE);
		x_raise_pointed(view->server,
			view->server->seat->pointer_state.focused_surface);
	}
}

static void x_close(struct c8_view *view) {
	wlr_xwayland_surface_close(xview_from_view(view)->xsurface);
}

static const struct c8_view_impl xwayland_impl = {
	.get_surface = x_get_surface,
	.get_title = x_get_title,
	.get_app_id = x_get_app_id,
	.get_parent = x_get_parent,
	.wants_fullscreen = x_wants_fullscreen,
	.configure = x_configure,
	.place = x_place,
	.activate = x_activate,
	.close = x_close,
};

static bool x_wants_floating(struct wlr_xwayland_surface *xs) {
	static const enum wlr_xwayland_net_wm_window_type floating_types[] = {
		WLR_XWAYLAND_NET_WM_WINDOW_TYPE_DIALOG,
		WLR_XWAYLAND_NET_WM_WINDOW_TYPE_UTILITY,
		WLR_XWAYLAND_NET_WM_WINDOW_TYPE_TOOLBAR,
		WLR_XWAYLAND_NET_WM_WINDOW_TYPE_SPLASH,
	};
	if (xs->parent || xs->modal) {
		return true;
	}
	for (size_t i = 0; i < sizeof(floating_types) / sizeof(floating_types[0]); i++) {
		if (wlr_xwayland_surface_has_window_type(xs, floating_types[i])) {
			return true;
		}
	}
	xcb_size_hints_t *hints = xs->size_hints;
	return hints && hints->min_width > 0 && hints->min_height > 0 &&
		hints->min_width == hints->max_width &&
		hints->min_height == hints->max_height;
}

static void xview_map(struct wl_listener *listener, void *data) {
	struct c8_xview *xview = wl_container_of(listener, xview, map);
	struct wlr_xwayland_surface *xs = xview->xsurface;
	xview->surface_tree =
		wlr_scene_subsurface_tree_create(xview->base.tree, xs->surface);
	xview->base.floating = x_wants_floating(xs);
	xview->base.geo = (struct wlr_box){ 0 };
	xview->activated = false;
	c8_view_mapped(&xview->base);
}

static void xview_unmap(struct wl_listener *listener, void *data) {
	struct c8_xview *xview = wl_container_of(listener, xview, unmap);
	c8_view_unmapped(&xview->base);
	if (xview->surface_tree) {
		wlr_scene_node_destroy(&xview->surface_tree->node);
		xview->surface_tree = NULL;
	}
}

static void xview_associate(struct wl_listener *listener, void *data) {
	struct c8_xview *xview = wl_container_of(listener, xview, associate);
	struct wlr_surface *surface = xview->xsurface->surface;
	xview->associated = true;
	c8_listen(&xview->map, &surface->events.map, xview_map);
	c8_listen(&xview->unmap, &surface->events.unmap, xview_unmap);
}

static void xview_dissociate(struct wl_listener *listener, void *data) {
	struct c8_xview *xview = wl_container_of(listener, xview, dissociate);
	xview->associated = false;
	wl_list_remove(&xview->map.link);
	wl_list_remove(&xview->unmap.link);
}

static void xview_request_configure(struct wl_listener *listener, void *data) {
	struct c8_xview *xview = wl_container_of(listener, xview, request_configure);
	struct wlr_xwayland_surface_configure_event *event = data;
	struct c8_view *view = &xview->base;
	if (!view->mapped || view->floating) {
		/* Let it pick its size; floating windows get re-centred */
		wlr_xwayland_surface_configure(xview->xsurface, event->x, event->y,
			event->width, event->height);
		if (view->mapped) {
			c8_views_arrange(view->server);
		}
		return;
	}
	/* Tiled windows keep the geometry we gave them */
	struct wlr_box *g = &view->geo;
	int x, y;
	x_origin(view, g->x, g->y, &x, &y);
	wlr_xwayland_surface_configure(xview->xsurface, x, y, g->width,
		g->height);
}

static void xview_request_fullscreen(struct wl_listener *listener, void *data) {
	struct c8_xview *xview = wl_container_of(listener, xview, request_fullscreen);
	xview->base.holo.theatre_ask = 0; // the app's say again
	if (xview->base.mapped) {
		c8_views_arrange(xview->base.server);
	}
}

static void xview_request_activate(struct wl_listener *listener, void *data) {
	struct c8_xview *xview = wl_container_of(listener, xview, request_activate);
	if (xview->base.mapped) {
		c8_view_activate(&xview->base);
	}
}

static void xview_set_title(struct wl_listener *listener, void *data) {
	struct c8_xview *xview = wl_container_of(listener, xview, set_title);
	c8_view_props_changed(&xview->base);
}

static void xview_set_class(struct wl_listener *listener, void *data) {
	struct c8_xview *xview = wl_container_of(listener, xview, set_class);
	c8_view_props_changed(&xview->base);
}

static void xview_destroy(struct wl_listener *listener, void *data) {
	struct c8_xview *xview = wl_container_of(listener, xview, destroy);
	xview->xsurface->data = NULL;
	if (xview->associated) {
		wl_list_remove(&xview->map.link);
		wl_list_remove(&xview->unmap.link);
	}
	wl_list_remove(&xview->destroy.link);
	wl_list_remove(&xview->associate.link);
	wl_list_remove(&xview->dissociate.link);
	wl_list_remove(&xview->request_configure.link);
	wl_list_remove(&xview->request_fullscreen.link);
	wl_list_remove(&xview->request_activate.link);
	wl_list_remove(&xview->set_title.link);
	wl_list_remove(&xview->set_class.link);
	wlr_scene_node_destroy(&xview->base.tree->node);
	c8_view_title_free(&xview->base);
	free(xview);
}

static void xview_create(struct c8_server *server, struct wlr_xwayland_surface *xs) {
	struct c8_xview *xview = calloc(1, sizeof(*xview));
	struct c8_view *view = &xview->base;
	view->server = server;
	view->impl = &xwayland_impl;
	view->desc.type = C8_NODE_VIEW;
	view->desc.data = view;
	view->tree = wlr_scene_tree_create(server->layers.views);
	view->tree->node.data = &view->desc;
	wl_list_init(&view->link);
	xview->xsurface = xs;
	xs->data = view;

	c8_listen(&xview->destroy, &xs->events.destroy, xview_destroy);
	c8_listen(&xview->associate, &xs->events.associate, xview_associate);
	c8_listen(&xview->dissociate, &xs->events.dissociate, xview_dissociate);
	c8_listen(&xview->request_configure, &xs->events.request_configure,
		xview_request_configure);
	c8_listen(&xview->request_fullscreen, &xs->events.request_fullscreen,
		xview_request_fullscreen);
	c8_listen(&xview->request_activate, &xs->events.request_activate,
		xview_request_activate);
	c8_listen(&xview->set_title, &xs->events.set_title, xview_set_title);
	c8_listen(&xview->set_class, &xs->events.set_class, xview_set_class);
}

/* Unmanaged */

static void unmanaged_map(struct wl_listener *listener, void *data) {
	struct c8_unmanaged *um = wl_container_of(listener, um, map);
	struct wlr_xwayland_surface *xs = um->xsurface;
	um->tree = wlr_scene_subsurface_tree_create(um->server->layers.unmanaged,
		xs->surface);
	um->tree->node.data = &um->desc;
	wlr_scene_node_set_position(&um->tree->node, xs->x, xs->y);
	/* Not from a card that holds the keyboard (a password being typed):
	 * any X program can map one of these */
	if (um->server->focused_layer == NULL &&
			wlr_xwayland_surface_override_redirect_wants_focus(xs)) {
		c8_view_keyboard_enter(um->server, xs->surface);
	}
}

static void unmanaged_unmap(struct wl_listener *listener, void *data) {
	struct c8_unmanaged *um = wl_container_of(listener, um, unmap);
	struct c8_server *server = um->server;
	if (um->tree) {
		wlr_scene_node_destroy(&um->tree->node);
		um->tree = NULL;
	}
	if (server->seat->keyboard_state.focused_surface == um->xsurface->surface) {
		c8_focus_restore(server);
	}
}

static void unmanaged_set_geometry(struct wl_listener *listener, void *data) {
	struct c8_unmanaged *um = wl_container_of(listener, um, set_geometry);
	if (um->tree) {
		wlr_scene_node_set_position(&um->tree->node, um->xsurface->x,
			um->xsurface->y);
	}
}

static void unmanaged_request_configure(struct wl_listener *listener, void *data) {
	struct c8_unmanaged *um = wl_container_of(listener, um, request_configure);
	struct wlr_xwayland_surface_configure_event *event = data;
	wlr_xwayland_surface_configure(um->xsurface, event->x, event->y,
		event->width, event->height);
}

static void unmanaged_associate(struct wl_listener *listener, void *data) {
	struct c8_unmanaged *um = wl_container_of(listener, um, associate);
	struct wlr_surface *surface = um->xsurface->surface;
	um->associated = true;
	c8_listen(&um->map, &surface->events.map, unmanaged_map);
	c8_listen(&um->unmap, &surface->events.unmap, unmanaged_unmap);
}

static void unmanaged_dissociate(struct wl_listener *listener, void *data) {
	struct c8_unmanaged *um = wl_container_of(listener, um, dissociate);
	um->associated = false;
	wl_list_remove(&um->map.link);
	wl_list_remove(&um->unmap.link);
}

static void unmanaged_destroy(struct wl_listener *listener, void *data) {
	struct c8_unmanaged *um = wl_container_of(listener, um, destroy);
	if (um->associated) {
		wl_list_remove(&um->map.link);
		wl_list_remove(&um->unmap.link);
	}
	wl_list_remove(&um->destroy.link);
	wl_list_remove(&um->associate.link);
	wl_list_remove(&um->dissociate.link);
	wl_list_remove(&um->request_configure.link);
	wl_list_remove(&um->set_geometry.link);
	free(um);
}

static void unmanaged_create(struct c8_server *server,
		struct wlr_xwayland_surface *xs) {
	struct c8_unmanaged *um = calloc(1, sizeof(*um));
	um->server = server;
	um->xsurface = xs;
	um->desc.type = C8_NODE_POPUP;
	um->desc.data = um;

	c8_listen(&um->destroy, &xs->events.destroy, unmanaged_destroy);
	c8_listen(&um->associate, &xs->events.associate, unmanaged_associate);
	c8_listen(&um->dissociate, &xs->events.dissociate, unmanaged_dissociate);
	c8_listen(&um->request_configure, &xs->events.request_configure,
		unmanaged_request_configure);
	c8_listen(&um->set_geometry, &xs->events.set_geometry,
		unmanaged_set_geometry);
}

/* Server */

static void new_surface(struct wl_listener *listener, void *data) {
	struct c8_server *server =
		wl_container_of(listener, server, xwayland_new_surface);
	struct wlr_xwayland_surface *xs = data;
	if (xs->override_redirect) {
		unmanaged_create(server, xs);
	} else {
		xview_create(server, xs);
	}
}

/* The root window cursor, shown over X11 windows that don't set one */
void c8_xwayland_set_cursor(struct c8_server *server) {
	if (server->xwayland == NULL) {
		return;
	}
	wlr_xcursor_manager_load(server->xcursor_manager, 1);
	struct wlr_xcursor *xcursor =
		wlr_xcursor_manager_get_xcursor(server->xcursor_manager, "default", 1);
	if (xcursor && xcursor->image_count > 0) {
		struct wlr_xcursor_image *image = xcursor->images[0];
		struct wlr_buffer *buffer =
			c8_buffer_from_argb(image->buffer, image->width, image->height);
		if (buffer) {
			wlr_xwayland_set_cursor(server->xwayland, buffer,
				image->hotspot_x, image->hotspot_y);
			wlr_buffer_drop(buffer);
		}
	}
}

static void pointer_focus(struct wl_listener *listener, void *data) {
	struct c8_server *server =
		wl_container_of(listener, server, xwayland_pointer_focus);
	struct wlr_seat_pointer_focus_change_event *event = data;
	x_raise_pointed(server, event->new_surface);
}

static void ready(struct wl_listener *listener, void *data) {
	struct c8_server *server = wl_container_of(listener, server, xwayland_ready);
	wlr_xwayland_set_seat(server->xwayland, server->seat);
	c8_xwayland_set_cursor(server);
	wlr_log(WLR_INFO, "Xwayland ready on DISPLAY=%s",
		server->xwayland->display_name);
}

void c8_xwayland_init(struct c8_server *server) {
	if (!server->config.xwayland) {
		unsetenv("DISPLAY");
		return;
	}
	/* Lazy: Xwayland only starts when the first X11 client connects */
	server->xwayland = wlr_xwayland_create(server->display,
		server->compositor, true);
	if (server->xwayland == NULL) {
		wlr_log(WLR_ERROR, "Cannot start Xwayland; X11 apps won't run");
		unsetenv("DISPLAY");
		return;
	}
	c8_listen(&server->xwayland_ready, &server->xwayland->events.ready, ready);
	c8_listen(&server->xwayland_new_surface, &server->xwayland->events.new_surface,
		new_surface);
	c8_listen(&server->xwayland_pointer_focus,
		&server->seat->pointer_state.events.focus_change, pointer_focus);
	setenv("DISPLAY", server->xwayland->display_name, true);
}

void c8_xwayland_finish(struct c8_server *server) {
	if (server->xwayland == NULL) {
		return;
	}
	wl_list_remove(&server->xwayland_ready.link);
	wl_list_remove(&server->xwayland_new_surface.link);
	wl_list_remove(&server->xwayland_pointer_focus.link);
	wlr_xwayland_destroy(server->xwayland);
	server->xwayland = NULL;
}

#else

void c8_xwayland_init(struct c8_server *server) {
	unsetenv("DISPLAY");
}

void c8_xwayland_finish(struct c8_server *server) {
}

void c8_xwayland_set_cursor(struct c8_server *server) {
}

#endif
