#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <wlr/types/wlr_output.h>
#include <wlr/util/edges.h>
#include <wlr/util/log.h>
#include <glib.h>
#include "server.h"
#include "stealth.h"

#define SNAP_MIN_WIDTH 320
#define DIVIDER_WIDTH 8
#define BORDER_WIDTH 1 // on the focused app's edge while two share the screen

struct c8_decoration {
	struct wlr_xdg_toplevel_decoration_v1 *decoration;
	struct wl_listener request_mode, destroy;
};

struct c8_view *c8_top_view(struct c8_server *server) {
	struct c8_view *view;
	wl_list_for_each(view, &server->views, link) {
		if (view->mapped && !c8_holo_minimised(view)) {
			return view;
		}
	}
	return NULL;
}

/* A snapped app's width: room left for the other, and no less than its
 * own least (which wins where the area has room for neither) */
static double snap_clamp(double w, int area_width) {
	double max = area_width - SNAP_MIN_WIDTH - DIVIDER_WIDTH;
	if (w > max) {
		w = max;
	}
	return w < SNAP_MIN_WIDTH ? SNAP_MIN_WIDTH : w;
}

static struct c8_view *primary_view(struct c8_server *server) {
	struct c8_view *view;
	wl_list_for_each(view, &server->views, link) {
		if (view->mapped && !view->floating && view != server->snapped) {
			return view;
		}
	}
	return NULL;
}

/* In stealth mode the login, real name, PC name and home folder in a
 * title show as the persona's (a terminal's user@host:~/dir), here, so
 * chrome, the slate bar, the shell and the toplevel lists all get it.
 * Kept per view while the title is the same, so callers may hold it
 * as they held the app's. */
const char *c8_view_title(struct c8_view *view) {
	const char *title = view->impl->get_title(view);
	if (title == NULL || !c8_stealth()) {
		return title;
	}
	if (view->title_gen != view->server->stealth_gen ||
			view->title_from == NULL ||
			strcmp(view->title_from, title) != 0) {
		free(view->title_from);
		g_free(view->title_shown);
		view->title_from = c8_strdup(title);
		view->title_shown = c8_stealth_text(title);
		view->title_gen = view->server->stealth_gen;
	}
	return view->title_shown;
}

void c8_view_title_free(struct c8_view *view) {
	free(view->title_from);
	g_free(view->title_shown);
	view->title_from = view->title_shown = NULL;
}

/* Stealth mode turned on or off: every title told again */
void c8_views_stealth_changed(struct c8_server *server) {
	server->stealth_gen++;
	struct c8_view *view;
	wl_list_for_each(view, &server->views, link) {
		c8_view_props_changed(view);
		c8_chrome_view_restyled(server, view);
	}
}

const char *c8_view_app_id(struct c8_view *view) {
	return view->impl->get_app_id(view);
}

const char *c8_view_label(struct c8_view *view) {
	const char *title = c8_view_title(view);
	return title && title[0] ? title : c8_view_app_id(view);
}

struct c8_view *c8_view_parent(struct c8_view *view) {
	return view->impl->get_parent(view);
}

struct c8_view *c8_view_root(struct c8_view *view) {
	struct c8_view *parent;
	int depth = 0;
	while ((parent = c8_view_parent(view)) && depth++ < 64) {
		view = parent;
	}
	return view;
}

/* xdg-shell */

static struct wlr_surface *xdg_get_surface(struct c8_view *view) {
	return view->toplevel->base->surface;
}

static const char *xdg_get_title(struct c8_view *view) {
	return view->toplevel->title;
}

static const char *xdg_get_app_id(struct c8_view *view) {
	return view->toplevel->app_id;
}

static struct c8_view *xdg_get_parent(struct c8_view *view) {
	struct wlr_xdg_toplevel *parent = view->toplevel->parent;
	return parent ? parent->base->data : NULL;
}

static bool xdg_wants_fullscreen(struct c8_view *view) {
	return view->toplevel->requested.fullscreen;
}

static void xdg_activate(struct c8_view *view, bool activated) {
	if (view->toplevel->base->initialized) {
		wlr_xdg_toplevel_set_activated(view->toplevel, activated);
	}
}

static void xdg_close(struct c8_view *view) {
	wlr_xdg_toplevel_send_close(view->toplevel);
}

static void xdg_configure(struct c8_view *view, struct wlr_box box,
		bool fullscreen) {
	struct wlr_xdg_toplevel *toplevel = view->toplevel;
	struct wlr_box *geo = &toplevel->base->geometry;
	wlr_scene_node_set_position(&view->tree->node, box.x - geo->x,
		box.y - geo->y);
	if (view->geo.width == box.width && view->geo.height == box.height &&
			toplevel->scheduled.fullscreen == fullscreen) {
		view->geo = box;
		return;
	}
	view->geo = box;
	wlr_xdg_toplevel_set_tiled(toplevel, WLR_EDGE_TOP | WLR_EDGE_BOTTOM |
		WLR_EDGE_LEFT | WLR_EDGE_RIGHT);
	wlr_xdg_toplevel_set_maximized(toplevel, !fullscreen);
	wlr_xdg_toplevel_set_fullscreen(toplevel, fullscreen);
	wlr_xdg_toplevel_set_size(toplevel, box.width, box.height);
}

static void xdg_place(struct c8_view *view, struct wlr_box area) {
	struct wlr_box *geo = &view->toplevel->base->geometry;
	int x = area.x + (area.width - geo->width) / 2;
	int y = area.y + (area.height - geo->height) / 2;
	if (y < area.y) {
		y = area.y;
	}
	view->geo = (struct wlr_box){ x, y, geo->width, geo->height };
	wlr_scene_node_set_position(&view->tree->node, x - geo->x, y - geo->y);
}

/* Raise parent's mapped children, least recently focused first, each
 * with its own above it */
static void raise_children(struct c8_server *server, struct c8_view *parent,
		int depth) {
	if (depth > 64) {
		return;
	}
	struct c8_view *view;
	wl_list_for_each_reverse(view, &server->views, link) {
		if (view->mapped && c8_view_parent(view) == parent) {
			wlr_scene_node_raise_to_top(&view->tree->node);
			raise_children(server, view, depth + 1);
		}
	}
}

/* The accent-coloured border along the inside of box's edge, or none. It
 * lies over the app in layers.border, which the pointer hit test skips,
 * so the app keeps its full size and still gets the pointer under it */
static void set_focus_border(struct c8_server *server, const struct wlr_box *box) {
	for (int i = 0; i < 4; i++) {
		wlr_scene_node_set_enabled(&server->focus_border[i]->node, box != NULL);
	}
	if (box == NULL) {
		return;
	}
	float color[4];
	c8_color_to_float(server->config.accent, 1, color);
	int bw = BORDER_WIDTH;
	struct wlr_box sides[4] = {
		{ box->x, box->y, box->width, bw }, // top
		{ box->x, box->y + box->height - bw, box->width, bw }, // bottom
		{ box->x, box->y + bw, bw, box->height - 2 * bw }, // left
		{ box->x + box->width - bw, box->y + bw, bw, box->height - 2 * bw }, // right
	};
	for (int i = 0; i < 4; i++) {
		struct wlr_scene_rect *r = server->focus_border[i];
		wlr_scene_rect_set_color(r, color);
		wlr_scene_node_set_position(&r->node, sides[i].x, sides[i].y);
		wlr_scene_rect_set_size(r, sides[i].width, sides[i].height);
	}
}

/* XR: every window on, at its own size, in its own slot far
 * off the shell's screen; hologram.c says where and glasses.c draws it */
/* The shell's pick is open beside the snapped app */
static bool picking_over(struct c8_server *server) {
	return server->snapped && server->shell.snap.side != 0 &&
		server->shell.snap.view == server->snapped;
}

static void arrange_holograms(struct c8_server *server) {
	c8_tween_stop(server);
	set_focus_border(server, NULL);
	wlr_scene_node_set_enabled(&server->divider->node, false);
	wlr_scene_node_set_enabled(&server->layers.views->node, true);
	wlr_scene_node_set_enabled(&server->layers.unmanaged->node, true);
	server->divider_box = (struct wlr_box){ 0 };
	server->rest_box = (struct wlr_box){ 0 };
	struct c8_view *focused = c8_top_view(server);
	struct c8_view *view;
	wl_list_for_each(view, &server->views, link) {
		if (!view->mapped) {
			continue;
		}
		struct wlr_box box;
		bool fullscreen;
		bool shown = c8_holo_window_box(view, &box, &fullscreen);
		if (shown && view->floating) {
			view->impl->place(view, box);
		} else if (shown) {
			view->impl->configure(view, box, fullscreen);
		}
		wlr_scene_node_set_enabled(&view->tree->node, shown);
		view->impl->activate(view, view == focused && !server->start_visible);
	}
}

void c8_views_arrange(struct c8_server *server) {
	/* The desktop's colour behind the apps: in XR there is
	 * nothing behind them but the room */
	if (server->desktop) {
		wlr_scene_node_set_enabled(&server->desktop->node,
			!c8_xr_active(server));
	}
	if (c8_xr_active(server)) {
		arrange_holograms(server);
		return;
	}
	struct wlr_box area = server->usable;
	struct wlr_box full;
	c8_output_box(server, &full);

	if (server->snapped && !server->snapped->mapped) {
		server->snapped = NULL;
	}
	struct c8_view *primary = primary_view(server);
	struct c8_view *snapped = server->snapped;

	wlr_scene_node_set_enabled(&server->layers.views->node,
		!server->start_visible);
	wlr_scene_node_set_enabled(&server->layers.unmanaged->node,
		!server->start_visible);

	struct wlr_box primary_box = area, snap_box = area;
	server->divider_box = (struct wlr_box){ 0 };
	if (snapped) {
		int w = (int)snap_clamp((int)(area.width * server->snap_fraction),
			area.width);
		snap_box.width = w;
		primary_box.width = area.width - w - DIVIDER_WIDTH;
		if (server->snap_left) {
			primary_box.x = area.x + w + DIVIDER_WIDTH;
		} else {
			snap_box.x = area.x + area.width - w;
		}
		struct wlr_box div = {
			.x = server->snap_left ? area.x + w : area.x + primary_box.width,
			.y = area.y,
			.width = DIVIDER_WIDTH,
			.height = area.height,
		};
		wlr_scene_node_set_position(&server->divider->node, div.x, div.y);
		wlr_scene_rect_set_size(server->divider, div.width, div.height);
		server->divider_box = div;
	}
	wlr_scene_node_set_enabled(&server->divider->node, snapped != NULL);

	/* The focused one of two apps gets a border in the accent colour
	 * drawn along its edge, once they have stopped moving */
	struct c8_view *focused = c8_top_view(server);
	struct c8_view *focused_root = focused ? c8_view_root(focused) : NULL;
	/* The shell's pick over the rest of the screen: what would be
	 * there stays out of sight behind it, so it doesn't show past the
	 * pick while that follows the split */
	bool picking = picking_over(server);
	struct c8_view *tiled[2];
	struct wlr_box tiled_box[2];
	int ntiled = 0;
	if (snapped) {
		tiled[ntiled] = snapped;
		tiled_box[ntiled++] = snap_box;
	}
	if (primary && primary != snapped && !primary->floating) {
		bool fs = primary->impl->wants_fullscreen(primary) && !snapped;
		tiled[ntiled] = primary;
		tiled_box[ntiled++] = fs ? full : primary_box;
	}
	if (ntiled == 2 && focused_root == tiled[1]) { // its cover goes over
		struct c8_view *v = tiled[0];
		struct wlr_box b = tiled_box[0];
		tiled[0] = tiled[1];
		tiled_box[0] = tiled_box[1];
		tiled[1] = v;
		tiled_box[1] = b;
	}
	bool moving = c8_tween_layout(server, tiled, tiled_box, ntiled,
		&server->divider_box, snapped != NULL, picking ? primary : NULL);
	set_focus_border(server,
		snapped == NULL || server->start_visible || moving ? NULL :
		focused_root == snapped ? &snap_box :
		focused_root == primary ? &primary_box : NULL);
	struct c8_view *view;
	wl_list_for_each(view, &server->views, link) {
		if (!view->mapped) {
			continue;
		}
		bool visible;
		if (view->floating) {
			struct c8_view *root = c8_view_root(view);
			visible = root == view || root == primary || root == snapped;
			if (visible) {
				view->impl->place(view, area);
			}
		} else if (view == snapped) {
			visible = true;
			view->impl->configure(view, snap_box, false);
		} else if (view == primary) {
			visible = !picking;
			bool fs = view->impl->wants_fullscreen(view) && !snapped;
			view->impl->configure(view, fs ? full : primary_box, fs);
		} else {
			visible = false;
		}
		if (view == server->chrome.view && server->chrome.card->node.enabled) {
			visible = false; // being carried by its title bar
		}
		wlr_scene_node_set_enabled(&view->tree->node, visible);
		view->impl->activate(view, view == focused && !server->start_visible);
	}

	/* Stack most recently focused on top, an app's windows together and
	 * dialogs above what they belong to, so focusing the main window
	 * doesn't bury them: raising a group again for each more recent
	 * member leaves it where its most recent one is */
	wl_list_for_each_reverse(view, &server->views, link) {
		if (view->mapped) {
			struct c8_view *root = c8_view_root(view);
			wlr_scene_node_raise_to_top(&root->tree->node);
			raise_children(server, root, 0);
		}
	}
	wlr_scene_node_raise_to_top(&server->divider->node);
	server->rest_box = snapped ? primary_box : (struct wlr_box){ 0 };
	c8_shell_snap_changed(server);
	if (!picking && primary && primary != snapped &&
			picking_over(server)) {
		/* The pick has just been offered */
		c8_tween_hide(server, primary);
		wlr_scene_node_set_enabled(&primary->tree->node, false);
	}
	c8_tween_restack(server);
	/* What's under the pointer may have changed (Alt+Tab brought
	 * another app forward): a click or scroll before it moves must
	 * reach that one, not the one it was last over. Not off the
	 * shell's own surfaces: a toast swiped away keeps the pointer it
	 * slid out from under till the swipe ends. Nor while the chrome
	 * holds the pointer (the divider, an app carried): its motion is
	 * what arranged, and asking again went round till the stack ran
	 * out (2026-12-06, dragging the divider) */
	struct wlr_surface *over = server->seat->pointer_state.focused_surface;
	if (!c8_chrome_grabbing(server) && (over == NULL ||
			!c8_shell_is_client(server,
			wl_resource_get_client(over->resource)))) {
		c8_cursor_rebase(server);
	}
}

void c8_view_keyboard_enter(struct c8_server *server, struct wlr_surface *surface) {
	struct wlr_seat *seat = server->seat;
	/* Locked, the keyboard stays with the locker whoever asks */
	if (c8_locked(server) && !c8_lock_owns_surface(server, surface)) {
		surface = c8_lock_keyboard_surface(server);
	}
	if (seat->keyboard_state.focused_surface == surface) {
		return;
	}
	if (surface == NULL) {
		wlr_seat_keyboard_notify_clear_focus(seat);
		c8_pointer_constraint_update(server, NULL);
		c8_im_focus(server, NULL);
		return;
	}
	struct wlr_keyboard *kb = wlr_seat_get_keyboard(seat);
	if (kb) {
		wlr_seat_keyboard_notify_enter(seat, surface, kb->keycodes,
			kb->num_keycodes, &kb->modifiers);
	} else {
		wlr_seat_keyboard_notify_enter(seat, surface, NULL, 0, NULL);
	}
	/* Constraints only hold while their app has the keyboard */
	c8_pointer_constraint_update(server, seat->pointer_state.focused_surface);
	c8_im_focus(server, surface);
}

void c8_focus_restore(struct c8_server *server) {
	if (c8_locked(server)) {
		c8_view_keyboard_enter(server, c8_lock_keyboard_surface(server));
		return;
	}
	if (server->focused_layer) {
		c8_view_keyboard_enter(server, server->focused_layer->surface);
		return;
	}
	struct wlr_surface *shell = c8_shell_keyboard_surface(server);
	if (shell || server->start_visible) {
		c8_view_keyboard_enter(server, shell);
		c8_views_arrange(server);
		return;
	}
	struct c8_view *top = c8_top_view(server);
	if (top) {
		c8_focus_view(top);
	} else {
		c8_view_keyboard_enter(server, NULL);
	}
}

void c8_view_raise(struct c8_view *view) {
	if (view != c8_top_view(view->server)) {
		c8_focus_view(view);
	}
}

void c8_view_activate(struct c8_view *view) {
	c8_focus_view(view);
	c8_holo_summon(view);
}

void c8_focus_view(struct c8_view *view) {
	struct c8_server *server = view->server;
	if (!view->mapped) {
		return;
	}
	c8_holo_restore(view); // picked again: no longer minimised
	/* Activation tokens from input older than this are stale: an app
	 * refocusing itself when it loses focus must not win */
	server->focus_serial = wl_display_get_serial(server->display);
	wl_list_remove(&view->link);
	wl_list_insert(&server->views, &view->link);
	/* A dialog brings the window it belongs to along, right behind it,
	 * so that one is the app on screen and the dialog shows over it */
	struct c8_view *behind = view, *up = view, *parent;
	int depth = 0;
	while ((parent = c8_view_parent(up)) && depth++ < 64) {
		up = parent;
		if (parent->mapped) {
			wl_list_remove(&parent->link);
			wl_list_insert(&behind->link, &parent->link);
			behind = parent;
		}
	}
	c8_shell_focus_changed(server);
	if (server->start_visible) {
		/* Hiding start restores focus to the view we just raised */
		c8_start_show(server, false);
		return;
	}
	c8_views_arrange(server);
	if (server->focused_layer == NULL) {
		struct wlr_surface *shell = c8_shell_keyboard_surface(server);
		c8_view_keyboard_enter(server,
			shell ? shell : view->impl->get_surface(view));
	}
}

void c8_view_close(struct c8_view *view) {
	view->impl->close(view);
}

void c8_view_snap(struct c8_server *server, int side) {
	struct c8_view *top = c8_top_view(server);
	if (side == 0) {
		server->snapped = NULL;
	} else if (top && !top->floating) {
		/* Both sides filled and the big one asks for a side: the two
		 * swap places, the one that was snapped takes the rest. It
		 * has to be the most recent of the others to be the primary */
		struct c8_view *old = server->snapped;
		if (old && old != top && old->mapped &&
				top == primary_view(server)) {
			wl_list_remove(&old->link);
			wl_list_insert(&top->link, &old->link);
		}
		server->snapped = top;
		server->snap_left = side < 0;
	}
	c8_views_arrange(server);
}

/* Snap view to a side (-1 left, 1 right) taking fraction of the width
 * (0 keeps the current split), or with side 0 give it the whole screen. */
void c8_view_snap_to(struct c8_view *view, int side, double fraction) {
	struct c8_server *server = view->server;
	if (view->floating || !view->mapped) {
		return;
	}
	if (side == 0) {
		/* Full screen on its own: the other side goes away */
		server->snapped = NULL;
	} else {
		server->snapped = view;
		server->snap_left = side < 0;
		if (fraction > 0) {
			server->snap_fraction = fraction;
		}
	}
	c8_focus_view(view);
	c8_views_arrange(server);
}

/* Set the snapped side's width from a pointer position on the divider */
void c8_view_set_split(struct c8_server *server, double lx) {
	struct wlr_box area = server->usable;
	if (server->snapped == NULL || area.width <= 0) {
		return;
	}
	double w = server->snap_left ? lx - area.x : area.x + area.width - lx;
	w = snap_clamp(w, area.width);
	server->snap_fraction = w / area.width;
	c8_views_arrange(server);
}

void c8_view_split_step(struct c8_server *server, int direction) {
	struct c8_view *snapped = server->snapped;
	struct c8_view *primary = primary_view(server);
	if (snapped == NULL || primary == NULL) {
		return;
	}
	/* The split as a share of the width from the left, on the quarter
	 * nearest to where it is, then one quarter along */
	double split = server->snap_left ? server->snap_fraction :
		1 - server->snap_fraction;
	int quarters = (int)(split * 4 + 0.5) + direction;
	struct c8_view *left = server->snap_left ? snapped : primary;
	struct c8_view *right = server->snap_left ? primary : snapped;
	if (quarters >= 4) {
		c8_view_snap_to(left, 0, 0); // the left app has it all
	} else if (quarters <= 0) {
		c8_view_snap_to(right, 0, 0);
	} else {
		split = quarters / 4.0;
		server->snap_fraction = server->snap_left ? split : 1 - split;
		c8_views_arrange(server);
	}
}

int c8_view_snap_min_width(void) {
	return SNAP_MIN_WIDTH;
}

/* Out of the way: the next app comes forward, or Start with none left.
 * In XR it's put away for real, as an icon over the charms bar
 * (hologram.c) until it's picked again; flat there is nothing to put it
 * away from, so it only goes behind the others (what a window list
 * asking for it gets: the title bar has no such button) */
void c8_view_minimize(struct c8_view *view) {
	struct c8_server *server = view->server;
	if (server->snapped == view) {
		server->snapped = NULL;
	}
	/* Its dialogs go with it, or the first would bring it straight back */
	struct c8_view *root = c8_view_root(view), *v, *tmp;
	struct wl_list group;
	wl_list_init(&group);
	wl_list_for_each_safe(v, tmp, &server->views, link) {
		if (v->mapped && c8_view_root(v) == root) {
			wl_list_remove(&v->link);
			wl_list_insert(group.prev, &v->link);
		}
	}
	wl_list_insert_list(server->views.prev, &group);
	c8_holo_minimise(root);
	struct c8_view *top = c8_top_view(server);
	if (top == NULL || c8_view_root(top) == root) {
		c8_start_show(server, true);
		return;
	}
	c8_focus_view(top);
}

/* The window of view's app (it and its dialogs) last used: what to
 * bring back when the app is picked in the switcher */
struct c8_view *c8_view_group_latest(struct c8_view *view) {
	struct c8_view *root = c8_view_root(view), *v;
	wl_list_for_each(v, &view->server->views, link) {
		if (v->mapped && c8_view_root(v) == root) {
			return v;
		}
	}
	return view;
}

static bool same_app(struct c8_view *a, struct c8_view *b) {
	if (c8_view_root(a) == c8_view_root(b)) {
		return true;
	}
	const char *ia = c8_view_app_id(a), *ib = c8_view_app_id(b);
	return ia && ib && ia[0] && strcmp(ia, ib) == 0;
}

/* Super+`: the next window of the app in front, dialogs included.
 * Forward brings up the one least recently used, so pressing it again
 * and again goes round them all; back sends the front one behind the
 * app's others, which goes round the other way. */
void c8_view_cycle_app(struct c8_server *server, int direction) {
	struct c8_view *top = c8_top_view(server);
	if (top == NULL || server->start_visible) {
		return;
	}
	struct c8_view *v, *last = NULL, *next = NULL;
	wl_list_for_each(v, &server->views, link) {
		if (v != top && v->mapped && same_app(v, top)) {
			if (next == NULL) {
				next = v;
			}
			last = v;
		}
	}
	if (last == NULL) {
		return;
	}
	if (direction < 0) {
		wl_list_remove(&top->link);
		wl_list_insert(&last->link, &top->link);
		c8_view_activate(next);
	} else {
		c8_view_activate(last);
	}
}

/* The full-screen or snapped app at (lx, ly), if any */
struct c8_view *c8_tiled_view_at(struct c8_server *server, double lx, double ly) {
	if (server->start_visible) {
		return NULL;
	}
	struct c8_view *candidates[] = { primary_view(server), server->snapped };
	for (size_t i = 0; i < 2; i++) {
		struct c8_view *view = candidates[i];
		if (view && view->mapped &&
				wlr_box_contains_point(&view->geo, lx, ly)) {
			return view;
		}
	}
	return NULL;
}

static bool wants_floating(struct wlr_xdg_toplevel *toplevel) {
	struct wlr_xdg_toplevel_state *s = &toplevel->current;
	return toplevel->parent != NULL ||
		(s->min_width > 0 && s->min_width == s->max_width &&
		 s->min_height > 0 && s->min_height == s->max_height);
}

/* Shared by xdg and X11 views; the caller sets view->floating first */
void c8_view_mapped(struct c8_view *view) {
	struct c8_server *server = view->server;
	view->mapped = true;
	wl_list_insert(&server->views, &view->link);
	c8_shell_window_mapped(view);
	c8_toplevel_mapped(view);
	c8_focus_view(view);
	c8_holo_view_mapped(view);
}

void c8_view_unmapped(struct c8_view *view) {
	struct c8_server *server = view->server;
	c8_xr_window_closing(view); // its picture, while there is one
	view->mapped = false;
	view->geo = (struct wlr_box){ 0 };
	c8_holo_view_gone(view);
	c8_tween_view_gone(view);
	wl_list_remove(&view->link);
	c8_shell_window_unmapped(view);
	c8_toplevel_unmapped(view);
	c8_shell_focus_changed(server);
	if (server->snapped == view) {
		server->snapped = NULL;
	}
	c8_chrome_view_gone(server, view);
	if (c8_top_view(server) == NULL && !server->start_visible) {
		c8_start_show(server, true);
	} else {
		c8_focus_restore(server);
	}
	c8_cursor_rebase(server);
}

static void view_map(struct wl_listener *listener, void *data) {
	struct c8_view *view = wl_container_of(listener, view, map);
	view->floating = wants_floating(view->toplevel);
	c8_view_mapped(view);
}

static void view_unmap(struct wl_listener *listener, void *data) {
	struct c8_view *view = wl_container_of(listener, view, unmap);
	c8_view_unmapped(view);
}

static void view_commit(struct wl_listener *listener, void *data) {
	struct c8_view *view = wl_container_of(listener, view, commit);
	struct wlr_xdg_toplevel *toplevel = view->toplevel;
	if (toplevel->base->initial_commit) {
		wlr_xdg_toplevel_set_wm_capabilities(toplevel,
			WLR_XDG_TOPLEVEL_WM_CAPABILITIES_FULLSCREEN);
		if (wants_floating(toplevel)) {
			wlr_xdg_toplevel_set_size(toplevel, 0, 0);
		} else {
			struct wlr_box area = view->server->usable;
			wlr_xdg_toplevel_set_tiled(toplevel, WLR_EDGE_TOP |
				WLR_EDGE_BOTTOM | WLR_EDGE_LEFT | WLR_EDGE_RIGHT);
			wlr_xdg_toplevel_set_maximized(toplevel, true);
			wlr_xdg_toplevel_set_size(toplevel, area.width, area.height);
		}
		if (view->decoration) {
			wlr_xdg_toplevel_decoration_v1_set_mode(view->decoration,
				WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
		}
		return;
	}
	if (view->mapped && view->floating) {
		struct wlr_box *geo = &toplevel->base->geometry;
		if (geo->width != view->geo.width || geo->height != view->geo.height) {
			c8_views_arrange(view->server);
		}
	}
}

static void view_destroy(struct wl_listener *listener, void *data) {
	struct c8_view *view = wl_container_of(listener, view, destroy);
	view->toplevel->base->data = NULL;
	wl_list_remove(&view->map.link);
	wl_list_remove(&view->unmap.link);
	wl_list_remove(&view->commit.link);
	wl_list_remove(&view->destroy.link);
	wl_list_remove(&view->request_fullscreen.link);
	wl_list_remove(&view->request_maximize.link);
	wl_list_remove(&view->request_move.link);
	wl_list_remove(&view->request_resize.link);
	wl_list_remove(&view->set_title.link);
	wl_list_remove(&view->set_app_id.link);
	c8_view_title_free(view);
	free(view);
}

static void view_request_fullscreen(struct wl_listener *listener, void *data) {
	struct c8_view *view = wl_container_of(listener, view, request_fullscreen);
	view->holo.theatre_ask = 0; // the app's say again
	if (view->toplevel->base->initialized) {
		view->geo = (struct wlr_box){ 0 };
		c8_views_arrange(view->server);
		if (!view->mapped) {
			wlr_xdg_surface_schedule_configure(view->toplevel->base);
		}
	}
}

static void view_request_noop(struct wl_listener *listener, void *data) {
	/* Every window is maximized already; the protocol still requires a
	 * configure in reply to maximize requests. */
	struct c8_view *view = wl_container_of(listener, view, request_maximize);
	if (view->toplevel->base->initialized) {
		wlr_xdg_surface_schedule_configure(view->toplevel->base);
	}
}

static void view_request_ignore(struct wl_listener *listener, void *data) {
}

void c8_view_props_changed(struct c8_view *view) {
	c8_shell_window_changed(view);
	c8_toplevel_changed(view);
}

static void view_set_title(struct wl_listener *listener, void *data) {
	struct c8_view *view = wl_container_of(listener, view, set_title);
	c8_view_props_changed(view);
}

static void view_set_app_id(struct wl_listener *listener, void *data) {
	struct c8_view *view = wl_container_of(listener, view, set_app_id);
	c8_view_props_changed(view);
}

static const struct c8_view_impl xdg_impl = {
	.get_surface = xdg_get_surface,
	.get_title = xdg_get_title,
	.get_app_id = xdg_get_app_id,
	.get_parent = xdg_get_parent,
	.wants_fullscreen = xdg_wants_fullscreen,
	.configure = xdg_configure,
	.place = xdg_place,
	.activate = xdg_activate,
	.close = xdg_close,
};

static void new_toplevel(struct wl_listener *listener, void *data) {
	struct c8_server *server = wl_container_of(listener, server, new_toplevel);
	struct wlr_xdg_toplevel *toplevel = data;

	struct c8_view *view = calloc(1, sizeof(*view));
	view->server = server;
	view->impl = &xdg_impl;
	view->toplevel = toplevel;
	view->desc.type = C8_NODE_VIEW;
	view->desc.data = view;
	view->tree = wlr_scene_xdg_surface_create(server->layers.views, toplevel->base);
	view->tree->node.data = &view->desc;
	toplevel->base->data = view;
	toplevel->base->surface->data = view->tree;
	wl_list_init(&view->link);

	c8_listen(&view->map, &toplevel->base->surface->events.map, view_map);
	c8_listen(&view->unmap, &toplevel->base->surface->events.unmap, view_unmap);
	c8_listen(&view->commit, &toplevel->base->surface->events.commit,
		view_commit);
	c8_listen(&view->destroy, &toplevel->events.destroy, view_destroy);
	c8_listen(&view->request_fullscreen, &toplevel->events.request_fullscreen,
		view_request_fullscreen);
	c8_listen(&view->request_maximize, &toplevel->events.request_maximize,
		view_request_noop);
	c8_listen(&view->request_move, &toplevel->events.request_move,
		view_request_ignore);
	c8_listen(&view->request_resize, &toplevel->events.request_resize,
		view_request_ignore);
	c8_listen(&view->set_title, &toplevel->events.set_title, view_set_title);
	c8_listen(&view->set_app_id, &toplevel->events.set_app_id, view_set_app_id);
}

static void popup_unconstrain(struct wlr_xdg_popup *popup) {
	struct wlr_surface *surface = popup->parent;
	while (surface) {
		struct wlr_xdg_surface *xdg = wlr_xdg_surface_try_from_wlr_surface(surface);
		if (xdg == NULL || xdg->role != WLR_XDG_SURFACE_ROLE_POPUP ||
				xdg->popup->parent == NULL) {
			break;
		}
		surface = xdg->popup->parent;
	}
	struct wlr_scene_tree *root = surface ? surface->data : NULL;
	if (root == NULL) {
		return;
	}
	struct c8_node_desc *desc = root->node.data;
	struct c8_server *server = NULL;
	if (desc && desc->type == C8_NODE_VIEW) {
		server = ((struct c8_view *)desc->data)->server;
	} else if (desc && desc->type == C8_NODE_LAYER) {
		server = ((struct c8_layer *)desc->data)->server;
	}
	if (server == NULL) {
		return;
	}
	struct wlr_box out;
	if (!(desc->type == C8_NODE_VIEW &&
			c8_holo_area(desc->data, &out))) {
		c8_output_box(server, &out);
	}
	int lx, ly;
	wlr_scene_node_coords(&root->node, &lx, &ly);
	struct wlr_box box = { out.x - lx, out.y - ly, out.width, out.height };
	wlr_xdg_popup_unconstrain_from_box(popup, &box);
}

static void popup_commit(struct wl_listener *listener, void *data) {
	struct c8_popup *popup = wl_container_of(listener, popup, commit);
	if (popup->popup->base->initial_commit) {
		popup_unconstrain(popup->popup);
	}
}

/* A popup that changes size asks to be placed again (Firefox's add-on
 * prompt grows out of the small download one); without fitting it to the
 * screen again it keeps the old side and runs off the edge. */
static void popup_reposition(struct wl_listener *listener, void *data) {
	struct c8_popup *popup = wl_container_of(listener, popup, reposition);
	popup_unconstrain(popup->popup);
}

static void popup_destroy(struct wl_listener *listener, void *data) {
	struct c8_popup *popup = wl_container_of(listener, popup, destroy);
	wl_list_remove(&popup->commit.link);
	wl_list_remove(&popup->reposition.link);
	wl_list_remove(&popup->destroy.link);
	free(popup);
}

static void new_popup(struct wl_listener *listener, void *data) {
	struct wlr_xdg_popup *xdg_popup = data;
	/* Popups of layer surfaces get a parent later and are set up by the
	 * layer shell code. */
	if (xdg_popup->parent == NULL) {
		return;
	}
	struct wlr_xdg_surface *parent =
		wlr_xdg_surface_try_from_wlr_surface(xdg_popup->parent);
	if (parent == NULL || xdg_popup->parent->data == NULL) {
		return;
	}
	struct wlr_scene_tree *parent_tree = xdg_popup->parent->data;
	struct wlr_scene_tree *tree =
		wlr_scene_xdg_surface_create(parent_tree, xdg_popup->base);
	tree->node.data = parent_tree->node.data;
	xdg_popup->base->surface->data = tree;

	struct c8_popup *popup = calloc(1, sizeof(*popup));
	popup->popup = xdg_popup;
	c8_listen(&popup->commit, &xdg_popup->base->surface->events.commit,
		popup_commit);
	c8_listen(&popup->reposition, &xdg_popup->events.reposition,
		popup_reposition);
	c8_listen(&popup->destroy, &xdg_popup->events.destroy, popup_destroy);
}

static void decoration_apply(struct c8_decoration *deco) {
	if (deco->decoration->toplevel->base->initialized) {
		wlr_xdg_toplevel_decoration_v1_set_mode(deco->decoration,
			WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
	}
}

static void decoration_request_mode(struct wl_listener *listener, void *data) {
	struct c8_decoration *deco = wl_container_of(listener, deco, request_mode);
	decoration_apply(deco);
}

static void decoration_destroy(struct wl_listener *listener, void *data) {
	struct c8_decoration *deco = wl_container_of(listener, deco, destroy);
	struct c8_view *view = deco->decoration->toplevel->base->data;
	if (view) {
		view->decoration = NULL;
	}
	wl_list_remove(&deco->request_mode.link);
	wl_list_remove(&deco->destroy.link);
	free(deco);
}

static void new_decoration(struct wl_listener *listener, void *data) {
	struct wlr_xdg_toplevel_decoration_v1 *decoration = data;
	struct c8_decoration *deco = calloc(1, sizeof(*deco));
	deco->decoration = decoration;
	struct c8_view *view = decoration->toplevel->base->data;
	if (view) {
		view->decoration = decoration;
	}
	c8_listen(&deco->request_mode, &decoration->events.request_mode,
		decoration_request_mode);
	c8_listen(&deco->destroy, &decoration->events.destroy, decoration_destroy);
	decoration_apply(deco);
}

void c8_view_finish(struct c8_server *server) {
	wl_list_remove(&server->new_toplevel.link);
	wl_list_remove(&server->new_popup.link);
	wl_list_remove(&server->new_decoration.link);
}

void c8_view_init(struct c8_server *server) {
	wl_list_init(&server->views);
	server->snap_fraction = 1.0 / 3;
	server->xdg_shell = wlr_xdg_shell_create(server->display, 6);
	c8_listen(&server->new_toplevel, &server->xdg_shell->events.new_toplevel,
		new_toplevel);
	c8_listen(&server->new_popup, &server->xdg_shell->events.new_popup,
		new_popup);

	server->decoration_manager =
		wlr_xdg_decoration_manager_v1_create(server->display);
	c8_listen(&server->new_decoration, &server->decoration_manager->events.new_toplevel_decoration,
		new_decoration);
	/* GTK3 ignores xdg-decoration but drops its own title bar, shadow
	 * and resize border when this one says the server draws them. */
	server->kde_decoration_manager =
		wlr_server_decoration_manager_create(server->display);
	wlr_server_decoration_manager_set_default_mode(
		server->kde_decoration_manager,
		WLR_SERVER_DECORATION_MANAGER_MODE_SERVER);

	float black[4] = { 0, 0, 0, 1 };
	server->divider = wlr_scene_rect_create(server->layers.views, 0, 0, black);
	server->divider->node.data = &c8_ui_desc;
	wlr_scene_node_set_enabled(&server->divider->node, false);
	c8_tween_init(server);
	for (int i = 0; i < 4; i++) {
		server->focus_border[i] =
			wlr_scene_rect_create(server->layers.border, 0, 0, black);
		server->focus_border[i]->node.data = &c8_ui_desc;
		wlr_scene_node_set_enabled(&server->focus_border[i]->node, false);
	}
}
