/*
 * Print Screen, the Windows 8 way: PrtSc copies the screens to the
 * clipboard, Alt+PrtSc just the app in front, and Super+PrtSc dims the
 * screens for a moment and saves them to Pictures/Screenshots as
 * "Screenshot (N).png". A notification says which happened; the saved
 * one opens the file (or its folder) when clicked.
 *
 * Each output's scene is rendered once more into a swapchain of our own
 * (so nothing the screens show changes), read back and put together in
 * layout coordinates at the largest output scale. PNG encoding happens in
 * a forked child so the compositor doesn't stall on a 4K image.
 *
 * Snips (snip.c) use the same capture and land on the clipboard too.
 */
#include <cairo.h>
#include <dirent.h>
#include <drm_fourcc.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <wlr/render/allocator.h>
#include <wlr/render/swapchain.h>
#include <wlr/render/wlr_renderer.h>
#include <wlr/types/wlr_compositor.h>
#include <wlr/types/wlr_data_device.h>
#include <wlr/types/wlr_output.h>
#include <wlr/types/wlr_output_layout.h>
#include <wlr/types/wlr_scene.h>
#include <wlr/types/wlr_xdg_shell.h>
#include <wlr/util/box.h>
#include <wlr/util/log.h>
#include <wlr/util/transform.h>
#include "server.h"

#define FLASH_MS 250

/* A buffer's pixels (its top left width x height, 0: all of it) read
 * back as an XRGB image, or NULL */
cairo_surface_t *c8_buffer_read(struct c8_server *server,
		struct wlr_buffer *buffer, int width, int height) {
	struct wlr_texture *texture =
		wlr_texture_from_buffer(server->renderer, buffer);
	if (texture == NULL) {
		return NULL;
	}
	width = width > 0 ? width : (int)texture->width;
	height = height > 0 ? height : (int)texture->height;
	cairo_surface_t *image = cairo_image_surface_create(CAIRO_FORMAT_RGB24,
		width, height);
	bool ok = cairo_surface_status(image) == CAIRO_STATUS_SUCCESS;
	if (ok) {
		cairo_surface_flush(image);
	}
	/* Cairo's RGB24 is XRGB8888 in memory on little and big endian alike
	 * as far as DRM fourccs go (both are native 32-bit words) */
	uint32_t formats[] = { DRM_FORMAT_XRGB8888, DRM_FORMAT_ARGB8888 };
	bool read = false;
	for (size_t i = 0; ok && i < 2 && !read; i++) {
		read = wlr_texture_read_pixels(texture,
			&(struct wlr_texture_read_pixels_options){
				.data = cairo_image_surface_get_data(image),
				.format = formats[i],
				.stride = cairo_image_surface_get_stride(image),
				.src_box = { 0, 0, width, height },
			});
	}
	wlr_texture_destroy(texture);
	if (!read) {
		cairo_surface_destroy(image);
		return NULL;
	}
	cairo_surface_mark_dirty(image);
	return image;
}

/* One output's frame, read back as XRGB in buffer orientation */
static cairo_surface_t *read_output(struct c8_server *server,
		struct c8_output *output) {
	struct wlr_output *wlr_output = output->wlr_output;
	struct wlr_output_state state;
	wlr_output_state_init(&state);
	struct wlr_swapchain *swapchain = NULL;
	cairo_surface_t *image = NULL;

	if (!wlr_output_configure_primary_swapchain(wlr_output, &state,
			&swapchain)) {
		goto out;
	}
	struct wlr_scene_output_state_options options = {
		.swapchain = swapchain,
	};
	if (wlr_scene_output_build_state(output->scene_output, &state,
			&options) && (state.committed & WLR_OUTPUT_STATE_BUFFER) &&
			state.buffer) {
		image = c8_buffer_read(server, state.buffer, 0, 0);
	}
out:
	wlr_output_state_finish(&state);
	if (swapchain) {
		wlr_swapchain_destroy(swapchain);
	}
	if (image == NULL) {
		wlr_log(WLR_ERROR, "Screenshot: couldn't read %s", wlr_output->name);
	}
	return image;
}

/* The pixel map wlroots itself uses from the output's upright pixels
 * (tw x th) to its buffer, as a cairo pattern matrix */
static void buffer_matrix(enum wl_output_transform transform, int tw, int th,
		cairo_matrix_t *m) {
	enum wl_output_transform inv = wlr_output_transform_invert(transform);
	struct wlr_box o, ex, ey;
	wlr_box_transform(&o, &(struct wlr_box){ 0, 0, 1, 1 }, inv, tw, th);
	wlr_box_transform(&ex, &(struct wlr_box){ 1, 0, 1, 1 }, inv, tw, th);
	wlr_box_transform(&ey, &(struct wlr_box){ 0, 1, 1, 1 }, inv, tw, th);
	double xx = ex.x - o.x, yx = ex.y - o.y;
	double xy = ey.x - o.x, yy = ey.y - o.y;
	/* Pixel centres map to pixel centres */
	cairo_matrix_init(m, xx, yx, xy, yy,
		o.x + 0.5 - 0.5 * (xx + xy), o.y + 0.5 - 0.5 * (yx + yy));
}

/* Every enabled output in layout coordinates, scaled by *scale_out. The
 * layout area covered is *area_out. */
cairo_surface_t *c8_screenshot_capture(struct c8_server *server,
		struct wlr_box *area_out, double *scale_out) {
	struct wlr_box area = { 0 };
	double scale = 1;
	struct c8_output *output;
	wl_list_for_each(output, &server->outputs, link) {
		if (!output->wlr_output->enabled) {
			continue;
		}
		struct wlr_box box;
		wlr_output_layout_get_box(server->output_layout,
			output->wlr_output, &box);
		if (wlr_box_empty(&box)) {
			continue;
		}
		if (wlr_box_empty(&area)) {
			area = box;
		} else {
			int x2 = MAX(area.x + area.width, box.x + box.width);
			int y2 = MAX(area.y + area.height, box.y + box.height);
			area.x = MIN(area.x, box.x);
			area.y = MIN(area.y, box.y);
			area.width = x2 - area.x;
			area.height = y2 - area.y;
		}
		scale = MAX(scale, output->wlr_output->scale);
	}
	if (wlr_box_empty(&area)) {
		return NULL;
	}

	cairo_surface_t *canvas = cairo_image_surface_create(CAIRO_FORMAT_RGB24,
		(int)(area.width * scale + 0.5), (int)(area.height * scale + 0.5));
	if (cairo_surface_status(canvas) != CAIRO_STATUS_SUCCESS) {
		cairo_surface_destroy(canvas);
		return NULL;
	}
	cairo_t *cr = cairo_create(canvas);
	cairo_set_source_rgb(cr, 0, 0, 0);
	cairo_paint(cr);
	bool any = false;
	wl_list_for_each(output, &server->outputs, link) {
		struct wlr_output *wo = output->wlr_output;
		struct wlr_box box;
		wlr_output_layout_get_box(server->output_layout, wo, &box);
		if (!wo->enabled || wlr_box_empty(&box)) {
			continue;
		}
		cairo_surface_t *image = read_output(server, output);
		if (image == NULL) {
			continue;
		}
		int tw, th;
		wlr_output_transformed_resolution(wo, &tw, &th);
		cairo_save(cr);
		cairo_translate(cr, (box.x - area.x) * scale, (box.y - area.y) * scale);
		cairo_scale(cr, box.width * scale / tw, box.height * scale / th);
		cairo_pattern_t *pattern = cairo_pattern_create_for_surface(image);
		cairo_matrix_t m;
		buffer_matrix(wo->transform, tw, th, &m);
		cairo_pattern_set_matrix(pattern, &m);
		cairo_pattern_set_filter(pattern, wo->scale == scale ?
			CAIRO_FILTER_NEAREST : CAIRO_FILTER_GOOD);
		cairo_set_source(cr, pattern);
		cairo_rectangle(cr, 0, 0, tw, th);
		cairo_fill(cr);
		cairo_pattern_destroy(pattern);
		cairo_restore(cr);
		cairo_surface_destroy(image);
		any = true;
	}
	cairo_destroy(cr);
	if (!any) {
		cairo_surface_destroy(canvas);
		return NULL;
	}
	cairo_surface_flush(canvas);
	*area_out = area;
	*scale_out = scale;
	return canvas;
}

/* Just the box (layout coordinates) out of a capture */
cairo_surface_t *c8_screenshot_crop(cairo_surface_t *full,
		struct wlr_box area, double scale, struct wlr_box box) {
	struct wlr_box inside;
	if (!wlr_box_intersection(&inside, &area, &box)) {
		return NULL;
	}
	int x = (int)((inside.x - area.x) * scale + 0.5);
	int y = (int)((inside.y - area.y) * scale + 0.5);
	int w = (int)(inside.width * scale + 0.5);
	int h = (int)(inside.height * scale + 0.5);
	if (w <= 0 || h <= 0) {
		return NULL;
	}
	cairo_surface_t *out = cairo_image_surface_create(CAIRO_FORMAT_RGB24, w, h);
	cairo_t *cr = cairo_create(out);
	cairo_set_source_surface(cr, full, -x, -y);
	cairo_paint(cr);
	cairo_destroy(cr);
	cairo_surface_flush(out);
	return out;
}

static cairo_status_t write_fd(void *closure, const unsigned char *data,
		unsigned int length) {
	int fd = *(int *)closure;
	while (length > 0) {
		ssize_t n = write(fd, data, length);
		if (n < 0 && errno == EINTR) {
			continue;
		}
		if (n <= 0) {
			return CAIRO_STATUS_WRITE_ERROR;
		}
		data += n;
		length -= n;
	}
	return CAIRO_STATUS_SUCCESS;
}

/* Runs fn(image, data) in a grandchild that encodes and writes, so the
 * compositor neither waits for it nor has to reap it */
static void in_child(cairo_surface_t *image,
		void (*fn)(cairo_surface_t *image, void *data), void *data) {
	pid_t pid = fork();
	if (pid < 0) {
		wlr_log_errno(WLR_ERROR, "Screenshot: fork failed");
		return;
	}
	if (pid == 0) {
		sigset_t set;
		sigemptyset(&set);
		sigprocmask(SIG_SETMASK, &set, NULL);
		signal(SIGPIPE, SIG_DFL); // a paste given up on just ends us
		if (fork() == 0) {
			fn(image, data);
			_exit(0);
		}
		_exit(0);
	}
	waitpid(pid, NULL, 0);
}

/* XDG_PICTURES_DIR from user-dirs.dirs, else ~/Pictures */
static void pictures_dir(char *out, size_t size) {
	const char *home = getenv("HOME");
	if (home == NULL) {
		home = "/tmp";
	}
	snprintf(out, size, "%s/Pictures", home);
	char path[PATH_MAX];
	const char *config = getenv("XDG_CONFIG_HOME");
	if (config && config[0]) {
		snprintf(path, sizeof(path), "%s/user-dirs.dirs", config);
	} else {
		snprintf(path, sizeof(path), "%s/.config/user-dirs.dirs", home);
	}
	FILE *f = fopen(path, "r");
	if (f == NULL) {
		return;
	}
	char line[PATH_MAX];
	while (fgets(line, sizeof(line), f)) {
		const char *key = "XDG_PICTURES_DIR=\"";
		if (strncmp(line, key, strlen(key)) != 0) {
			continue;
		}
		char *v = line + strlen(key);
		char *end = strrchr(v, '"');
		if (end == NULL) {
			break;
		}
		*end = '\0';
		int n = -1;
		if (strncmp(v, "$HOME", 5) == 0) {
			n = snprintf(out, size, "%s%s", home, v + 5);
		} else if (v[0] == '/') {
			n = snprintf(out, size, "%s", v);
		}
		if (n < 0 || (size_t)n >= size) {
			/* Too long to keep whole: a cut path is somewhere else */
			snprintf(out, size, "%s/Pictures", home);
		}
		break;
	}
	fclose(f);
}

/* notify-send in the background (it's only a child of ours), the
 * shell's notification server shows it as a toast */
static void notify(const char *const argv[]) {
	pid_t pid = fork();
	if (pid == 0) {
		execvp(argv[0], (char *const *)argv);
		_exit(127);
	}
	if (pid > 0) {
		waitpid(pid, NULL, 0);
	}
}

static void notify_failed(const char *why) {
	notify((const char *const[]){ "notify-send", "--app-name=Screenshots",
		"--icon=dialog-error", "Couldn't save the screenshot", why, NULL });
}

/* notify-send --wait: the action clicked into answer, false for none */
static bool notify_wait(const char *const argv[], char *answer, size_t size) {
	int fds[2];
	if (pipe(fds) < 0) {
		return false;
	}
	pid_t pid = fork();
	if (pid == 0) {
		dup2(fds[1], STDOUT_FILENO);
		close(fds[0]);
		close(fds[1]);
		execvp(argv[0], (char *const *)argv);
		_exit(127);
	}
	close(fds[1]);
	ssize_t n = pid > 0 ? read(fds[0], answer, size - 1) : -1;
	close(fds[0]);
	if (pid > 0) {
		waitpid(pid, NULL, 0);
	}
	if (n <= 0) {
		return false;
	}
	answer[n] = '\0';
	answer[strcspn(answer, "\n")] = '\0';
	return answer[0] != '\0';
}

/* Tell where it went and wait for a click: the toast opens the file,
 * its button the folder. Runs in the writing child, so it can wait. */
static void notify_saved(const char *path, const char *dir) {
	char shown[PATH_MAX];
	const char *home = getenv("HOME");
	size_t hl = home ? strlen(home) : 0;
	if (hl > 1 && strncmp(path, home, hl) == 0 && path[hl] == '/') {
		snprintf(shown, sizeof(shown), "~%s", path + hl);
	} else {
		snprintf(shown, sizeof(shown), "%s", path);
	}
	char answer[64];
	if (!notify_wait((const char *const[]){ "notify-send",
			"--app-name=Screenshots", "--icon", path, "--wait",
			"--action=default=Open", "--action=folder=Open folder",
			"Screenshot saved", shown, NULL }, answer, sizeof(answer))) {
		return;
	}
	const char *target = strcmp(answer, "default") == 0 ? path :
		strcmp(answer, "folder") == 0 ? dir : NULL;
	if (target) {
		execlp("xdg-open", "xdg-open", target, (char *)NULL);
	}
}

/* Pictures/Screenshots/Screenshot (N).png, N one past the highest there */
static void save(cairo_surface_t *image, void *data) {
	char dir[PATH_MAX - 64];
	pictures_dir(dir, sizeof(dir));
	mkdir(dir, 0755);
	size_t len = strlen(dir);
	snprintf(dir + len, sizeof(dir) - len, "/Screenshots");
	mkdir(dir, 0755);

	int next = 1;
	DIR *d = opendir(dir);
	if (d) {
		struct dirent *e;
		while ((e = readdir(d))) {
			int n;
			char tail[8];
			if (sscanf(e->d_name, "Screenshot (%d)%7s", &n, tail) == 2 &&
					strcmp(tail, ".png") == 0 && n >= next) {
				next = n + 1;
			}
		}
		closedir(d);
	}
	for (int tries = 0; tries < 100; tries++, next++) {
		char path[PATH_MAX];
		snprintf(path, sizeof(path), "%s/Screenshot (%d).png", dir, next);
		int fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644);
		if (fd < 0 && errno == EEXIST) {
			continue;
		}
		if (fd < 0) {
			fprintf(stderr, "c8: cannot save %s: %s\n", path, strerror(errno));
			notify_failed(strerror(errno));
			return;
		}
		bool ok = cairo_surface_write_to_png_stream(image, write_fd, &fd) ==
			CAIRO_STATUS_SUCCESS;
		close(fd);
		if (!ok) {
			fprintf(stderr, "c8: cannot write %s\n", path);
			unlink(path);
			notify_failed("The disk may be full.");
			return;
		}
		cairo_surface_destroy(image); // the child doesn't need it while waiting
		notify_saved(path, dir);
		return;
	}
}

/* The clipboard: a PNG, encoded for each paste */
struct shot_source {
	struct wlr_data_source base;
	cairo_surface_t *image;
};

static void send_png(cairo_surface_t *image, void *data) {
	cairo_surface_write_to_png_stream(image, write_fd, data);
}

static void source_send(struct wlr_data_source *base, const char *mime_type,
		int32_t fd) {
	struct shot_source *source = wl_container_of(base, source, base);
	if (strcmp(mime_type, "image/png") == 0) {
		in_child(source->image, send_png, &fd);
	}
	close(fd);
}

static void source_destroy(struct wlr_data_source *base) {
	struct shot_source *source = wl_container_of(base, source, base);
	cairo_surface_destroy(source->image);
	free(source);
}

static const struct wlr_data_source_impl source_impl = {
	.send = source_send,
	.destroy = source_destroy,
};

static void to_clipboard(struct c8_server *server, cairo_surface_t *image) {
	struct shot_source *source = calloc(1, sizeof(*source));
	if (source == NULL) {
		cairo_surface_destroy(image);
		return;
	}
	wlr_data_source_init(&source->base, &source_impl);
	source->image = image;
	char **mime = wl_array_add(&source->base.mime_types, sizeof(*mime));
	if (mime) {
		*mime = strdup("image/png");
	}
	wlr_seat_set_selection(server->seat, &source->base,
		wl_display_next_serial(server->display));
}

/* The screens dim for a moment, as Windows does when it saves one */
static struct wlr_scene_rect *flash_rect;
static struct wl_event_source *flash_timer;

static int flash_end(void *data) {
	if (flash_rect) {
		wlr_scene_node_destroy(&flash_rect->node);
		flash_rect = NULL;
	}
	return 0;
}

static void flash(struct c8_server *server, struct wlr_box area) {
	if (flash_timer == NULL) {
		flash_timer = wl_event_loop_add_timer(server->loop, flash_end, NULL);
	}
	if (flash_rect == NULL) {
		flash_rect = wlr_scene_rect_create(&server->scene->tree,
			area.width, area.height, (float[4]){ 0, 0, 0, 0.5f });
	}
	if (flash_rect == NULL) {
		return;
	}
	wlr_scene_node_raise_to_top(&flash_rect->node);
	wlr_scene_node_set_position(&flash_rect->node, area.x, area.y);
	wlr_scene_rect_set_size(flash_rect, area.width, area.height);
	if (flash_timer) {
		wl_event_source_timer_update(flash_timer, FLASH_MS);
	}
}

static void notify_copied(cairo_surface_t *image, void *data) {
	notify(data);
}

/* The snip's toast: a click on it (or Save) keeps it in Screenshots */
static void notify_snip(cairo_surface_t *image, void *data) {
	char answer[64];
	if (notify_wait((const char *const[]){ "notify-send",
			"--app-name=Screenshots", "--icon=edit-cut", "--wait",
			"--action=default=Save", "--action=save=Save",
			"Snip copied to the clipboard",
			"Select here to save it in Screenshots.", NULL },
			answer, sizeof(answer)) && (strcmp(answer, "default") == 0 ||
			strcmp(answer, "save") == 0)) {
		save(image, NULL);
	}
}

void c8_screenshot_snipped(struct c8_server *server, cairo_surface_t *image) {
	in_child(image, notify_snip, NULL);
	to_clipboard(server, image);
}

/* One window on its own, for the switcher: its surfaces drawn straight
 * from their textures, so what covers it on screen (Start, other apps,
 * the switcher itself) isn't in the picture, as it would be cropping
 * the screen or with wlroots' scene node capture */

struct capture_pass {
	struct wlr_render_pass *pass;
	double scale;
	int gx, gy; // the window geometry's corner, in surface coordinates
};

static void capture_surface(struct wlr_surface *surface, int sx, int sy,
		void *data) {
	struct capture_pass *cp = data;
	struct wlr_texture *texture = wlr_surface_get_texture(surface);
	if (texture == NULL) {
		return;
	}
	struct wlr_fbox src;
	wlr_surface_get_buffer_source_box(surface, &src);
	double x = (sx - cp->gx) * cp->scale, y = (sy - cp->gy) * cp->scale;
	int x0 = (int)lround(x), y0 = (int)lround(y);
	struct wlr_box dst = {
		.x = x0,
		.y = y0,
		.width = (int)lround(x + surface->current.width * cp->scale) - x0,
		.height = (int)lround(y + surface->current.height * cp->scale) - y0,
	};
	if (dst.width <= 0 || dst.height <= 0) {
		return;
	}
	wlr_render_pass_add_texture(cp->pass, &(struct wlr_render_texture_options){
		.texture = texture,
		.src_box = src,
		.dst_box = dst,
		.transform = surface->current.transform,
		.filter_mode = WLR_SCALE_FILTER_BILINEAR,
		.blend_mode = WLR_RENDER_BLEND_MODE_PREMULTIPLIED,
	});
}

struct wlr_buffer *c8_capture_buffer(struct c8_server *server, int w,
		int h) {
	/* A linear buffer if the allocator does modifiers, else whatever it
	 * picks (shm ignores them) */
	static const uint64_t mods[] = { DRM_FORMAT_MOD_LINEAR,
		DRM_FORMAT_MOD_INVALID };
	for (size_t i = 0; i < 2; i++) {
		uint64_t mod = mods[i];
		struct wlr_drm_format format = {
			.format = DRM_FORMAT_ARGB8888,
			.len = 1,
			.capacity = 1,
			.modifiers = &mod,
		};
		struct wlr_buffer *buffer = wlr_allocator_create_buffer(
			server->allocator, w, h, &format);
		if (buffer) {
			return buffer;
		}
	}
	return NULL;
}

bool c8_view_capture(struct c8_view *view, int max_w, int max_h, void *data,
		int *width, int *height) {
	struct c8_server *server = view->server;
	struct wlr_surface *surface = view->impl->get_surface(view);
	if (surface == NULL || !view->mapped || max_w <= 0 || max_h <= 0) {
		return false;
	}
	struct wlr_box geo = { 0, 0, surface->current.width,
		surface->current.height };
	if (view->toplevel && !wlr_box_empty(&view->toplevel->base->geometry)) {
		geo = view->toplevel->base->geometry;
	}
	if (wlr_box_empty(&geo)) {
		return false;
	}
	double scale = MIN(1, MIN((double)max_w / geo.width,
		(double)max_h / geo.height));
	int w = MAX(1, MIN(max_w, (int)lround(geo.width * scale)));
	int h = MAX(1, MIN(max_h, (int)lround(geo.height * scale)));

	struct wlr_buffer *buffer = c8_capture_buffer(server, w, h);
	if (buffer == NULL) {
		wlr_log(WLR_ERROR, "Window capture: no buffer");
		return false;
	}
	bool ok = false;
	struct wlr_render_pass *pass = wlr_renderer_begin_buffer_pass(
		server->renderer, buffer, NULL);
	if (pass) {
		wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){
			.box = { 0, 0, w, h },
			.color = { 0, 0, 0, 0 },
			.blend_mode = WLR_RENDER_BLEND_MODE_NONE,
		});
		struct capture_pass cp = { pass, scale, geo.x, geo.y };
		wlr_surface_for_each_surface(surface, capture_surface, &cp);
		ok = wlr_render_pass_submit(pass);
	}
	struct wlr_texture *texture = ok ?
		wlr_texture_from_buffer(server->renderer, buffer) : NULL;
	ok = texture && wlr_texture_read_pixels(texture,
		&(struct wlr_texture_read_pixels_options){
			.data = data,
			.format = DRM_FORMAT_ARGB8888,
			.stride = w * 4,
		});
	if (texture) {
		wlr_texture_destroy(texture);
	}
	wlr_buffer_drop(buffer);
	if (!ok) {
		wlr_log(WLR_ERROR, "Window capture: couldn't draw or read it");
		return false;
	}
	*width = w;
	*height = h;
	return true;
}

static cairo_surface_t *xr_window(struct c8_server *server) {
	struct c8_view *view = c8_top_view(server);
	if (view == NULL || server->start_visible) {
		return NULL;
	}
	int w = MIN(view->geo.width, 8192), h = MIN(view->geo.height, 8192);
	cairo_surface_t *image = w > 0 && h > 0 ?
		cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w, h) : NULL;
	if (image == NULL || cairo_surface_status(image) != CAIRO_STATUS_SUCCESS ||
			cairo_image_surface_get_stride(image) != w * 4) {
		goto fail;
	}
	cairo_surface_flush(image);
	int cw, ch;
	if (!c8_view_capture(view, w, h, cairo_image_surface_get_data(image),
			&cw, &ch)) {
		goto fail;
	}
	cairo_surface_mark_dirty(image);
	if (cw == w && ch == h) {
		return image;
	}
	/* Drawn smaller than asked: just that part */
	cairo_surface_t *part = cairo_image_surface_create_for_data(
		cairo_image_surface_get_data(image), CAIRO_FORMAT_ARGB32, cw, ch,
		cw * 4); // its rows are as wide as it drew
	cairo_surface_t *copy = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
		cw, ch);
	cairo_t *cr = cairo_create(copy);
	cairo_set_source_surface(cr, part, 0, 0);
	cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
	cairo_paint(cr);
	cairo_destroy(cr);
	cairo_surface_destroy(part);
	cairo_surface_destroy(image);
	return copy;
fail:
	if (image) {
		cairo_surface_destroy(image);
	}
	return NULL;
}

#define SHOT_WAIT_MS 1000 // for Monado's picture, before drawing our own

static void screenshot_with(struct c8_server *server,
		enum c8_action_type action, cairo_surface_t *image, bool xr);

/* Monado didn't send its picture: ours, without a game */
static int shot_timeout(void *data) {
	struct c8_server *server = data;
	int action = server->xr.shot_action;
	if (action == 0) {
		return 0;
	}
	server->xr.shot_action = 0;
	wlr_log(WLR_ERROR, "Screenshot: Monado sent no picture; drawing ours");
	screenshot_with(server, action, c8_xr_screenshot(server), true);
	return 0;
}

void c8_screenshot_finish(struct c8_server *server, int action,
		cairo_surface_t *image, bool xr) {
	screenshot_with(server, action, image, xr);
}

void c8_screenshot(struct c8_server *server, enum c8_action_type action) {
	/* In XR the picture is what you see: the slates around
	 * you, not the shell's screen alone; the app in front is its window
	 * drawn flat. No flash, which would blind you */
	bool xr = c8_xr_active(server);
	cairo_surface_t *image = NULL;
	if (xr && action == C8_ACTION_SCREENSHOT_WINDOW) {
		image = xr_window(server);
	}
	if (xr && image == NULL) {
		if (server->xr.shot_action) {
			return; // one is on its way
		}
		/* Monado's own picture, everything it puts together, a game
		 * too: it comes in a frame or two (c8_xr_share_frame) */
		if (c8_xr_runtime_share(server, '1')) {
			if (server->xr.shot_timer == NULL) {
				server->xr.shot_timer = wl_event_loop_add_timer(
					server->loop, shot_timeout, server);
			}
			server->xr.shot_action = action;
			wl_event_source_timer_update(server->xr.shot_timer,
				SHOT_WAIT_MS);
			return;
		}
		image = c8_xr_screenshot(server);
	}
	screenshot_with(server, action, image, xr);
}

static void screenshot_with(struct c8_server *server,
		enum c8_action_type action, cairo_surface_t *image, bool xr) {
	struct wlr_box area;
	double scale;
	if (image) {
		/* The window's picture is already cut out: nothing to crop.
		 * Saving stays saving */
		if (action == C8_ACTION_SCREENSHOT_WINDOW) {
			action = C8_ACTION_SCREENSHOT;
		}
	} else {
		xr = false;
		image = c8_screenshot_capture(server, &area, &scale);
	}
	if (image == NULL) {
		wlr_log(WLR_ERROR, "Screenshot: nothing to capture");
		return;
	}
	if (action == C8_ACTION_SCREENSHOT_WINDOW) {
		struct c8_view *view = c8_top_view(server);
		cairo_surface_t *part = NULL;
		if (view && !server->start_visible) {
			part = c8_screenshot_crop(image, area, scale, view->geo);
		}
		if (part) {
			cairo_surface_destroy(image);
			image = part;
		}
	}
	if (action == C8_ACTION_SCREENSHOT_SAVE) {
		if (!xr) {
			flash(server, area);
		}
		in_child(image, save, NULL);
		cairo_surface_destroy(image);
	} else {
		to_clipboard(server, image);
		static const char *const copied[] = { "notify-send",
			"--app-name=Screenshots", "--icon=edit-paste",
			"--hint=string:transient:true", "Screenshot copied",
			"Paste it into an app to use it.", NULL };
		in_child(NULL, notify_copied, (void *)copied);
	}
}
