/*
 * c8-share: picks what an app may share, a screen or one window, for
 * xdg-desktop-portal-wlr (its chooser_cmd, chooser_type=simple). It
 * prints "Monitor: NAME" or "Window: IDENTIFIER" (an
 * ext-foreign-toplevel-list identifier) and exits 0; printing nothing
 * and exiting 1 is No.
 *
 * The screen dims behind a band across it, as Windows 8's dialogs were,
 * with a picture of every screen and every window to choose from. The
 * pictures come from ext-image-copy-capture: the screens' before the
 * band shows (or it would be in them), the windows' whenever (c8 gives a
 * window's capture only its own surfaces, so what covers it isn't in
 * it, hidden ones too).
 */
#define _GNU_SOURCE
#include <errno.h>
#include <math.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <time.h>
#include <unistd.h>
#include <gio/gdesktopappinfo.h>
#include <glib.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include <c8ui/c8ui.h>
#include <c8ui/c8ui-wayland.h>
#include "shrink.h"
#include "askpass-wlr-layer-shell-unstable-v1-client-protocol.h"
#include "ext-foreign-toplevel-list-v1-client-protocol.h"
#include "ext-image-capture-source-v1-client-protocol.h"
#include "ext-image-copy-capture-v1-client-protocol.h"

#define ITEM_W 240.0
#define ITEM_GAP 20.0
#define LABEL_H 44.0 // under the picture: title and a smaller line
#define HEAD_H 40.0 // "Screens", "Windows"
#define BAND_MAX 1180.0 // the content's width at most, centred
/* Pictures are kept this many times their drawn size, for HiDPI */
#define KEEP 2
/* Screens' pictures are waited for this long before the band shows */
#define WAIT_MS 1000

struct item {
	struct wl_list link; // S.screens or S.windows
	bool window;
	uint32_t global; // a screen's wl_output
	struct wl_output *output;
	struct ext_foreign_toplevel_handle_v1 *handle;
	char *name; // the output's name, the window's identifier
	char *title, *sub;
	bool ready; // a window's done came: it has its identifier
	struct c8ui_icon *icon;
	bool icon_tried;
	cairo_surface_t *picture; // shrunk
	/* Capturing */
	struct ext_image_capture_source_v1 *source;
	struct ext_image_copy_capture_session_v1 *session;
	struct ext_image_copy_capture_frame_v1 *frame;
	struct wl_buffer *buffer;
	void *pixels;
	size_t size;
	int width, height;
	uint32_t format;
	bool have_format, capturing;
	struct c8ui_rect rect; // laid out
};

static struct {
	struct c8ui_app *app;
	struct wl_display *display;
	struct wl_registry *registry;
	struct wl_shm *shm;
	struct ext_foreign_toplevel_list_v1 *toplevels;
	struct ext_image_copy_capture_manager_v1 *copy;
	struct ext_output_image_capture_source_manager_v1 *output_sources;
	struct ext_foreign_toplevel_image_capture_source_manager_v1
		*window_sources;
	struct zwlr_layer_shell_v1 *shell;
	struct zwlr_layer_surface_v1 *layer;
	struct c8ui_window *win;
	struct wl_list screens, windows;
	int capturing; // captures not finished

	struct c8ui_widget *picker, *scroll, *band, *share;
	struct item *selected, *hovered, *pressed;
	int64_t last_click;
	struct item *last_clicked;
	int columns;
	bool done;
} S;

/* Answering */

static void finish(struct item *it) {
	if (S.done) {
		return;
	}
	S.done = true;
	if (it) {
		printf("%s: %s\n", it->window ? "Window" : "Monitor", it->name);
		fflush(stdout);
	}
	c8ui_app_quit(S.app, it ? 0 : 1);
}

static void share_clicked(struct c8ui_widget *w, void *data) {
	if (S.selected) {
		finish(S.selected);
	}
}

static void cancel_clicked(struct c8ui_widget *w, void *data) {
	finish(NULL);
}

/* Items */

static void item_changed(void) {
	if (S.picker) {
		c8ui_widget_queue_layout(S.picker);
	}
}

static void capture_end(struct item *it) {
	if (it->frame) {
		ext_image_copy_capture_frame_v1_destroy(it->frame);
		it->frame = NULL;
	}
	if (it->session) {
		ext_image_copy_capture_session_v1_destroy(it->session);
		it->session = NULL;
	}
	if (it->source) {
		ext_image_capture_source_v1_destroy(it->source);
		it->source = NULL;
	}
	if (it->buffer) {
		wl_buffer_destroy(it->buffer);
		it->buffer = NULL;
	}
	if (it->pixels) {
		munmap(it->pixels, it->size);
		it->pixels = NULL;
	}
	if (it->capturing) {
		it->capturing = false;
		S.capturing--;
	}
}

static void item_destroy(struct item *it) {
	if (S.selected == it) {
		S.selected = NULL;
		if (S.share) {
			c8ui_widget_set_disabled(S.share, true);
		}
	}
	if (S.hovered == it) {
		S.hovered = NULL;
	}
	if (S.pressed == it) {
		S.pressed = NULL;
	}
	if (S.last_clicked == it) {
		S.last_clicked = NULL;
	}
	capture_end(it);
	if (it->picture) {
		cairo_surface_destroy(it->picture);
	}
	if (it->icon) {
		c8ui_icon_destroy(it->icon);
	}
	if (it->handle) {
		ext_foreign_toplevel_handle_v1_destroy(it->handle);
	}
	if (it->output) {
		wl_output_release(it->output);
	}
	wl_list_remove(&it->link);
	g_free(it->name);
	g_free(it->title);
	g_free(it->sub);
	free(it);
	item_changed();
}

/* Capturing a picture */

static void frame_transform(void *data,
		struct ext_image_copy_capture_frame_v1 *frame, uint32_t transform) {
}

static void frame_damage(void *data,
		struct ext_image_copy_capture_frame_v1 *frame, int32_t x, int32_t y,
		int32_t width, int32_t height) {
}

static void frame_time(void *data, struct ext_image_copy_capture_frame_v1 *f,
		uint32_t hi, uint32_t lo, uint32_t nsec) {
}

/* The whole picture shrunk once to what is drawn (times KEEP) */
static void frame_ready(void *data, struct ext_image_copy_capture_frame_v1 *f) {
	struct item *it = data;
	cairo_format_t format = it->format == WL_SHM_FORMAT_ARGB8888 ?
		CAIRO_FORMAT_ARGB32 : CAIRO_FORMAT_RGB24;
	cairo_surface_t *full = cairo_image_surface_create_for_data(it->pixels,
		format, it->width, it->height, it->width * 4);
	cairo_surface_t *small = image_shrunk(full, it->width, it->height,
		ITEM_W * KEEP, ITEM_W * 9 / 16 * KEEP);
	cairo_surface_destroy(full);
	if (it->picture) {
		cairo_surface_destroy(it->picture);
	}
	it->picture = small;
	capture_end(it);
	c8ui_widget_queue_draw(S.picker);
}

static void frame_failed(void *data, struct ext_image_copy_capture_frame_v1 *f,
		uint32_t reason) {
	capture_end(data);
}

static const struct ext_image_copy_capture_frame_v1_listener frame_listener = {
	.transform = frame_transform,
	.damage = frame_damage,
	.presentation_time = frame_time,
	.ready = frame_ready,
	.failed = frame_failed,
};

static void session_size(void *data,
		struct ext_image_copy_capture_session_v1 *session, uint32_t width,
		uint32_t height) {
	struct item *it = data;
	it->width = width;
	it->height = height;
}

static void session_shm_format(void *data,
		struct ext_image_copy_capture_session_v1 *session, uint32_t format) {
	struct item *it = data;
	/* Either of the two cairo reads as it is; ARGB when offered, so a
	 * window's see-through parts stay so */
	if (format == WL_SHM_FORMAT_ARGB8888 ||
			(format == WL_SHM_FORMAT_XRGB8888 && !it->have_format)) {
		it->format = format;
		it->have_format = true;
	}
}

static void session_dmabuf_device(void *data,
		struct ext_image_copy_capture_session_v1 *session,
		struct wl_array *device) {
}

static void session_dmabuf_format(void *data,
		struct ext_image_copy_capture_session_v1 *session, uint32_t format,
		struct wl_array *modifiers) {
}

static void session_done(void *data,
		struct ext_image_copy_capture_session_v1 *session) {
	struct item *it = data;
	if (it->frame || it->picture) {
		return; // the size changed meanwhile: the picture coming will do
	}
	if (!it->have_format || it->width <= 0 || it->height <= 0) {
		capture_end(it);
		return;
	}
	it->size = (size_t)it->width * it->height * 4;
	int fd = memfd_create("c8-share", MFD_CLOEXEC);
	if (fd < 0 || ftruncate(fd, it->size) < 0) {
		if (fd >= 0) {
			close(fd);
		}
		capture_end(it);
		return;
	}
	it->pixels = mmap(NULL, it->size, PROT_READ | PROT_WRITE, MAP_SHARED, fd,
		0);
	if (it->pixels == MAP_FAILED) {
		it->pixels = NULL;
		close(fd);
		capture_end(it);
		return;
	}
	struct wl_shm_pool *pool = wl_shm_create_pool(S.shm, fd, it->size);
	it->buffer = wl_shm_pool_create_buffer(pool, 0, it->width, it->height,
		it->width * 4, it->format);
	wl_shm_pool_destroy(pool);
	close(fd);
	it->frame = ext_image_copy_capture_session_v1_create_frame(session);
	ext_image_copy_capture_frame_v1_add_listener(it->frame, &frame_listener,
		it);
	ext_image_copy_capture_frame_v1_attach_buffer(it->frame, it->buffer);
	ext_image_copy_capture_frame_v1_damage_buffer(it->frame, 0, 0, it->width,
		it->height);
	ext_image_copy_capture_frame_v1_capture(it->frame);
}

static void session_stopped(void *data,
		struct ext_image_copy_capture_session_v1 *session) {
	capture_end(data);
}

static const struct ext_image_copy_capture_session_v1_listener
		session_listener = {
	.buffer_size = session_size,
	.shm_format = session_shm_format,
	.dmabuf_device = session_dmabuf_device,
	.dmabuf_format = session_dmabuf_format,
	.done = session_done,
	.stopped = session_stopped,
};

static void capture(struct item *it) {
	if (S.copy == NULL || S.shm == NULL || it->capturing) {
		return;
	}
	if (it->window && S.window_sources) {
		it->source = ext_foreign_toplevel_image_capture_source_manager_v1_create_source(
			S.window_sources, it->handle);
	} else if (!it->window && S.output_sources) {
		it->source = ext_output_image_capture_source_manager_v1_create_source(
			S.output_sources, it->output);
	}
	if (it->source == NULL) {
		return;
	}
	it->capturing = true;
	S.capturing++;
	it->session = ext_image_copy_capture_manager_v1_create_session(S.copy,
		it->source, 0);
	ext_image_copy_capture_session_v1_add_listener(it->session,
		&session_listener, it);
}

/* Screens */

static void output_geometry(void *data, struct wl_output *o, int32_t x,
		int32_t y, int32_t pw, int32_t ph, int32_t subpixel, const char *make,
		const char *model, int32_t transform) {
}

static void output_mode(void *data, struct wl_output *o, uint32_t flags,
		int32_t width, int32_t height, int32_t refresh) {
}

static void output_done(void *data, struct wl_output *o) {
	item_changed();
}

static void output_scale(void *data, struct wl_output *o, int32_t factor) {
}

static void output_name(void *data, struct wl_output *o, const char *name) {
	struct item *it = data;
	g_free(it->name);
	it->name = g_strdup(name);
}

static void output_description(void *data, struct wl_output *o,
		const char *description) {
	struct item *it = data;
	g_free(it->sub);
	it->sub = g_strdup(description);
}

static const struct wl_output_listener output_listener = {
	.geometry = output_geometry,
	.mode = output_mode,
	.done = output_done,
	.scale = output_scale,
	.name = output_name,
	.description = output_description,
};

/* "Built-in screen" for a laptop's panel, else "Screen" (numbered when
 * there are more) */
static const char *screen_title(struct item *it, int n, int count) {
	static char buf[32];
	const char *name = it->name ? it->name : "";
	if (g_str_has_prefix(name, "eDP") || g_str_has_prefix(name, "LVDS") ||
			g_str_has_prefix(name, "DSI")) {
		return "Built-in screen";
	}
	if (count == 1) {
		return "Your screen";
	}
	snprintf(buf, sizeof(buf), "Screen %d", n);
	return buf;
}

/* Windows */

static void toplevel_closed(void *data,
		struct ext_foreign_toplevel_handle_v1 *handle) {
	item_destroy(data);
}

static void toplevel_done(void *data,
		struct ext_foreign_toplevel_handle_v1 *handle) {
	struct item *it = data;
	bool first = !it->ready;
	it->ready = true;
	if (first) {
		capture(it);
	}
	item_changed();
}

static void toplevel_title(void *data,
		struct ext_foreign_toplevel_handle_v1 *handle, const char *title) {
	struct item *it = data;
	g_free(it->title);
	it->title = g_strdup(title);
}

static void toplevel_app_id(void *data,
		struct ext_foreign_toplevel_handle_v1 *handle, const char *app_id) {
	struct item *it = data;
	g_free(it->sub);
	it->sub = g_strdup(app_id);
}

static void toplevel_identifier(void *data,
		struct ext_foreign_toplevel_handle_v1 *handle, const char *id) {
	struct item *it = data;
	g_free(it->name);
	it->name = g_strdup(id);
}

static const struct ext_foreign_toplevel_handle_v1_listener toplevel_listener = {
	.closed = toplevel_closed,
	.done = toplevel_done,
	.title = toplevel_title,
	.app_id = toplevel_app_id,
	.identifier = toplevel_identifier,
};

static void list_toplevel(void *data, struct ext_foreign_toplevel_list_v1 *list,
		struct ext_foreign_toplevel_handle_v1 *handle) {
	struct item *it = calloc(1, sizeof(*it));
	it->window = true;
	it->handle = handle;
	ext_foreign_toplevel_handle_v1_add_listener(handle, &toplevel_listener, it);
	/* Newest first */
	wl_list_insert(&S.windows, &it->link);
}

static void list_finished(void *data,
		struct ext_foreign_toplevel_list_v1 *list) {
}

static const struct ext_foreign_toplevel_list_v1_listener list_listener = {
	.toplevel = list_toplevel,
	.finished = list_finished,
};

/* The app's name and icon from its desktop entry, else its id */
static void window_app(struct item *it) {
	if (it->icon_tried || it->sub == NULL) {
		return;
	}
	it->icon_tried = true;
	char *file = g_strconcat(it->sub, ".desktop", NULL);
	GDesktopAppInfo *info = g_desktop_app_info_new(file);
	g_free(file);
	if (info) {
		char *icon = g_desktop_app_info_get_string(info, "Icon");
		if (icon && icon[0]) {
			it->icon = c8ui_icon_load(NULL, icon);
		}
		g_free(icon);
		const char *name = g_app_info_get_name(G_APP_INFO(info));
		if (name && name[0]) {
			g_free(it->sub);
			it->sub = g_strdup(name);
		}
		g_object_unref(info);
	}
	if (it->icon == NULL) {
		it->icon = c8ui_icon_load(NULL, it->sub);
	}
}

/* Globals */

static void registry_global(void *data, struct wl_registry *registry,
		uint32_t name, const char *interface, uint32_t version) {
	if (strcmp(interface, wl_output_interface.name) == 0 && version >= 4) {
		struct item *it = calloc(1, sizeof(*it));
		it->global = name;
		it->output = wl_registry_bind(registry, name, &wl_output_interface, 4);
		wl_output_add_listener(it->output, &output_listener, it);
		wl_list_insert(S.screens.prev, &it->link);
		item_changed();
	} else if (strcmp(interface, wl_shm_interface.name) == 0) {
		S.shm = wl_registry_bind(registry, name, &wl_shm_interface, 1);
	} else if (strcmp(interface,
			ext_foreign_toplevel_list_v1_interface.name) == 0) {
		S.toplevels = wl_registry_bind(registry, name,
			&ext_foreign_toplevel_list_v1_interface, 1);
		ext_foreign_toplevel_list_v1_add_listener(S.toplevels,
			&list_listener, NULL);
	} else if (strcmp(interface,
			ext_image_copy_capture_manager_v1_interface.name) == 0) {
		S.copy = wl_registry_bind(registry, name,
			&ext_image_copy_capture_manager_v1_interface, 1);
	} else if (strcmp(interface,
			ext_output_image_capture_source_manager_v1_interface.name) == 0) {
		S.output_sources = wl_registry_bind(registry, name,
			&ext_output_image_capture_source_manager_v1_interface, 1);
	} else if (strcmp(interface,
			ext_foreign_toplevel_image_capture_source_manager_v1_interface.name)
			== 0) {
		S.window_sources = wl_registry_bind(registry, name,
			&ext_foreign_toplevel_image_capture_source_manager_v1_interface, 1);
	}
}

static void registry_global_remove(void *data, struct wl_registry *registry,
		uint32_t name) {
	struct item *it, *tmp;
	wl_list_for_each_safe(it, tmp, &S.screens, link) {
		if (it->global == name) {
			item_destroy(it);
		}
	}
}

static const struct wl_registry_listener registry_listener = {
	.global = registry_global,
	.global_remove = registry_global_remove,
};

/* Waits for the screens' pictures (and the windows') before the band
 * shows, at most WAIT_MS */
static void wait_for_pictures(void) {
	struct timespec start, now;
	clock_gettime(CLOCK_MONOTONIC, &start);
	while (S.capturing > 0) {
		clock_gettime(CLOCK_MONOTONIC, &now);
		long ms = (now.tv_sec - start.tv_sec) * 1000 +
			(now.tv_nsec - start.tv_nsec) / 1000000;
		if (ms >= WAIT_MS) {
			break;
		}
		while (wl_display_prepare_read(S.display) != 0) {
			wl_display_dispatch_pending(S.display);
		}
		wl_display_flush(S.display);
		struct pollfd pfd = { wl_display_get_fd(S.display), POLLIN, 0 };
		if (poll(&pfd, 1, WAIT_MS - ms) > 0) {
			wl_display_read_events(S.display);
		} else {
			wl_display_cancel_read(S.display);
		}
		wl_display_dispatch_pending(S.display);
	}
}

/* The picker: screens, then windows, each a picture over its name */

static int count_items(struct wl_list *list) {
	return wl_list_length(list);
}

/* Columns and the items' width for a width: as many ITEM_W as fit, but
 * two at least, shrunk to fit when narrow */
static double item_width(double width, int *columns) {
	int cols = (int)floor((width + ITEM_GAP) / (ITEM_W + ITEM_GAP));
	if (cols >= 2) {
		*columns = cols;
		return ITEM_W;
	}
	*columns = 2;
	return fmax(80, (width - ITEM_GAP) / 2);
}

static double section_height(int count, int cols, double iw) {
	int rows = count > 0 ? (count + cols - 1) / cols : 1;
	double ih = iw * 9 / 16 + LABEL_H;
	return HEAD_H + rows * ih + (rows - 1) * ITEM_GAP;
}

static double picker_height(double width) {
	int cols;
	double iw = item_width(width, &cols);
	return section_height(count_items(&S.screens), cols, iw) + ITEM_GAP +
		section_height(count_items(&S.windows), cols, iw);
}

static void picker_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	*width = avail;
	*height = picker_height(avail);
}

static double layout_section(struct wl_list *list, double x, double y,
		double width) {
	int cols;
	double iw = item_width(width, &cols);
	double ih = iw * 9 / 16 + LABEL_H;
	int i = 0;
	struct item *it;
	wl_list_for_each(it, list, link) {
		it->rect = (struct c8ui_rect){
			x + (i % cols) * (iw + ITEM_GAP),
			y + HEAD_H + (i / cols) * (ih + ITEM_GAP), iw, ih,
		};
		i++;
	}
	S.columns = cols;
	return section_height(i, cols, iw);
}

static void picker_layout(struct c8ui_widget *w) {
	struct c8ui_rect *r = &w->rect;
	double h = layout_section(&S.screens, r->x, r->y, r->width);
	layout_section(&S.windows, r->x, r->y + h + ITEM_GAP, r->width);
}

/* A screen with nothing captured: a monitor drawn in lines */
static void draw_screen_glyph(cairo_t *cr, double cx, double cy) {
	cairo_set_source_rgba(cr, 1, 1, 1, 0.8);
	cairo_set_line_width(cr, 2);
	cairo_rectangle(cr, cx - 24, cy - 18, 48, 30);
	cairo_move_to(cr, cx - 10, cy + 20);
	cairo_line_to(cr, cx + 10, cy + 20);
	cairo_move_to(cr, cx, cy + 12);
	cairo_line_to(cr, cx, cy + 20);
	cairo_stroke(cr);
}

static void draw_item(struct c8ui_widget *w, cairo_t *cr, struct item *it,
		const char *title) {
	struct c8ui_rect *r = &it->rect;
	struct c8ui_colors c = c8ui_widget_colors(w);
	double ph = r->width * 9 / 16;
	cairo_set_source_rgba(cr, 0, 0, 0, 0.35);
	cairo_rectangle(cr, r->x, r->y, r->width, ph);
	cairo_fill(cr);
	if (it->window) {
		window_app(it);
	}
	if (it->picture) {
		c8ui_draw_surface_fit(cr, it->picture, r->x, r->y, r->width, ph, 1);
	} else if (it->window && it->icon) {
		c8ui_icon_draw_fit(cr, it->icon, r->x + r->width / 2,
			r->y + ph / 2, 48);
	} else if (!it->window) {
		draw_screen_glyph(cr, r->x + r->width / 2, r->y + ph / 2);
	}

	/* The window's app icon, then its title over the app's name */
	double y = r->y + ph + 8, x = r->x;
	if (it->window && it->icon) {
		c8ui_icon_draw_fit(cr, it->icon, x + 12, y + 14, 24);
		x += 32;
	}
	double tw = r->x + r->width - x;
	const char *font = c8ui_widget_font(w);
	c8ui_set_source(cr, c.fg, 1);
	c8ui_text_draw(cr, font, c8ui_text_font(C8UI_TEXT_BODY), title, x, y, tw,
		1);
	if (it->sub) {
		c8ui_set_source(cr, c.fg, c.fg_secondary);
		c8ui_text_draw(cr, font, c8ui_text_font(C8UI_TEXT_CAPTION), it->sub,
			x, y + 20, tw, 1);
	}

	/* Chosen: the accent round it; pointed at: a thin line */
	bool ring = it == S.selected && c8ui_widget_shows_focus(w);
	if (it == S.selected) {
		c8ui_set_source(cr, c.accent, 1);
		cairo_set_line_width(cr, 4);
		cairo_rectangle(cr, r->x - 2, r->y - 2, r->width + 4, ph + 4);
		cairo_stroke(cr);
		/* A tick in the corner, as Metro's selected items had */
		double s = 28, cx = r->x + r->width - s, cy = r->y;
		cairo_move_to(cr, cx, cy);
		cairo_line_to(cr, cx + s, cy);
		cairo_line_to(cr, cx + s, cy + s);
		cairo_close_path(cr);
		cairo_fill(cr);
		cairo_set_source_rgb(cr, 1, 1, 1);
		cairo_set_line_width(cr, 2);
		cairo_move_to(cr, cx + 14, cy + 8);
		cairo_line_to(cr, cx + 18, cy + 12);
		cairo_line_to(cr, cx + 25, cy + 4);
		cairo_stroke(cr);
	} else if (it == S.hovered) {
		c8ui_set_source(cr, c.fg, 0.7);
		cairo_set_line_width(cr, 2);
		cairo_rectangle(cr, r->x - 1, r->y - 1, r->width + 2, ph + 2);
		cairo_stroke(cr);
	}
	if (ring) {
		c8ui_set_source(cr, c.fg, 1);
		cairo_set_line_width(cr, 1);
		cairo_set_dash(cr, (double[]){ 1, 1 }, 1, 0);
		cairo_rectangle(cr, r->x - 6.5, r->y - 6.5, r->width + 13,
			r->height + 13);
		cairo_stroke(cr);
		cairo_set_dash(cr, NULL, 0, 0);
	}
}

static void draw_heading(struct c8ui_widget *w, cairo_t *cr, const char *text,
		double y) {
	struct c8ui_colors c = c8ui_widget_colors(w);
	c8ui_set_source(cr, c.fg, 1);
	c8ui_text_draw(cr, c8ui_widget_font(w), c8ui_text_font(C8UI_TEXT_TITLE),
		text, w->rect.x, y, w->rect.width, 1);
}

static void picker_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct c8ui_rect *r = &w->rect;
	int count = count_items(&S.screens);
	draw_heading(w, cr, count == 1 ? "Screen" : "Screens", r->y);
	int n = 1;
	struct item *it;
	wl_list_for_each(it, &S.screens, link) {
		draw_item(w, cr, it, screen_title(it, n++, count));
	}
	int cols;
	double iw = item_width(r->width, &cols);
	double wy = r->y + section_height(count, cols, iw) + ITEM_GAP;
	draw_heading(w, cr, "Windows", wy);
	bool any = false;
	wl_list_for_each(it, &S.windows, link) {
		if (it->ready && it->name) {
			draw_item(w, cr, it, it->title && it->title[0] ? it->title :
				"Untitled");
			any = true;
		}
	}
	if (!any) {
		struct c8ui_colors c = c8ui_widget_colors(w);
		c8ui_set_source(cr, c.fg, c.fg_secondary);
		c8ui_text_draw(cr, c8ui_widget_font(w),
			c8ui_text_font(C8UI_TEXT_BODY), "No apps are open.", r->x,
			wy + HEAD_H, r->width, 1);
	}
}

/* Every item in order: screens, then windows */
static struct item *item_at_index(int index) {
	int i = 0;
	struct item *it;
	wl_list_for_each(it, &S.screens, link) {
		if (i++ == index) {
			return it;
		}
	}
	wl_list_for_each(it, &S.windows, link) {
		if (it->ready && it->name && i++ == index) {
			return it;
		}
	}
	return NULL;
}

static int index_of(struct item *want) {
	int i = 0;
	struct item *it;
	wl_list_for_each(it, &S.screens, link) {
		if (it == want) {
			return i;
		}
		i++;
	}
	wl_list_for_each(it, &S.windows, link) {
		if (it->ready && it->name) {
			if (it == want) {
				return i;
			}
			i++;
		}
	}
	return -1;
}

static struct item *item_at(double x, double y) {
	struct item *it;
	wl_list_for_each(it, &S.screens, link) {
		if (c8ui_rect_contains(&it->rect, x, y)) {
			return it;
		}
	}
	wl_list_for_each(it, &S.windows, link) {
		if (it->ready && it->name && c8ui_rect_contains(&it->rect, x, y)) {
			return it;
		}
	}
	return NULL;
}

static void select_item(struct item *it) {
	S.selected = it;
	c8ui_widget_set_disabled(S.share, it == NULL);
	if (it) {
		c8ui_widget_reveal(S.picker, &it->rect);
	}
	c8ui_widget_queue_draw(S.picker);
}

static int64_t now_ms(void) {
	return g_get_monotonic_time() / 1000;
}

/* Arrows move the choice: sideways along the rows, up and down by a row
 * within a section, or to the other section */
static void move(int dx, int dy) {
	int i = S.selected ? index_of(S.selected) : -1;
	int screens = count_items(&S.screens);
	if (i < 0) {
		select_item(item_at_index(0));
		return;
	}
	int cols = S.columns;
	int next = i + dx;
	if (dy != 0) {
		bool in_screens = i < screens;
		int base = in_screens ? 0 : screens;
		int col = (i - base) % cols;
		next = i + dy * cols;
		if (dy > 0 && in_screens && next >= screens) {
			/* Down out of the screens: the windows' first row */
			next = screens + col;
		} else if (dy < 0 && !in_screens && next < screens) {
			/* Up into the screens' last row */
			int last_row = (screens - 1) / cols;
			next = last_row * cols + col;
			if (next >= screens) {
				next = screens - 1;
			}
		}
	}
	struct item *it = next >= 0 ? item_at_index(next) : NULL;
	if (it == NULL && dy > 0) {
		/* The last row is shorter: its last item */
		int total = i;
		while (item_at_index(total + 1)) {
			total++;
		}
		it = total != i ? item_at_index(total) : NULL;
	}
	if (it) {
		select_item(it);
	}
}

static bool picker_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	switch (ev->type) {
	case C8UI_EVENT_MOTION:
	case C8UI_EVENT_ENTER: {
		struct item *it = item_at(ev->x, ev->y);
		if (it != S.hovered) {
			S.hovered = it;
			c8ui_widget_queue_draw(w);
		}
		return false;
	}
	case C8UI_EVENT_LEAVE:
		S.hovered = NULL;
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_PRESS:
		if (ev->button != C8UI_BUTTON_LEFT) {
			return false;
		}
		S.pressed = item_at(ev->x, ev->y);
		return S.pressed != NULL;
	case C8UI_EVENT_RELEASE: {
		struct item *it = item_at(ev->x, ev->y);
		bool was = it && it == S.pressed;
		S.pressed = NULL;
		if (!was) {
			return false;
		}
		/* A click chooses; a second on the same one shares it */
		int64_t t = now_ms();
		if (it == S.last_clicked && t - S.last_click < 400) {
			finish(it);
			return true;
		}
		S.last_clicked = it;
		S.last_click = t;
		select_item(it);
		return true;
	}
	case C8UI_EVENT_KEY:
		switch (ev->sym) {
		case XKB_KEY_Left:
			move(-1, 0);
			return true;
		case XKB_KEY_Right:
			move(1, 0);
			return true;
		case XKB_KEY_Up:
			move(0, -1);
			return true;
		case XKB_KEY_Down:
			move(0, 1);
			return true;
		case XKB_KEY_space:
			if (S.selected == NULL) {
				move(0, 0);
			}
			return true;
		}
		return false;
	case C8UI_EVENT_FOCUS_IN:
		if (S.selected == NULL) {
			select_item(item_at_index(0));
		}
		/* fall through */
	case C8UI_EVENT_FOCUS_OUT:
		c8ui_widget_queue_draw(w);
		return false;
	default:
		return false;
	}
}

static const struct c8ui_widget_impl picker_impl = {
	.name = "share-picker",
	.measure = picker_measure,
	.layout = picker_layout,
	.draw = picker_draw,
	.event = picker_event,
};

/* Building it */

static bool key(const struct c8ui_event *ev, void *data) {
	switch (ev->sym) {
	case XKB_KEY_Escape:
		finish(NULL);
		return true;
	case XKB_KEY_Return:
	case XKB_KEY_KP_Enter:
		if (S.selected) {
			finish(S.selected);
		}
		return true;
	}
	return false;
}

/* The content centred in the band, BAND_MAX at most; the pictures
 * scroll when there are more than half the screen holds */
static void resized(struct c8ui_root *root, double width, double height,
		void *data) {
	bool narrow = width < C8UI_NARROW_WIDTH;
	double side = narrow ? 12 : fmax(40, (width - BAND_MAX) / 2);
	c8ui_box_set_padding(S.band, side, narrow ? 16 : 28, side,
		narrow ? 16 : 24);
	double room = height - (narrow ? 200 : 260);
	double want = picker_height(width - 2 * side);
	S.scroll->fixed_height = fmax(120, fmin(want + 8, room));
}

static struct c8ui_widget *build(void) {
	struct c8ui_widget *cover = c8ui_box_new(C8UI_VERTICAL, 0);
	struct c8ui_widget *above = c8ui_spacer_new(0, 0);
	above->expand = true;
	c8ui_widget_add(cover, above);

	S.band = c8ui_box_new(C8UI_VERTICAL, 8);
	S.band->fill = true;
	c8ui_widget_set_scheme(S.band, C8UI_SCHEME_DARK);
	const struct c8ui_theme *theme = c8ui_app_theme(S.app);
	c8ui_widget_set_background(S.band, theme ? theme->background : 0x1d1d1d);
	c8ui_widget_add(cover, S.band);

	c8ui_widget_add(S.band, c8ui_label_new("Choose what to share",
		C8UI_TEXT_SUBHEADER));
	struct c8ui_widget *why = c8ui_label_new("An app wants to share your "
		"screen. It sees only the screen or window you choose, until it "
		"stops sharing.", C8UI_TEXT_BODY);
	c8ui_label_set_color(why, C8UI_COLOR_SECONDARY);
	c8ui_label_set_max_lines(why, 3);
	c8ui_widget_add(S.band, why);
	c8ui_widget_add(S.band, c8ui_spacer_new(0, 8));

	S.picker = c8ui_widget_new(&picker_impl, NULL);
	S.picker->focusable = true;
	S.picker->fill = true;
	S.scroll = c8ui_scroll_new(S.picker);
	S.scroll->fill = true;
	c8ui_widget_add(S.band, S.scroll);

	struct c8ui_widget *foot = c8ui_box_new(C8UI_HORIZONTAL, 12);
	foot->fill = true;
	c8ui_box_set_padding(foot, 0, 16, 0, 0);
	c8ui_widget_add(S.band, foot);
	struct c8ui_widget *gap = c8ui_spacer_new(0, 0);
	gap->expand = true;
	c8ui_widget_add(foot, gap);
	S.share = c8ui_button_new("Share", share_clicked, NULL);
	c8ui_button_set_primary(S.share, true);
	c8ui_widget_set_disabled(S.share, true);
	c8ui_widget_add(foot, S.share);
	c8ui_widget_add(foot, c8ui_button_new("Cancel", cancel_clicked, NULL));

	struct c8ui_widget *below = c8ui_spacer_new(0, 0);
	below->expand = true;
	c8ui_widget_add(cover, below);
	return cover;
}

/* Layer shell */

static void layer_configure(void *data, struct zwlr_layer_surface_v1 *layer,
		uint32_t serial, uint32_t width, uint32_t height) {
	zwlr_layer_surface_v1_ack_configure(layer, serial);
	c8ui_window_configure(S.win, width, height);
}

static void layer_closed(void *data, struct zwlr_layer_surface_v1 *layer) {
	finish(NULL);
}

static const struct zwlr_layer_surface_v1_listener layer_listener = {
	.configure = layer_configure,
	.closed = layer_closed,
};

int main(int argc, char *argv[]) {
	wl_list_init(&S.screens);
	wl_list_init(&S.windows);
	S.app = c8ui_app_new("org.cont8nuum.Share");
	if (S.app == NULL) {
		fprintf(stderr, "c8-share: can't reach the compositor\n");
		return 1;
	}
	S.display = c8ui_app_display(S.app);
	S.registry = wl_display_get_registry(S.display);
	wl_registry_add_listener(S.registry, &registry_listener, NULL);
	/* Globals, then the outputs' names and the windows, then their done */
	wl_display_roundtrip(S.display);
	wl_display_roundtrip(S.display);
	wl_display_roundtrip(S.display);
	if (wl_list_empty(&S.screens)) {
		fprintf(stderr, "c8-share: no screens\n");
		return 1;
	}
	struct item *it;
	wl_list_for_each(it, &S.screens, link) {
		capture(it);
	}
	wait_for_pictures();

	struct c8ui_widget *cover = build();
	S.shell = c8ui_app_bind(S.app, &zwlr_layer_shell_v1_interface, 4);
	struct c8ui_root *root;
	if (S.shell) {
		S.win = c8ui_window_new_bare(S.app);
		c8ui_window_set_background(S.win, 0x000000, 0.6);
		struct wl_surface *surface = c8ui_window_surface(S.win);
		S.layer = zwlr_layer_shell_v1_get_layer_surface(S.shell, surface,
			NULL, ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY, "c8-share");
		zwlr_layer_surface_v1_add_listener(S.layer, &layer_listener, NULL);
		zwlr_layer_surface_v1_set_anchor(S.layer,
			ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP |
			ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM |
			ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT |
			ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT);
		zwlr_layer_surface_v1_set_exclusive_zone(S.layer, -1);
		zwlr_layer_surface_v1_set_keyboard_interactivity(S.layer, 1);
		wl_surface_commit(surface);
	} else {
		/* Another compositor: a plain window will do */
		S.win = c8ui_window_new(S.app, "Choose what to share", 900, 640);
		c8ui_window_set_background(S.win, 0x000000, 1);
	}
	root = c8ui_window_root(S.win);
	c8ui_root_on_resize(root, resized, NULL);
	c8ui_root_set_child(root, cover);
	c8ui_root_set_key_handler(root, key, NULL);
	c8ui_widget_grab_focus(S.picker);
	c8ui_widget_enter(S.band);
	int status = c8ui_app_run(S.app);
	return S.done ? status : 1;
}
