/*
 * Snip (Super+Shift+S): the screens freeze and dim, a bar at the top
 * picks how to cut (a rectangle, a freeform shape, a window or all the
 * screens), and what's cut goes to the clipboard as Print's does, with a
 * toast that saves it. Escape or the bar's close button lets go.
 *
 * The frozen picture is one capture (screenshot.c) shown in layers.snip.
 * Dimming is scene rects around the selection, and a freeform line is
 * drawn in short pieces, so dragging never redraws anything big. While
 * it's up it has the pointer and the keys; a finger is the pointer, as
 * it is anywhere that isn't an app.
 */
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <linux/input-event-codes.h>
#include <wlr/types/wlr_output_layout.h>
#include <wlr/types/wlr_scene.h>
#include <wlr/util/box.h>
#include <wlr/util/log.h>
#include "server.h"

enum snip_button {
	SNIP_RECT,
	SNIP_FREE,
	SNIP_WINDOW,
	SNIP_FULL,
	SNIP_CLOSE,
	SNIP_BUTTONS,
};

#define BUTTON_W 52
#define BAR_H 44
#define BAR_TOP 12
#define PIECE 32 // freeform segments per line piece
#define MIN_STEP 2.0 // px between freeform points
#define MIN_SIZE 3 // a rectangle smaller than this was a click

struct point {
	double x, y;
};

static struct snip {
	struct c8_server *server;
	bool active;
	cairo_surface_t *image;
	struct wlr_box area; // layout coordinates the image covers
	double scale; // image pixels per layout pixel
	struct wlr_scene_tree *tree, *lines;
	struct wlr_scene_buffer *picture, *bar, *piece;
	struct wlr_scene_rect *dim[4], *edge[4];
	struct wlr_box bar_box;
	float bar_scale;
	int hover, pressed; // bar buttons, -1 for none
	bool dragging;
	double x0, y0;
	struct wlr_box sel; // undimmed, layout coordinates
	struct point *points;
	int npoints, cap, piece_start;
	/* Finished by a press: its release isn't for the app under it */
	bool eat_release;
} snip = { .hover = -1, .pressed = -1 };

/* Kept for next time, as Windows does; full screen isn't a mode */
static enum snip_button mode = SNIP_RECT;

bool c8_snip_active(struct c8_server *server) {
	return snip.active && snip.server == server;
}

/* Drawing */

static void draw_picture(cairo_t *cr, int w, int h, void *data) {
	cairo_scale(cr, 1 / snip.scale, 1 / snip.scale);
	cairo_set_source_surface(cr, snip.image, 0, 0);
	cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
	cairo_paint(cr);
}

/* The bar's glyphs, 20 px, white lines centred on cx, cy */
static void draw_glyph(cairo_t *cr, int which, double cx, double cy) {
	cairo_set_line_width(cr, 1.5);
	cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
	cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND);
	switch (which) {
	case SNIP_RECT: {
		double dash[] = { 3, 2.5 };
		cairo_set_dash(cr, dash, 2, 0);
		cairo_rectangle(cr, cx - 9.25, cy - 7.25, 18.5, 14.5);
		cairo_stroke(cr);
		cairo_set_dash(cr, NULL, 0, 0);
		break;
	}
	case SNIP_FREE:
		cairo_move_to(cr, cx - 2, cy - 8);
		cairo_curve_to(cr, cx + 7, cy - 9, cx + 11, cy - 2, cx + 6, cy + 3);
		cairo_curve_to(cr, cx + 2, cy + 7, cx - 3, cy + 9, cx - 7, cy + 6);
		cairo_curve_to(cr, cx - 11, cy + 2, cx - 9, cy - 7, cx - 2, cy - 8);
		cairo_stroke(cr);
		break;
	case SNIP_WINDOW:
		cairo_rectangle(cr, cx - 9.25, cy - 7.25, 18.5, 14.5);
		cairo_stroke(cr);
		cairo_rectangle(cr, cx - 9.25, cy - 7.25, 18.5, 4);
		cairo_fill(cr);
		break;
	case SNIP_FULL:
		for (int i = 0; i < 4; i++) {
			double sx = i & 1 ? 1 : -1, sy = i & 2 ? 1 : -1;
			cairo_move_to(cr, cx + sx * 9.25, cy + sy * 3);
			cairo_line_to(cr, cx + sx * 9.25, cy + sy * 7.25);
			cairo_line_to(cr, cx + sx * 4, cy + sy * 7.25);
		}
		cairo_stroke(cr);
		cairo_rectangle(cr, cx - 5, cy - 3.5, 10, 7);
		cairo_fill(cr);
		break;
	case SNIP_CLOSE:
		c8_cross_path(cr, cx, cy, 6);
		cairo_stroke(cr);
		break;
	}
}

static void draw_bar(cairo_t *cr, int w, int h, void *data) {
	struct c8_server *server = data;
	cairo_set_source_rgb(cr, 0x1f / 255.0, 0x1f / 255.0, 0x1f / 255.0);
	cairo_paint(cr);
	for (int i = 0; i < SNIP_BUTTONS; i++) {
		double x = i * BUTTON_W;
		if (i == (int)mode) {
			c8ui_set_source(cr, server->config.accent, 1);
			cairo_rectangle(cr, x, 0, BUTTON_W, h);
			cairo_fill(cr);
		}
		if (i == snip.hover) {
			cairo_set_source_rgba(cr, 1, 1, 1, i == snip.pressed ? 0.3 : 0.15);
			cairo_rectangle(cr, x, 0, BUTTON_W, h);
			cairo_fill(cr);
		}
		cairo_set_source_rgb(cr, 1, 1, 1);
		draw_glyph(cr, i, x + BUTTON_W / 2.0, h / 2.0);
	}
	/* Close stands apart from the modes */
	cairo_set_source_rgba(cr, 1, 1, 1, 0.25);
	cairo_rectangle(cr, SNIP_CLOSE * BUTTON_W, 8, 1, h - 16);
	cairo_fill(cr);
}

static void bar_redraw(void) {
	c8_scene_buffer_draw(snip.bar, snip.bar_box.width, snip.bar_box.height,
		snip.bar_scale, draw_bar, snip.server);
}

/* Dim all but sel, with a thin white edge round it */
static void set_selection(struct wlr_box sel) {
	struct wlr_box a = snip.area;
	if (!wlr_box_intersection(&sel, &sel, &a)) {
		sel = (struct wlr_box){ a.x, a.y, 0, 0 };
	}
	snip.sel = sel;
	struct wlr_box dims[4] = {
		{ a.x, a.y, a.width, sel.y - a.y }, // above
		{ a.x, sel.y + sel.height, a.width,
			a.y + a.height - sel.y - sel.height }, // below
		{ a.x, sel.y, sel.x - a.x, sel.height }, // left
		{ sel.x + sel.width, sel.y, a.x + a.width - sel.x - sel.width,
			sel.height }, // right
	};
	bool empty = wlr_box_empty(&sel);
	struct wlr_box edges[4] = {
		{ sel.x - 1, sel.y - 1, sel.width + 2, 1 },
		{ sel.x - 1, sel.y + sel.height, sel.width + 2, 1 },
		{ sel.x - 1, sel.y, 1, sel.height },
		{ sel.x + sel.width, sel.y, 1, sel.height },
	};
	for (int i = 0; i < 4; i++) {
		wlr_scene_node_set_position(&snip.dim[i]->node, dims[i].x, dims[i].y);
		wlr_scene_rect_set_size(snip.dim[i], MAX(dims[i].width, 0),
			MAX(dims[i].height, 0));
		wlr_scene_node_set_enabled(&snip.edge[i]->node, !empty);
		wlr_scene_node_set_position(&snip.edge[i]->node, edges[i].x,
			edges[i].y);
		wlr_scene_rect_set_size(snip.edge[i], edges[i].width,
			edges[i].height);
	}
}

static void clear_selection(void) {
	set_selection((struct wlr_box){ 0 });
}

/* Freeform: the line so far, in pieces of PIECE segments; only the last
 * piece is drawn again as the finger or mouse moves */
static void draw_piece(cairo_t *cr, int w, int h, void *data) {
	struct wlr_box *box = data;
	cairo_translate(cr, -box->x, -box->y);
	cairo_set_line_width(cr, 2);
	cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
	cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND);
	for (int i = MAX(snip.piece_start - 1, 0); i < snip.npoints; i++) {
		cairo_line_to(cr, snip.points[i].x, snip.points[i].y);
	}
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_stroke(cr);
}

/* The box round the points from one on */
static void points_bounds(int from, double *x1, double *y1, double *x2,
		double *y2) {
	*x1 = *y1 = INFINITY;
	*x2 = *y2 = -INFINITY;
	for (int i = from; i < snip.npoints; i++) {
		*x1 = MIN(*x1, snip.points[i].x);
		*y1 = MIN(*y1, snip.points[i].y);
		*x2 = MAX(*x2, snip.points[i].x);
		*y2 = MAX(*y2, snip.points[i].y);
	}
}

static void piece_redraw(void) {
	if (snip.piece == NULL) {
		snip.piece = c8_scene_buffer_create(snip.lines, NULL);
	}
	double x1, y1, x2, y2;
	points_bounds(MAX(snip.piece_start - 1, 0), &x1, &y1, &x2, &y2);
	struct wlr_box box = {
		(int)floor(x1) - 2, (int)floor(y1) - 2,
		(int)ceil(x2) - (int)floor(x1) + 4, (int)ceil(y2) - (int)floor(y1) + 4,
	};
	wlr_scene_node_set_position(&snip.piece->node, box.x, box.y);
	c8_scene_buffer_draw(snip.piece, box.width, box.height,
		(float)snip.scale, draw_piece, &box);
	if (snip.npoints - snip.piece_start >= PIECE) {
		snip.piece = NULL; // stays as it is; the next starts here
		snip.piece_start = snip.npoints;
	}
}

static void add_point(double x, double y) {
	if (snip.npoints > 0) {
		struct point *last = &snip.points[snip.npoints - 1];
		if (hypot(x - last->x, y - last->y) < MIN_STEP) {
			return;
		}
	}
	if (snip.npoints == snip.cap) {
		int cap = snip.cap ? snip.cap * 2 : 256;
		struct point *p = realloc(snip.points, cap * sizeof(*p));
		if (p == NULL) {
			return;
		}
		snip.points = p;
		snip.cap = cap;
	}
	snip.points[snip.npoints++] = (struct point){ x, y };
	piece_redraw();
}

static void clear_lines(void) {
	struct wlr_scene_node *node, *tmp;
	wl_list_for_each_safe(node, tmp, &snip.lines->children, link) {
		wlr_scene_node_destroy(node);
	}
	snip.piece = NULL;
	snip.npoints = snip.piece_start = 0;
}

/* Starting and ending */

static void end(void) {
	if (!snip.active) {
		return;
	}
	snip.active = false;
	wlr_scene_node_destroy(&snip.tree->node);
	snip.tree = NULL;
	cairo_surface_destroy(snip.image);
	snip.image = NULL;
	free(snip.points);
	snip.points = NULL;
	snip.npoints = snip.cap = snip.piece_start = 0;
	snip.piece = NULL;
	snip.dragging = false;
	c8_cursor_rebase(snip.server);
}

void c8_snip_cancel(struct c8_server *server) {
	if (c8_snip_active(server)) {
		end();
	}
}

static void finish(cairo_surface_t *image) {
	struct c8_server *server = snip.server;
	end();
	if (image) {
		c8_screenshot_snipped(server, image);
	}
}

static void finish_box(struct wlr_box box) {
	finish(c8_screenshot_crop(snip.image, snip.area, snip.scale, box));
}

/* The shape drawn, see-through outside it */
static void finish_free(void) {
	if (snip.npoints < 3) {
		clear_lines();
		return;
	}
	double x1, y1, x2, y2;
	points_bounds(0, &x1, &y1, &x2, &y2);
	struct wlr_box a = snip.area;
	x1 = MAX(floor(x1), a.x);
	y1 = MAX(floor(y1), a.y);
	x2 = MIN(ceil(x2), a.x + a.width);
	y2 = MIN(ceil(y2), a.y + a.height);
	int w = (int)((x2 - x1) * snip.scale + 0.5);
	int h = (int)((y2 - y1) * snip.scale + 0.5);
	if (w < MIN_SIZE || h < MIN_SIZE) {
		clear_lines();
		return;
	}
	cairo_surface_t *out = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
		w, h);
	if (cairo_surface_status(out) != CAIRO_STATUS_SUCCESS) {
		cairo_surface_destroy(out);
		finish(NULL);
		return;
	}
	cairo_t *cr = cairo_create(out);
	cairo_scale(cr, snip.scale, snip.scale);
	cairo_translate(cr, -x1, -y1);
	for (int i = 0; i < snip.npoints; i++) {
		cairo_line_to(cr, snip.points[i].x, snip.points[i].y);
	}
	cairo_close_path(cr);
	cairo_clip(cr);
	cairo_translate(cr, a.x, a.y);
	cairo_scale(cr, 1 / snip.scale, 1 / snip.scale);
	cairo_set_source_surface(cr, snip.image, 0, 0);
	cairo_paint(cr);
	cairo_destroy(cr);
	cairo_surface_flush(out);
	finish(out);
}

/* The app window under x, y, as the screens showed it */
static struct c8_view *view_at(struct c8_server *server, double x, double y) {
	if (server->start_visible) {
		return NULL;
	}
	double sx, sy;
	struct wlr_scene_node *node = wlr_scene_node_at(
		&server->layers.views->node, x, y, &sx, &sy);
	for (; node; node = node->parent ? &node->parent->node : NULL) {
		struct c8_node_desc *desc = node->data;
		if (desc && desc->type == C8_NODE_VIEW) {
			struct c8_view *view = desc->data;
			return view->mapped ? view : NULL;
		}
	}
	return NULL;
}

void c8_snip_start(struct c8_server *server) {
	if (snip.active || c8_locked(server)) {
		return;
	}
	struct wlr_box area;
	double scale;
	cairo_surface_t *image = c8_screenshot_capture(server, &area, &scale);
	if (image == NULL) {
		wlr_log(WLR_ERROR, "Snip: nothing to capture");
		return;
	}
	c8_chrome_hide(server);
	snip = (struct snip){
		.server = server, .active = true, .image = image, .area = area,
		.scale = scale, .hover = -1, .pressed = -1,
	};
	snip.tree = wlr_scene_tree_create(server->layers.snip);
	snip.picture = c8_scene_buffer_create(snip.tree, NULL);
	wlr_scene_node_set_position(&snip.picture->node, area.x, area.y);
	c8_scene_buffer_draw(snip.picture, area.width, area.height,
		(float)scale, draw_picture, NULL);
	for (int i = 0; i < 4; i++) {
		snip.dim[i] = wlr_scene_rect_create(snip.tree, 0, 0,
			(float[4]){ 0, 0, 0, 0.5f });
		snip.dim[i]->node.data = &c8_ui_desc;
	}
	for (int i = 0; i < 4; i++) {
		snip.edge[i] = wlr_scene_rect_create(snip.tree, 0, 0,
			(float[4]){ 1, 1, 1, 1 });
		snip.edge[i]->node.data = &c8_ui_desc;
	}
	snip.lines = wlr_scene_tree_create(snip.tree);

	/* The bar goes at the top of the screen with the pointer */
	struct wlr_output *output = wlr_output_layout_output_at(
		server->output_layout, server->cursor->x, server->cursor->y);
	struct wlr_box out = area;
	if (output) {
		wlr_output_layout_get_box(server->output_layout, output, &out);
	}
	snip.bar_scale = output ? output->scale : 1;
	snip.bar_box = (struct wlr_box){
		out.x + (out.width - SNIP_BUTTONS * BUTTON_W) / 2,
		out.y + BAR_TOP, SNIP_BUTTONS * BUTTON_W, BAR_H,
	};
	snip.bar = c8_scene_buffer_create(snip.tree, NULL);
	wlr_scene_node_set_position(&snip.bar->node, snip.bar_box.x,
		snip.bar_box.y);
	bar_redraw();
	clear_selection();
	c8_cursor_rebase(server);
}

/* Input */

static int button_at(double x, double y) {
	struct wlr_box *b = &snip.bar_box;
	if (!wlr_box_contains_point(b, x, y)) {
		return -1;
	}
	int i = (int)((x - b->x) / BUTTON_W);
	return i < SNIP_BUTTONS ? i : -1;
}

static struct wlr_box drag_box(double x, double y) {
	int x1 = (int)floor(MIN(snip.x0, x)), y1 = (int)floor(MIN(snip.y0, y));
	int x2 = (int)ceil(MAX(snip.x0, x)), y2 = (int)ceil(MAX(snip.y0, y));
	return (struct wlr_box){ x1, y1, x2 - x1, y2 - y1 };
}

const char *c8_snip_motion(struct c8_server *server, double x, double y) {
	if (snip.dragging) {
		if (mode == SNIP_RECT) {
			set_selection(drag_box(x, y));
		} else if (mode == SNIP_FREE) {
			add_point(x, y);
		}
		return "crosshair";
	}
	int hover = button_at(x, y);
	if (hover != snip.hover) {
		snip.hover = hover;
		bar_redraw();
	}
	if (hover >= 0) {
		return "default";
	}
	if (mode == SNIP_WINDOW && snip.pressed < 0) {
		struct c8_view *view = view_at(server, x, y);
		if (view) {
			set_selection(view->geo);
		} else {
			clear_selection();
		}
		return view ? "pointer" : "default";
	}
	return "crosshair";
}

static void bar_pressed(struct c8_server *server, int which) {
	switch (which) {
	case SNIP_CLOSE:
		end();
		return;
	case SNIP_FULL:
		finish_box(snip.area);
		return;
	default:
		mode = which;
		clear_selection();
		clear_lines();
		bar_redraw();
		/* Window mode lights up what's under the pointer at once */
		c8_snip_motion(server, server->cursor->x, server->cursor->y);
	}
}

bool c8_snip_button(struct c8_server *server, double x, double y,
		uint32_t button, bool pressed) {
	if (!c8_snip_active(server)) {
		if (snip.eat_release && !pressed) {
			snip.eat_release = false;
			return true;
		}
		snip.eat_release = false;
		return false;
	}
	if (button != BTN_LEFT) {
		return true;
	}
	if (pressed) {
		if (snip.dragging) {
			return true;
		}
		int at = button_at(x, y);
		if (at >= 0) {
			snip.pressed = at;
			bar_redraw();
			return true;
		}
		switch (mode) {
		case SNIP_RECT:
			snip.dragging = true;
			snip.x0 = x;
			snip.y0 = y;
			wlr_scene_node_set_enabled(&snip.bar->node, false);
			set_selection(drag_box(x, y));
			break;
		case SNIP_FREE:
			snip.dragging = true;
			wlr_scene_node_set_enabled(&snip.bar->node, false);
			clear_lines();
			add_point(x, y);
			break;
		case SNIP_WINDOW: {
			struct c8_view *view = view_at(server, x, y);
			if (view) {
				finish_box(view->geo);
				snip.eat_release = true;
			}
			break;
		}
		default:
			break;
		}
		return true;
	}

	if (snip.pressed >= 0) {
		int which = snip.pressed;
		snip.pressed = -1;
		if (button_at(x, y) == which) {
			bar_pressed(server, which);
		} else {
			bar_redraw();
		}
		return true;
	}
	if (!snip.dragging) {
		return true;
	}
	snip.dragging = false;
	wlr_scene_node_set_enabled(&snip.bar->node, true);
	if (mode == SNIP_RECT) {
		struct wlr_box box = drag_box(x, y);
		if (box.width >= MIN_SIZE && box.height >= MIN_SIZE) {
			finish_box(box);
		} else {
			clear_selection(); // just a click
		}
	} else if (mode == SNIP_FREE) {
		add_point(x, y);
		finish_free();
	}
	return true;
}

void c8_snip_key(struct c8_server *server, xkb_keysym_t sym) {
	if (sym == XKB_KEY_Escape) {
		end();
	}
}
