/*
 * The shell client (c8-shell) and the private protocol it uses.
 *
 * Start, all apps, the charms, flyouts, switcher and launch splash are drawn
 * by c8-shell. The compositor starts it over a socket pair, only that
 * connection sees c8_shell_v1, and it is started again if it exits. The
 * compositor keeps the Start mode (whether Start covers the apps) and
 * places the shell's surfaces. Live tiles are all the shell's: their
 * content reaches it over D-Bus.
 */
#define _GNU_SOURCE
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <wlr/types/wlr_compositor.h>
#include <wlr/util/log.h>
#include "cont8nuum-shell-v1-protocol.h"
#include "server.h"

#define SHELL_PROGRAM "c8-shell"
#define SHELL_VERSION 1
#define RESPAWN_MS 500
#define RESPAWN_MAX_MS 30000
/* Ran at least this long: an exit after that is a crash, not a loop */
#define SHELL_STABLE_MS 10000
#define START_REVEAL_MS 100 // longest Start stays hidden waiting to be drawn
/* Start's closing sweep in the glasses: the shell's 280, and room for
 * its first frames being late (the tiles are clear by then anyway; cut
 * off sooner, they vanished mid-sweep) */
#define START_CLOSE_MS 450

static const struct c8_shell_v1_interface shell_impl;
static const struct c8_shell_surface_v1_interface surface_impl;
static const struct c8_shell_window_v1_interface window_impl;

bool c8_shell_is_client(struct c8_server *server,
		const struct wl_client *client) {
	return client != NULL && client == server->shell.client;
}

static struct wlr_scene_tree *role_layer(struct c8_server *server,
		enum c8_shell_role role) {
	switch (role) {
	case C8_SHELL_START:
		return server->layers.start;
	case C8_SHELL_PANEL:
	case C8_SHELL_OSD:
	case C8_SHELL_BAR:
		return server->layers.shell;
	case C8_SHELL_SPLASH:
		break;
	}
	return server->layers.splash;
}

/* The desktop: the background colour behind the apps */

static void desktop_update(struct c8_server *server) {
	struct wlr_box out;
	c8_output_box(server, &out);
	float color[4];
	c8_color_to_float(server->config.background, 1, color);
	wlr_scene_rect_set_color(server->desktop, color);
	wlr_scene_rect_set_size(server->desktop, out.width, out.height);
	wlr_scene_node_set_position(&server->desktop->node, out.x, out.y);
}

/* Shell surfaces */

static struct c8_shell_surface *surface_from_resource(
		struct wl_resource *resource) {
	return wl_resource_get_user_data(resource);
}

static bool surface_shown(struct c8_shell_surface *ss) {
	return ss && ss->surface && ss->surface->mapped;
}

/* Tells the shell a surface's size, when it's another than it has */
static void send_configure(struct c8_shell_surface *ss, int w, int h) {
	if (w == ss->configured_w && h == ss->configured_h) {
		return;
	}
	ss->configured_w = w;
	ss->configured_h = h;
	c8_shell_surface_v1_send_configure(ss->resource, w, h);
}

/* The roles the shell gives a rect of its own (the rest fill the screen) */
static bool role_has_rect(enum c8_shell_role role) {
	return role == C8_SHELL_PANEL || role == C8_SHELL_OSD ||
		role == C8_SHELL_BAR;
}

static void configure_full(struct c8_shell_surface *ss) {
	struct wlr_box out;
	if (ss->role != C8_SHELL_SPLASH ||
			!c8_holo_splash_box(ss->server, &out)) {
		c8_output_box(ss->server, &out);
	}
	wlr_scene_node_set_position(&ss->tree->node, out.x, out.y);
	if (out.width > 0 && out.height > 0) {
		send_configure(ss, out.width, out.height);
	}
}

static void place_panel(struct c8_shell_surface *ss) {
	struct wlr_box out;
	if (ss->role == C8_SHELL_BAR) {
		/* In a slot of its own: only its size is the shell's */
		if (c8_holo_bar_box(ss->server, &out)) {
			wlr_scene_node_set_position(&ss->tree->node, out.x, out.y);
		}
		return;
	}
	/* In XR toasts and the level box go on the HUD, which
	 * follows the bottom of the view (hologram.c), not the shell's
	 * screen; it's as big, so the shell's rect means the same there */
	if (ss->role != C8_SHELL_OSD || !c8_holo_hud_box(ss->server, &out)) {
		c8_output_box(ss->server, &out);
	}
	wlr_scene_node_set_position(&ss->tree->node, out.x + ss->rect.x,
		out.y + ss->rect.y);
}

/* The pointer is over the shell surface's rect */
static bool now_under_pointer(struct c8_shell_surface *ss) {
	double x, y;
	int lx, ly;
	wlr_scene_node_coords(&ss->tree->node, &lx, &ly);
	x = ss->server->cursor->x - lx;
	y = ss->server->cursor->y - ly;
	return x >= 0 && y >= 0 && x < ss->rect.width && y < ss->rect.height;
}

static void focus_update(struct c8_server *server) {
	c8_focus_restore(server);
	c8_cursor_rebase(server);
}

static void start_reveal(struct c8_server *server) {
	struct c8_shell *shell = &server->shell;
	if (!shell->start_reveal_pending) {
		return;
	}
	shell->start_reveal_pending = false;
	wl_event_source_timer_update(shell->start_reveal, 0);
	if (server->start_visible) {
		wlr_scene_node_set_enabled(&server->layers.start->node, true);
	}
}

/* Start's closing sweep is done */
static int start_close_timeout(void *data) {
	struct c8_server *server = data;
	if (!server->start_visible) {
		wlr_scene_node_set_enabled(&server->layers.start->node, false);
		c8_holo_start_hidden(server);
	}
	return 0;
}

static int start_reveal_timeout(void *data) {
	start_reveal(data); // the shell is slow: show what it has
	return 0;
}

static void role_commit(struct wlr_surface *surface) {
	struct c8_shell_surface *ss = surface->role_resource ?
		surface_from_resource(surface->role_resource) : NULL;
	if (ss == NULL) {
		return;
	}
	struct c8_server *server = ss->server;
	if (ss == server->shell.start) {
		start_reveal(server);
	}
	bool moved = false;
	if (ss->rect_pending) {
		ss->rect_pending = false;
		moved = ss->rect.x != ss->pending_rect.x ||
			ss->rect.y != ss->pending_rect.y;
		ss->rect = ss->pending_rect;
		place_panel(ss);
		send_configure(ss, ss->rect.width, ss->rect.height);
	}
	bool changed = false;
	if (wlr_surface_has_buffer(surface)) {
		if (!surface->mapped) {
			wlr_surface_map(surface);
			changed = true;
		}
	} else if (surface->mapped) {
		wlr_surface_unmap(surface);
		changed = true;
	}
	if (changed) {
		if (ss->role == C8_SHELL_SPLASH) {
			c8_holo_splash_shown(server, surface->mapped);
			if (surface->mapped && c8_xr_active(server) &&
					server->start_visible) {
				/* Flat, the splash covers Start; in the glasses it's a
				 * slate of its own, so Start goes now */
				c8_start_show(server, false);
			}
		}
		if (ss->role == C8_SHELL_OSD) {
			wlr_scene_node_raise_to_top(&ss->tree->node);
		} else if (ss->role == C8_SHELL_PANEL) {
			wlr_scene_node_raise_to_top(&ss->tree->node);
			if (surface->mapped) {
				c8_chrome_hide(server);
			}
		}
		focus_update(server);
	} else if (moved && surface->mapped && now_under_pointer(ss)) {
		/* A toast slides in by moving: under a still pointer it must
		 * get the click, not what was there before. One moving away
		 * keeps the pointer till it moves: a toast swiped off on the
		 * touchpad slides out from under it and must still get the
		 * rest of the swipe, and its end */
		c8_cursor_rebase(server);
	}
}

static void surface_destroy(struct c8_shell_surface *ss) {
	struct c8_server *server = ss->server;
	bool shown = surface_shown(ss);
	if (ss == server->shell.start) {
		server->shell.start = NULL;
	}
	wl_list_remove(&ss->surface_destroy.link);
	wl_list_remove(&ss->link);
	if (!server->terminating) {
		wlr_scene_node_destroy(&ss->tree->node);
	}
	wl_resource_set_user_data(ss->resource, NULL);
	free(ss);
	if (shown && !server->terminating) {
		focus_update(server);
	}
}

static void role_destroy(struct wlr_surface *surface) {
	struct c8_shell_surface *ss = surface->role_resource ?
		surface_from_resource(surface->role_resource) : NULL;
	if (ss) {
		surface_destroy(ss);
	}
}

static const struct wlr_surface_role shell_role = {
	.name = "c8_shell_surface",
	.commit = role_commit,
	.destroy = role_destroy,
};

static void handle_surface_gone(struct wl_listener *listener, void *data) {
	struct c8_shell_surface *ss =
		wl_container_of(listener, ss, surface_destroy);
	surface_destroy(ss);
}

static void surface_resource_destroy(struct wl_resource *resource) {
	struct c8_shell_surface *ss = surface_from_resource(resource);
	if (ss) {
		surface_destroy(ss);
	}
}

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

static void surface_set_rect(struct wl_client *client,
		struct wl_resource *resource, int32_t x, int32_t y, int32_t width,
		int32_t height) {
	struct c8_shell_surface *ss = surface_from_resource(resource);
	if (ss == NULL || !role_has_rect(ss->role)) {
		return;
	}
	ss->pending_rect = (struct wlr_box){ x, y, width, height };
	ss->rect_pending = true;
}

static void surface_grab_keyboard(struct wl_client *client,
		struct wl_resource *resource, uint32_t grab) {
	struct c8_shell_surface *ss = surface_from_resource(resource);
	if (ss == NULL || ss->grab_keyboard == (grab != 0)) {
		return;
	}
	ss->grab_keyboard = grab != 0;
	if (ss->role == C8_SHELL_BAR) {
		c8_holo_bar_grab(ss->server, ss->grab_keyboard);
	}
	focus_update(ss->server);
}

static const struct c8_shell_surface_v1_interface surface_impl = {
	.destroy = surface_handle_destroy,
	.set_rect = surface_set_rect,
	.grab_keyboard = surface_grab_keyboard,
};

/* Windows */

static void window_resource_destroy(struct wl_resource *resource) {
	struct c8_view *view = wl_resource_get_user_data(resource);
	if (view) {
		view->shell_window = NULL;
	}
}

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

static void window_activate(struct wl_client *client,
		struct wl_resource *resource) {
	struct c8_view *view = wl_resource_get_user_data(resource);
	if (view) {
		/* The app, as it was left: its open dialog if it has one */
		c8_view_activate(c8_view_group_latest(view));
	}
}

static void window_close(struct wl_client *client,
		struct wl_resource *resource) {
	struct c8_view *view = wl_resource_get_user_data(resource);
	if (view) {
		c8_view_close(view);
	}
}

/* Window icons come from c8ui's loader thread: finding one indexes the
 * icon themes and parses an SVG, tens of milliseconds the compositor's
 * loop mustn't spend. One picture, as big as it's ever drawn (the card's
 * 56 px on a 2x screen, the beacon), shrunk where it's drawn. */
#define ICON_PX 128

static void view_style_clear_icon(struct c8_view_style *style) {
	c8ui_icon_request_cancel(style->icon_request);
	style->icon_request = NULL;
	if (style->icon) {
		cairo_surface_destroy(style->icon);
	}
	style->icon = NULL;
	style->icon_loaded = false;
}

static void icon_arrived(void *data, cairo_surface_t *image) {
	struct c8_view *view = data;
	struct c8_view_style *style = &view->style;
	style->icon_request = NULL;
	style->icon = image;
	style->icon_loaded = true;
	/* What was drawn without it is drawn again */
	c8_slatebar_drop(view);
	c8_slatebar_beacon_drop(view);
	c8_chrome_view_restyled(view->server, view);
}

static void view_style_request_icon(struct c8_view *view) {
	struct c8_view_style *style = &view->style;
	if (style->icon_name == NULL || style->icon_loaded ||
			style->icon_request) {
		return;
	}
	/* Without the loader this answers before it returns (NULL) */
	struct c8ui_icon_request *request = c8ui_icon_request(
		view->server->config.icon_theme, style->icon_name, ICON_PX, true,
		icon_arrived, view);
	if (!style->icon_loaded) {
		style->icon_request = request;
	}
}

static void window_set_style(struct wl_client *client,
		struct wl_resource *resource, uint32_t rgb, const char *icon) {
	struct c8_view *view = wl_resource_get_user_data(resource);
	if (view == NULL) {
		return;
	}
	struct c8_view_style *style = &view->style;
	style->set = true;
	style->color = rgb & 0xffffff;
	if (strcmp(style->icon_name ? style->icon_name : "", icon) != 0) {
		c8_set_str(&style->icon_name, icon[0] ? icon : NULL);
		view_style_clear_icon(style);
		view_style_request_icon(view);
	}
}

/* The switcher's previews: drawn now, straight into the shell's fd */
static void window_capture(struct wl_client *client,
		struct wl_resource *resource, uint32_t serial, int32_t fd,
		int32_t width, int32_t height) {
	struct c8_view *view = wl_resource_get_user_data(resource);
	int w = 0, h = 0;
	struct stat st;
	size_t size = (size_t)(width > 0 ? width : 0) *
		(size_t)(height > 0 ? height : 0) * 4;
	if (view && !c8_locked(view->server) && width > 0 && height > 0 &&
			width <= 4096 && height <= 4096 && fstat(fd, &st) == 0 &&
			(size_t)st.st_size >= size) {
		void *data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED,
			fd, 0);
		if (data != MAP_FAILED) {
			if (!c8_view_capture(view, width, height, data, &w, &h)) {
				w = h = 0;
			}
			munmap(data, size);
		}
	}
	close(fd);
	c8_shell_window_v1_send_captured(resource, serial, w, h);
}

static const struct c8_shell_window_v1_interface window_impl = {
	.destroy = window_handle_destroy,
	.activate = window_activate,
	.close = window_close,
	.set_style = window_set_style,
	.capture = window_capture,
};

void c8_view_style_draw_icon(struct c8_view *view, cairo_t *cr, double x,
		double y, double size) {
	struct c8_view_style *style = &view->style;
	view_style_request_icon(view);
	if (style->icon) {
		c8ui_draw_surface_fit(cr, style->icon, x, y, size, size, 0);
	}
}

static void send_window_props(struct c8_view *view) {
	const char *title = c8_view_title(view);
	const char *app_id = c8_view_app_id(view);
	c8_shell_window_v1_send_title(view->shell_window, title ? title : "");
	c8_shell_window_v1_send_app_id(view->shell_window, app_id ? app_id : "");
	c8_shell_window_v1_send_focused(view->shell_window, view->shell_focused);
	c8_shell_window_v1_send_done(view->shell_window);
}

/* X11 windows all come from Xwayland's connection: no use */
static uint32_t view_pid(struct c8_view *view) {
	if (view->toplevel == NULL) {
		return 0;
	}
	pid_t pid = 0;
	wl_client_get_credentials(view->toplevel->base->client->client, &pid,
		NULL, NULL);
	return pid > 0 ? (uint32_t)pid : 0;
}

static void announce_window(struct c8_server *server, struct c8_view *view) {
	struct c8_shell *shell = &server->shell;
	if (shell->resource == NULL || view->shell_window || !view->mapped ||
			c8_view_parent(view) != NULL) {
		return;
	}
	struct wl_resource *resource = wl_resource_create(shell->client,
		&c8_shell_window_v1_interface, wl_resource_get_version(shell->resource),
		0);
	if (resource == NULL) {
		wl_client_post_no_memory(shell->client);
		return;
	}
	wl_resource_set_implementation(resource, &window_impl, view,
		window_resource_destroy);
	view->shell_window = resource;
	view->shell_focused = view == c8_top_view(server);
	c8_shell_v1_send_window(shell->resource, resource);
	c8_shell_window_v1_send_pid(resource, view_pid(view));
	send_window_props(view);
}

void c8_shell_window_mapped(struct c8_view *view) {
	announce_window(view->server, view);
	c8_shell_focus_changed(view->server);
}

void c8_shell_window_unmapped(struct c8_view *view) {
	view_style_clear_icon(&view->style);
	free(view->style.icon_name);
	view->style = (struct c8_view_style){ 0 };
	if (view->shell_window) {
		c8_shell_window_v1_send_closed(view->shell_window);
		wl_resource_set_user_data(view->shell_window, NULL);
		view->shell_window = NULL;
	}
}

void c8_shell_window_changed(struct c8_view *view) {
	if (view->shell_window) {
		send_window_props(view);
	}
}

void c8_shell_focus_changed(struct c8_server *server) {
	struct c8_view *top = c8_top_view(server);
	/* An app with its dialog in front is the app in front */
	struct c8_view *front = top ? c8_view_root(top) : NULL;
	struct c8_view *view;
	wl_list_for_each(view, &server->views, link) {
		bool focused = view == front;
		if (view->shell_window && view->shell_focused != focused) {
			view->shell_focused = focused;
			c8_shell_window_v1_send_focused(view->shell_window, focused);
			c8_shell_window_v1_send_done(view->shell_window);
		}
	}
	c8_toplevels_focus_changed(server);
}

/* State the shell is told about */

static void send_appearance(struct c8_server *server,
		struct wl_resource *resource) {
	struct c8_config *c = &server->config;
	char buf[16];
	snprintf(buf, sizeof(buf), "#%06x", c->accent & 0xffffff);
	c8_shell_v1_send_appearance(resource, "accent", buf);
	snprintf(buf, sizeof(buf), "#%06x", c->background & 0xffffff);
	c8_shell_v1_send_appearance(resource, "background", buf);
	c8_shell_v1_send_appearance(resource, "pattern", c8_pattern_name(c->pattern));
	c8_shell_v1_send_appearance(resource, "more_tiles",
		c->more_tiles ? "true" : "false");
	c8_shell_v1_send_appearance(resource, "live_tiles",
		c->live_tiles ? "true" : "false");
	c8_shell_v1_send_appearance(resource, "font", c->font ? c->font : "");
	c8_shell_v1_send_appearance(resource, "icon_theme",
		c->icon_theme ? c->icon_theme : "");
	c8_shell_v1_send_appearance(resource, "notification_corner",
		c->notify_corner ? c->notify_corner : "top-right");
	c8_shell_v1_send_appearance(resource, "clock", c->clock ? c->clock : "auto");
	c8_shell_v1_send_appearance(resource, "night_light",
		c8_nightlight_on(server) ? "on" : "off");
	char choices[96];
	c8_project_choices(server, choices, sizeof(choices));
	c8_shell_v1_send_appearance(resource, "project",
		c8_project_name(c8_project_now(server)));
	c8_shell_v1_send_appearance(resource, "project_choices", choices);
	c8_shell_v1_send_appearance(resource, "xr",
		c8_xr_active(server) ? "true" : "false");
	c8_shell_v1_send_appearance_done(resource);
}

static uint32_t power_mask(struct c8_server *server) {
	struct c8_config *c = &server->config;
	uint32_t mask = server->session ? C8_SHELL_V1_POWER_SIGN_OUT :
		C8_SHELL_V1_POWER_EXIT;
	if (c->lock_cmd && c->lock_cmd[0]) {
		mask |= C8_SHELL_V1_POWER_LOCK;
	}
	if (c->sleep_cmd && c->sleep_cmd[0]) {
		mask |= C8_SHELL_V1_POWER_SLEEP;
	}
	if (c->restart_cmd && c->restart_cmd[0]) {
		mask |= C8_SHELL_V1_POWER_RESTART;
	}
	if (c->shutdown_cmd && c->shutdown_cmd[0]) {
		mask |= C8_SHELL_V1_POWER_SHUT_DOWN;
	}
	return mask;
}

void c8_shell_appearance_changed(struct c8_server *server) {
	desktop_update(server);
	/* A new icon theme gives the title bars new glyphs */
	struct c8_view *view;
	wl_list_for_each(view, &server->views, link) {
		view_style_clear_icon(&view->style);
		view_style_request_icon(view);
	}
	if (server->shell.resource) {
		send_appearance(server, server->shell.resource);
	}
}

void c8_shell_locked_changed(struct c8_server *server) {
	struct wl_resource *r = server->shell.resource;
	if (r) {
		c8_shell_v1_send_locked(r, c8_locked(server));
	}
}

void c8_shell_power_changed(struct c8_server *server) {
	if (server->shell.resource) {
		c8_shell_v1_send_power(server->shell.resource, power_mask(server));
	}
}

/* The surface of a role there's one of, once it's mapped */
static struct c8_shell_surface *mapped_role(struct c8_server *server,
		enum c8_shell_role role) {
	struct c8_shell_surface *ss;
	wl_list_for_each(ss, &server->shell.surfaces, link) {
		if (ss->role == role && ss->surface->mapped) {
			return ss;
		}
	}
	return NULL;
}

struct c8_shell_surface *c8_shell_splash(struct c8_server *server) {
	return mapped_role(server, C8_SHELL_SPLASH);
}

struct c8_shell_surface *c8_shell_bar(struct c8_server *server) {
	return mapped_role(server, C8_SHELL_BAR);
}

bool c8_shell_osd_shown(struct c8_shell_surface *ss) {
	return ss->role == C8_SHELL_OSD && ss->surface->mapped &&
		ss->tree->node.enabled;
}

void c8_shell_output_changed(struct c8_server *server) {
	desktop_update(server);
	struct c8_shell_surface *ss;
	wl_list_for_each(ss, &server->shell.surfaces, link) {
		if (role_has_rect(ss->role)) {
			place_panel(ss);
		} else {
			configure_full(ss);
		}
	}
}

void c8_shell_action(struct c8_server *server, uint32_t action) {
	struct wl_resource *r = server->shell.resource;
	if (r == NULL) {
		return;
	}
	c8_shell_v1_send_action(r, action);
}

void c8_shell_switcher(struct c8_server *server, int direction, uint32_t mods) {
	if (server->shell.resource) {
		c8_shell_v1_send_switcher(server->shell.resource, direction, mods);
	}
}

/* The pictures to pick an app for the other side from: only worth
 * showing with a choice, an app besides the one already there */
static void send_snap(struct c8_server *server, bool force) {
	struct c8_shell *shell = &server->shell;
	struct wl_resource *r = shell->resource;
	if (r == NULL) {
		return;
	}
	struct c8_view *snapped = server->snapped;
	struct c8_view *primary = NULL;
	int side = 0;
	struct wlr_box rest = { 0 };
	if (snapped && snapped->mapped) {
		int others = 0;
		struct c8_view *view;
		wl_list_for_each(view, &server->views, link) {
			if (view->mapped && !view->floating && view != snapped &&
					c8_view_parent(view) == NULL) {
				if (primary == NULL) {
					primary = view;
				}
				others++;
			}
		}
		if (others >= 2) {
			struct wlr_box out;
			c8_output_box(server, &out);
			side = server->snap_left ? -1 : 1;
			rest = server->rest_box;
			rest.x -= out.x;
			rest.y -= out.y;
		}
	}
	/* The pick is for a fresh snap: a window newly snapped while others
	 * are left to choose from. The same two apps swapping sides or
	 * moving the split between them (the snapped one was already on
	 * screen as one of the pair) only close a pick still open, and so
	 * does the choice going away. A third window appearing beside a
	 * pair, or one of the pair closing, changes nothing: the new
	 * window, or the next most recent, takes the rest, and the shell
	 * needs no pick for that. While the pick is open (till pick_done),
	 * its window moving side or split sends it again: the pick follows
	 * to the new rest, and stays until something is picked */
	bool fresh = snapped != shell->snap.view;
	bool same_pair = snapped && shell->snap.view &&
		(snapped == shell->snap.view || snapped == shell->snap.primary) &&
		(primary == shell->snap.view || primary == shell->snap.primary);
	bool offer = side != 0 && fresh && !same_pair;
	bool open = shell->snap.side != 0;
	bool follow = open && !fresh && side != 0 &&
		(side != shell->snap.side || !wlr_box_equal(&shell->snap.rest, &rest));
	bool close = open && !offer && !follow && (side == 0 || fresh ||
		side != shell->snap.side || !wlr_box_equal(&shell->snap.rest, &rest));
	shell->snap.view = snapped;
	shell->snap.primary = primary;
	shell->snap.rest = rest;
	if (force || offer || follow) {
		shell->snap.side = side;
		if (side != 0) { // an offer always has one
			c8_shell_v1_send_snap(r, snapped->shell_window, side, rest.x,
				rest.y, rest.width, rest.height);
		}
	} else if (close) {
		shell->snap.side = 0;
		c8_shell_v1_send_snap(r, NULL, 0, 0, 0, 0, 0);
	}
}

void c8_shell_snap_changed(struct c8_server *server) {
	send_snap(server, false);
}

/* Start */

void c8_start_show(struct c8_server *server, bool show) {
	/* Without apps there is nothing but Start to show; without a shell
	 * there is no Start */
	if (!show && c8_top_view(server) == NULL && server->shell.client) {
		show = true;
	}
	if (show && server->shell.client == NULL && c8_top_view(server)) {
		show = false;
	}
	struct c8_shell *shell = &server->shell;
	bool reveal = false;
	if (show != server->start_visible) {
		server->start_visible = show;
		/* Shown again: wait for the shell's first frame of the sweep */
		reveal = show && shell->resource && surface_shown(shell->start);
		shell->start_reveal_pending = reveal;
		wl_event_source_timer_update(shell->start_reveal,
			reveal ? START_REVEAL_MS : 0);
		/* Closing in the glasses: left up while the shell sweeps it
		 * away, as it sweeps in when opening */
		bool closing = !show && c8_xr_active(server) && shell->resource &&
			surface_shown(shell->start) &&
			server->layers.start->node.enabled;
		wl_event_source_timer_update(shell->start_close,
			closing ? START_CLOSE_MS : 0);
		wlr_scene_node_set_enabled(&server->layers.start->node,
			closing || (show && !reveal));
		if (show) {
			c8_chrome_hide(server);
			c8_holo_start_shown(server); // in front of you, in the glasses
		} else if (!closing) {
			c8_holo_start_hidden(server);
		}
		c8_views_arrange(server);
	}
	if (shell->resource) {
		c8_shell_v1_send_start_visible(shell->resource, show);
	}
	if (reveal) {
		/* Its last frame callback may still be pending from when it
		 * was hidden; without this it would never draw again */
		struct timespec now;
		clock_gettime(CLOCK_MONOTONIC, &now);
		wlr_surface_send_frame_done(shell->start->surface, &now);
	}
	focus_update(server);
}

bool c8_shell_panel_open(struct c8_server *server) {
	struct c8_shell_surface *ss;
	wl_list_for_each(ss, &server->shell.surfaces, link) {
		if (ss->role == C8_SHELL_PANEL && surface_shown(ss)) {
			return true;
		}
	}
	return false;
}

bool c8_shell_dismiss(struct c8_server *server, struct wlr_surface *pressed) {
	bool on_panel = false, any = false;
	struct c8_shell_surface *ss;
	wl_list_for_each(ss, &server->shell.surfaces, link) {
		/* The charms bar's charms close what's open themselves, and
		 * then do what they're for */
		if (ss->role == C8_SHELL_BAR && pressed &&
				wlr_surface_get_root_surface(pressed) == ss->surface) {
			return false;
		}
	}
	wl_list_for_each(ss, &server->shell.surfaces, link) {
		if (ss->role != C8_SHELL_PANEL || !surface_shown(ss)) {
			continue;
		}
		any = true;
		if (pressed && wlr_surface_get_root_surface(pressed) == ss->surface) {
			on_panel = true;
		}
	}
	if (!any || on_panel) {
		return false;
	}
	wl_list_for_each(ss, &server->shell.surfaces, link) {
		if (ss->role == C8_SHELL_PANEL && surface_shown(ss)) {
			c8_shell_surface_v1_send_dismissed(ss->resource);
		}
	}
	return true;
}

/* The bar went from view, or a press went elsewhere: what's on it with
 * the keyboard (the switcher, a card) is dismissed, as a panel clicked
 * outside of */
void c8_shell_bar_dismiss(struct c8_server *server) {
	struct c8_shell_surface *ss = c8_shell_bar(server);
	if (ss && ss->grab_keyboard) {
		c8_shell_surface_v1_send_dismissed(ss->resource);
	}
}

struct wlr_surface *c8_shell_keyboard_surface(struct c8_server *server) {
	struct c8_shell_surface *ss;
	wl_list_for_each(ss, &server->shell.surfaces, link) {
		if (ss->grab_keyboard && surface_shown(ss)) {
			return ss->surface;
		}
	}
	if (server->start_visible && surface_shown(server->shell.start)) {
		return server->shell.start->surface;
	}
	return NULL;
}

/* The global */

static void shell_get_surface(struct wl_client *client,
		struct wl_resource *resource, uint32_t id,
		struct wl_resource *surface_resource, uint32_t role) {
	struct c8_server *server = wl_resource_get_user_data(resource);
	struct wlr_surface *surface = wlr_surface_from_resource(surface_resource);
	if (role > C8_SHELL_V1_ROLE_BAR) {
		wl_resource_post_error(resource, C8_SHELL_V1_ERROR_ROLE,
			"unknown role %u", role);
		return;
	}
	if (role == C8_SHELL_V1_ROLE_START && server->shell.start) {
		wl_resource_post_error(resource, C8_SHELL_V1_ERROR_START_EXISTS,
			"there is already a start surface");
		return;
	}
	struct wl_resource *ss_resource = wl_resource_create(client,
		&c8_shell_surface_v1_interface, wl_resource_get_version(resource), id);
	if (ss_resource == NULL) {
		wl_client_post_no_memory(client);
		return;
	}
	if (!wlr_surface_set_role(surface, &shell_role, ss_resource,
			C8_SHELL_V1_ERROR_ROLE)) {
		wl_resource_destroy(ss_resource);
		return;
	}
	struct c8_shell_surface *ss = calloc(1, sizeof(*ss));
	ss->server = server;
	ss->resource = ss_resource;
	ss->surface = surface;
	ss->role = role;
	ss->desc = (struct c8_node_desc){ .type = C8_NODE_SHELL, .data = ss };
	ss->tree = wlr_scene_tree_create(role_layer(server, role));
	ss->tree->node.data = &ss->desc;
	ss->surface_tree = wlr_scene_subsurface_tree_create(ss->tree, surface);
	if (role == C8_SHELL_START) {
		server->shell.start = ss;
	}
	if (role == C8_SHELL_BAR) {
		/* Only the glasses show it, while it's up (hologram.c) */
		wlr_scene_node_set_enabled(&ss->tree->node, false);
	}
	c8_listen(&ss->surface_destroy, &surface->events.destroy,
		handle_surface_gone);
	wl_list_insert(server->shell.surfaces.prev, &ss->link);
	wl_resource_set_implementation(ss_resource, &surface_impl, ss,
		surface_resource_destroy);
	wlr_surface_set_role_object(surface, ss_resource);

	if (role == C8_SHELL_START || role == C8_SHELL_SPLASH) {
		configure_full(ss);
	}
}

static void shell_set_start_visible(struct wl_client *client,
		struct wl_resource *resource, uint32_t visible) {
	struct c8_server *server = wl_resource_get_user_data(resource);
	c8_start_show(server, visible != 0);
}

static void shell_launch(struct wl_client *client,
		struct wl_resource *resource, const char *command) {
	struct c8_server *server = wl_resource_get_user_data(resource);
	c8_launch(server, command);
}

static void shell_run(struct wl_client *client, struct wl_resource *resource,
		uint32_t command) {
	struct c8_server *server = wl_resource_get_user_data(resource);
	struct c8_config *c = &server->config;
	switch (command) {
	case C8_SHELL_V1_COMMAND_PC_SETTINGS:
		c8_settings_launch(server, "@pc-settings");
		break;
	case C8_SHELL_V1_COMMAND_SIGN_OUT:
		wl_display_terminate(server->display);
		break;
	case C8_SHELL_V1_COMMAND_LOCK:
		c8_launch(server, c->lock_cmd);
		break;
	case C8_SHELL_V1_COMMAND_SLEEP:
		c8_exec(c->sleep_cmd);
		break;
	case C8_SHELL_V1_COMMAND_RESTART:
		c8_exec(c->restart_cmd);
		break;
	case C8_SHELL_V1_COMMAND_SHUT_DOWN:
		c8_exec(c->shutdown_cmd);
		break;
	}
}

static void shell_set_appearance(struct wl_client *client,
		struct wl_resource *resource, const char *key, const char *value) {
	struct c8_server *server = wl_resource_get_user_data(resource);
	if (strcmp(key, "night_light") == 0) {
		/* The quick tile: warm now or not, see nightlight.c */
		c8_nightlight_set(server, strcmp(value, "on") == 0);
		send_appearance(server, resource);
		return;
	}
	if (strcmp(key, "project") == 0) {
		/* The Second screen flyout: kept in [display], not [appearance] */
		if (!c8_settings_set(server, "display", "project", value)) {
			send_appearance(server, resource);
		}
		return;
	}
	if (!c8_settings_set_appearance(server, key, value)) {
		/* Put the shell right again */
		send_appearance(server, resource);
	}
}

static void shell_set_start_width(struct wl_client *client,
		struct wl_resource *resource, uint32_t width) {
	struct c8_server *server = wl_resource_get_user_data(resource);
	server->xr.start_width = (int)(width < INT32_MAX ? width : INT32_MAX);
	if (c8_xr_active(server)) {
		c8_xr_shell_size(server); // a group added or taken away
	}
}

/* The shell's pick closed: moves of the snapped app no longer go to
 * it. One for an older snap than the last told is let be */
static void shell_pick_done(struct wl_client *client,
		struct wl_resource *resource, struct wl_resource *window) {
	struct c8_server *server = wl_resource_get_user_data(resource);
	struct c8_view *view = window ? wl_resource_get_user_data(window) : NULL;
	if (view == NULL || view == server->shell.snap.view) {
		server->shell.snap.side = 0;
		c8_views_arrange(server); // what was behind it comes back
	}
}

static const struct c8_shell_v1_interface shell_impl = {
	.get_surface = shell_get_surface,
	.set_start_visible = shell_set_start_visible,
	.launch = shell_launch,
	.run = shell_run,
	.set_appearance = shell_set_appearance,
	.set_start_width = shell_set_start_width,
	.pick_done = shell_pick_done,
};

static void shell_resource_destroy(struct wl_resource *resource) {
	struct c8_server *server = wl_resource_get_user_data(resource);
	if (server && server->shell.resource == resource) {
		server->shell.resource = NULL;
	}
}

static void shell_bind(struct wl_client *client, void *data, uint32_t version,
		uint32_t id) {
	struct c8_server *server = data;
	/* The global filter already hides it; this is belt and braces */
	if (client != server->shell.client || server->shell.resource) {
		wl_client_post_implementation_error(client,
			"c8_shell_v1 is only for the shell, once");
		return;
	}
	struct wl_resource *resource =
		wl_resource_create(client, &c8_shell_v1_interface, version, id);
	if (resource == NULL) {
		wl_client_post_no_memory(client);
		return;
	}
	wl_resource_set_implementation(resource, &shell_impl, server,
		shell_resource_destroy);
	server->shell.resource = resource;

	send_appearance(server, resource);
	c8_shell_v1_send_power(resource, power_mask(server));
	c8_shell_v1_send_locked(resource, c8_locked(server));
	/* Least recently used first, so the shell can keep the order */
	struct c8_view *view;
	wl_list_for_each_reverse(view, &server->views, link) {
		announce_window(server, view);
	}
	c8_shell_v1_send_start_visible(resource, server->start_visible);
	memset(&server->shell.snap, 0, sizeof(server->shell.snap));
	send_snap(server, true);
}

/* Running the shell */

static void spawn(struct c8_server *server);

static int respawn(void *data) {
	struct c8_server *server = data;
	spawn(server);
	return 0;
}

static void handle_client_destroy(struct wl_listener *listener, void *data) {
	struct c8_shell *shell = wl_container_of(listener, shell, client_destroy);
	struct c8_server *server =
		wl_container_of(shell, server, shell);
	wl_list_remove(&shell->client_destroy.link);
	shell->client = NULL;
	shell->resource = NULL;
	if (server->terminating) {
		return;
	}
	bool quick = c8_now_ms() - shell->started < SHELL_STABLE_MS;
	shell->quick_exits = quick ? shell->quick_exits + 1 : 0;
	int delay = RESPAWN_MS;
	for (int i = 1; i < shell->quick_exits && delay < RESPAWN_MAX_MS; i++) {
		delay *= 2;
	}
	if (delay > RESPAWN_MAX_MS) {
		delay = RESPAWN_MAX_MS;
	}
	wlr_log(WLR_ERROR, "%s went away; starting it again in %d ms",
		SHELL_PROGRAM, delay);
	wl_event_source_timer_update(shell->respawn, delay);
	/* Show the apps until it's back */
	c8_start_show(server, false);
}

static void spawn(struct c8_server *server) {
	struct c8_shell *shell = &server->shell;
	if (shell->client) {
		return;
	}
	/* Tile providers outlive the shell: only its first run starts them */
	char *argv[] = { SHELL_PROGRAM, "--config", server->config.dir,
		shell->spawned ? "--respawn" : NULL, NULL };
	shell->client = c8_spawn_client(server, argv);
	if (shell->client == NULL) {
		wl_event_source_timer_update(shell->respawn, RESPAWN_MAX_MS);
		return;
	}
	shell->started = c8_now_ms();
	shell->spawned = true;
	shell->client_destroy.notify = handle_client_destroy;
	wl_client_add_destroy_listener(shell->client, &shell->client_destroy);
}

static int icons_ready(int fd, uint32_t mask, void *data) {
	c8ui_icon_loader_dispatch();
	return 0;
}

void c8_shell_init(struct c8_server *server) {
	struct c8_shell *shell = &server->shell;
	wl_list_init(&shell->surfaces);
	server->desktop = wlr_scene_rect_create(server->layers.background, 0, 0,
		(float[4]){ 0, 0, 0, 1 });
	server->desktop->node.data = &c8_ui_desc;
	wlr_scene_node_lower_to_bottom(&server->desktop->node);
	desktop_update(server);
	shell->global = wl_global_create(server->display, &c8_shell_v1_interface,
		SHELL_VERSION, server, shell_bind);
	shell->respawn = wl_event_loop_add_timer(server->loop, respawn, server);
	int icons = c8ui_icon_loader_start();
	if (icons >= 0) {
		shell->icons = wl_event_loop_add_fd(server->loop, icons,
			WL_EVENT_READABLE, icons_ready, NULL);
	}
	shell->start_reveal = wl_event_loop_add_timer(server->loop,
		start_reveal_timeout, server);
	shell->start_close = wl_event_loop_add_timer(server->loop,
		start_close_timeout, server);
	/* Start shows as soon as the shell draws it */
	server->start_visible = true;
	wlr_scene_node_set_enabled(&server->layers.start->node, true);
}

void c8_shell_start(struct c8_server *server) {
	spawn(server);
}

void c8_shell_finish(struct c8_server *server) {
	struct c8_shell *shell = &server->shell;
	wl_event_source_remove(shell->respawn);
	shell->respawn = NULL;
	/* The loader itself is left running to the end: stopping it frees
	 * requests that windows closing after this would still cancel */
	if (shell->icons) {
		wl_event_source_remove(shell->icons);
		shell->icons = NULL;
	}
	wl_event_source_remove(shell->start_reveal);
	shell->start_reveal = NULL;
	wl_event_source_remove(shell->start_close);
	shell->start_close = NULL;
	if (shell->client) {
		wl_list_remove(&shell->client_destroy.link);
		shell->client = NULL;
	}
}
