/*
 * Desktop notifications: the shell serves org.freedesktop.Notifications
 * and shows each one as a toast in a corner of the screen (the top right
 * unless the [notifications] corner setting says otherwise). A
 * toast wears the colour of the app's tile (the accent if it has none),
 * slides in from its side, and goes after a while unless the pointer
 * rests on it. Clicking it opens the app; dragging or swiping it towards
 * its edge (a finger, or two on the touchpad), or its close button,
 * dismisses it.
 *
 * In XR they line up side by side along the bottom of the
 * screen, which the compositor keeps at the bottom of your view: they
 * rise in from below it and sink away.
 */
#define _GNU_SOURCE
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <gio/gio.h>
#include <gio/gdesktopappinfo.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include "shell.h"
#include "pixels.h"
#include "status.h"

#define TOAST_W 364
#define TOAST_MARGIN 24 // from the screen's top and right
#define TOAST_GAP 8
#define TOAST_PAD 14
#define TOAST_IMAGE 64
#define TOAST_ICON 44
#define TOAST_CLOSE 30
#define TOAST_ACTION_H 32
#define TOAST_MAX_SHOWN 3 // of each: critical ones queue apart
#define TOAST_TIMEOUT_MS 7000
#define TOAST_SLIDE_MS 260
#define TOAST_MOVE_MS 200
#define DRAG_START 8 // px before a press becomes a drag
#define FLING_SPEED 0.6 // px/ms towards the edge: let go so fast, it goes
#define FLING_STALE 80 // ms held still before letting go: no fling
#define BODY_LINES 3
#define ASK_LINES 14 // a question says all of what it asks
#define CRITICAL_RED 0xe51400 // Metro red

enum close_reason {
	CLOSED_EXPIRED = 1,
	CLOSED_DISMISSED = 2,
	CLOSED_BY_CALL = 3,
	CLOSED_UNDEFINED = 4,
};

struct toast {
	struct wl_list link; // n.toasts, oldest first
	uint32_t id;
	char *app_name, *summary, *body, *desktop_entry;
	char **actions; // key, label, key, label…
	int action_count; // pairs, not counting "default"
	bool has_default, resident, critical;
	int32_t timeout; // ms, 0 for until dismissed
	/* A question from the shell itself (notify_ask), not yet answered */
	notify_ask_fn ask_fn;
	void *ask_data;
	/* The shell's own (a question, the battery): nothing on the bus may
	 * replace or close it, or an app could reword a question and have
	 * the answer count for the one that was asked */
	bool ours;
	bool question; // all of its body shows (ASK_LINES)

	/* What it shows on the left: a picture fills the square, an icon
	 * sits in it */
	cairo_surface_t *image;
	struct c8ui_icon *icon;

	struct shell_surface *surface;
	struct c8ui_widget *w;
	int height;
	bool shown, leaving;
	/* Sliding: 0 is in place, 1 off to the right */
	double slide, slide_from, slide_to;
	int64_t slide_start;
	double y, y_from, y_to; // top, in output coordinates
	double x, x_from, x_to; // left, without the slide or a drag
	int64_t move_start;

	guint expire;
	int64_t expire_at, remaining;

	/* A press or finger, until it lets go */
	bool down, dragging;
	double down_x, drag; // output x where it went down, px moved to the edge
	double down_y; // output y where it went down
	double drag_base; // the drag it was pressed at (mid-swipe)
	bool sinking; // in a row, dragged down rather than sideways
	double swipe; // touchpad scroll so far, px
	double speed; // of the drag or swipe towards the edge, px/ms
	double speed_drag; // the drag when speed was last worked out
	int64_t speed_at;
	double last_x, last_y; // a finger's, on the toast
	int32_t finger; // -1 for the pointer
};

static struct {
	GDBusConnection *bus;
	guint owner, object;
	uint32_t next_id;
	struct wl_list toasts;
	guint anim;
	int64_t quiet_until; // real time, µs; 0: toasts show
	bool right, bottom; // the corner they gather in
	int battery_warned; // the lowest level warned of since charging
	uint32_t battery_id; // its toast
	bool from_bus; // notify() is running for a bus call
	bool asking; // … or for notify_ask
} n;

/* Side by side along the bottom, in XR */
static bool row(void) {
	return shell.appearance.xr;
}

/* +1 when toasts sit at the right edge (they leave to the right); in a
 * row they're thrown away to the right too */
static int side(void) {
	return n.right || row() ? 1 : -1;
}

/* Where a toast's left edge rests in the corner */
static double corner_x(void) {
	return n.right ? shell.output_width - TOAST_MARGIN - TOAST_W :
		TOAST_MARGIN;
}

static void read_corner(void) {
	const char *v = shell.appearance.notification_corner;
	n.right = v == NULL || strstr(v, "left") == NULL;
	n.bottom = v != NULL && strstr(v, "bottom") != NULL;
}

static void layout_toasts(void);
static void start_animating(void);
static void close_toast(struct toast *t, enum close_reason reason);

/* What the toast is for: the app's tile, its window, its desktop entry */

static const char *app_key(struct toast *t) {
	return t->desktop_entry ? t->desktop_entry : t->app_name;
}

static uint32_t toast_color(struct toast *t) {
	struct tile *tile = tile_for_app(app_key(t));
	if (tile == NULL && t->desktop_entry && t->app_name) {
		tile = tile_for_app(t->app_name);
	}
	return tile ? tile_color(tile) : app_color(app_key(t));
}

static struct window *toast_window(struct toast *t) {
	const char *keys[] = { t->desktop_entry, t->app_name };
	for (int i = 0; i < 2; i++) {
		if (keys[i] == NULL) {
			continue;
		}
		struct window *win;
		wl_list_for_each(win, &shell.windows, link) {
			if (win->app_id && strcasecmp(win->app_id, keys[i]) == 0) {
				return win;
			}
		}
	}
	return NULL;
}

/* Signals */

static void emit(const char *signal, GVariant *args) {
	if (n.bus) {
		g_dbus_connection_emit_signal(n.bus, NULL,
			"/org/freedesktop/Notifications", "org.freedesktop.Notifications",
			signal, args, NULL);
	}
}

/* Answers a question once, whichever way the toast ends */
static void answer(struct toast *t, bool yes) {
	notify_ask_fn fn = t->ask_fn;
	if (fn) {
		t->ask_fn = NULL;
		fn(yes, t->ask_data);
	}
}

static void invoke(struct toast *t, const char *key) {
	if (t->ask_fn) {
		answer(t, strcmp(key, "yes") == 0);
	}
	emit("ActionInvoked", g_variant_new("(us)", t->id, key));
}

/* Clicked: the default action if there is one, and the app comes to the
 * front either way */
static void activate(struct toast *t) {
	if (t->has_default) {
		invoke(t, "default");
	}
	struct window *win = toast_window(t);
	if (win) {
		c8_shell_window_v1_activate(win->proto);
	} else if (!t->has_default && t->desktop_entry) {
		char *file = g_strconcat(t->desktop_entry, ".desktop", NULL);
		GDesktopAppInfo *info = g_desktop_app_info_new(file);
		if (info) {
			g_app_info_launch(G_APP_INFO(info), NULL, NULL, NULL);
			g_object_unref(info);
		}
		g_free(file);
	}
	/* Critical ones only go when swiped or closed */
	if (!t->resident && !t->critical) {
		close_toast(t, CLOSED_DISMISSED);
	}
}

/* Expiring, paused while the pointer is on it */

static gboolean expired(gpointer data) {
	struct toast *t = data;
	t->expire = 0;
	close_toast(t, CLOSED_EXPIRED);
	return G_SOURCE_REMOVE;
}

static void expire_stop(struct toast *t) {
	if (t->expire) {
		g_source_remove(t->expire);
		t->expire = 0;
		t->remaining = t->expire_at - now_ms();
	}
}

static void expire_start(struct toast *t, int64_t ms) {
	expire_stop(t);
	if (t->timeout <= 0 || t->leaving) {
		return;
	}
	t->expire_at = now_ms() + ms;
	t->expire = g_timeout_add(ms, expired, t);
}

/* After the pointer or a finger leaves: a moment left to read it */
static void expire_resume(struct toast *t) {
	expire_start(t, t->remaining < 1500 ? 1500 : t->remaining);
}

/* Drawing */

static double text_x(struct toast *t) {
	return t->image || t->icon ? TOAST_PAD + TOAST_IMAGE + 12 : TOAST_PAD;
}

static double text_width(struct toast *t) {
	return TOAST_W - text_x(t) - TOAST_PAD - TOAST_CLOSE / 2;
}

static int body_lines(struct toast *t) {
	return t->question ? ASK_LINES : BODY_LINES;
}

static const char *body_text(struct toast *t) {
	return t->body && t->body[0] ? t->body : NULL;
}

static int measure(struct toast *t, const char *family) {
	struct c8ui_font title = c8ui_text_font(C8UI_TEXT_BODY_STRONG);
	struct c8ui_font body = c8ui_text_font(C8UI_TEXT_BODY);
	double w, th = 0, bh = 0;
	const char *b = body_text(t);
	c8ui_text_size(family, title, t->summary, text_width(t), b ? 1 : 2, &w,
		&th);
	if (b) {
		c8ui_text_size(family, body, b, text_width(t), body_lines(t), &w, &bh);
		bh += 2;
	}
	double h = th + bh;
	if ((t->image || t->icon) && h < TOAST_IMAGE) {
		h = TOAST_IMAGE;
	}
	h += 2 * TOAST_PAD;
	if (t->action_count > 0) {
		h += TOAST_ACTION_H + TOAST_PAD - 4;
	}
	return (int)ceil(h);
}

static struct c8ui_rect close_rect(void) {
	return (struct c8ui_rect){ TOAST_W - TOAST_CLOSE - 2, 2, TOAST_CLOSE,
		TOAST_CLOSE };
}

static struct c8ui_rect action_rect(struct toast *t, int i) {
	double w = (TOAST_W - 2 * TOAST_PAD - (t->action_count - 1) * 8.0) /
		t->action_count;
	return (struct c8ui_rect){ TOAST_PAD + i * (w + 8),
		t->height - TOAST_PAD - TOAST_ACTION_H, w, TOAST_ACTION_H };
}

/* The label of the i-th action other than "default" */
static const char *action_label(struct toast *t, int i, const char **key) {
	for (int k = 0; t->actions && t->actions[k] && t->actions[k + 1]; k += 2) {
		if (strcmp(t->actions[k], "default") == 0) {
			continue;
		}
		if (i-- == 0) {
			if (key) {
				*key = t->actions[k];
			}
			return t->actions[k + 1];
		}
	}
	return NULL;
}

static void draw_image(cairo_t *cr, cairo_surface_t *img, double x, double y,
		double size) {
	/* Covers the square, cut to it */
	c8ui_draw_surface_cover(cr, img, x, y, size, size);
}

static void toast_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct toast *t = w->data;
	const char *family = c8ui_widget_font(w);
	bool pressed = t->down && !t->dragging;
	if (t->critical) {
		/* Critical ones stand out: black, edged in red */
		c8ui_set_source(cr, pressed ? 0x262626 : 0x000000, 1);
		cairo_paint(cr);
		c8ui_set_source(cr, CRITICAL_RED, 1);
		cairo_set_line_width(cr, 3);
		cairo_rectangle(cr, 1.5, 1.5, TOAST_W - 3, t->height - 3);
		cairo_stroke(cr);
	} else {
		uint32_t rgb = toast_color(t);
		c8ui_set_source(cr, pressed ? c8ui_shade(rgb, 0.85) : rgb, 1);
		cairo_paint(cr);
		/* Metro's thin lighter edge */
		c8ui_set_source(cr, c8ui_shade(rgb, 1.3), 1);
		cairo_set_line_width(cr, 2);
		cairo_rectangle(cr, 1, 1, TOAST_W - 2, t->height - 2);
		cairo_stroke(cr);
	}

	double y = TOAST_PAD;
	if (t->image) {
		draw_image(cr, t->image, TOAST_PAD, y, TOAST_IMAGE);
	} else if (t->icon) {
		c8ui_icon_draw_fit(cr, t->icon, TOAST_PAD + TOAST_IMAGE / 2.0,
			y + TOAST_IMAGE / 2.0, TOAST_ICON);
	}

	const char *b = body_text(t);
	cairo_set_source_rgb(cr, 1, 1, 1);
	y += c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_BODY_STRONG),
		t->summary, text_x(t), y, text_width(t), b ? 1 : 2);
	if (b) {
		cairo_set_source_rgba(cr, 1, 1, 1, 0.85);
		c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_BODY), b,
			text_x(t), y + 2, text_width(t), body_lines(t));
	}

	for (int i = 0; i < t->action_count; i++) {
		struct c8ui_rect r = action_rect(t, i);
		cairo_set_source_rgba(cr, 1, 1, 1, 0.15);
		cairo_rectangle(cr, r.x, r.y, r.width, r.height);
		cairo_fill(cr);
		cairo_set_source_rgb(cr, 1, 1, 1);
		cairo_set_line_width(cr, 2);
		cairo_rectangle(cr, r.x + 1, r.y + 1, r.width - 2, r.height - 2);
		cairo_stroke(cr);
		struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY);
		const char *label = action_label(t, i, NULL);
		double tw, th;
		c8ui_text_size(family, font, label, r.width - 12, 1, &tw, &th);
		c8ui_text_draw(cr, family, font, label, r.x + (r.width - tw) / 2,
			r.y + (r.height - th) / 2, r.width - 12, 1);
	}

	/* The close button shows while the pointer is on the toast */
	if (w->hovered && !t->dragging) {
		struct c8ui_rect r = close_rect();
		double cx = r.x + r.width / 2, cy = r.y + r.height / 2;
		cairo_set_source_rgba(cr, 1, 1, 1, 0.9);
		cairo_set_line_width(cr, 1.5);
		cairo_move_to(cr, cx - 5, cy - 5);
		cairo_line_to(cr, cx + 5, cy + 5);
		cairo_move_to(cr, cx + 5, cy - 5);
		cairo_line_to(cr, cx - 5, cy + 5);
		cairo_stroke(cr);
	}
}

/* Input: a click opens the app; pressing and pulling to the right, by
 * pointer or finger, throws the toast away */

static void place(struct toast *t);
static void track_speed(struct toast *t);

/* How far a toast moves to be gone, the way it's being dragged: off to
 * the side, or in a row down below the screen */
static double drag_span(struct toast *t) {
	return t->sinking ? t->height + TOAST_MARGIN : TOAST_W + TOAST_MARGIN;
}

/* Let go short of throwing it away: back in place. The drag becomes the
 * slide, which is sideways in the corner and up and down in a row; a
 * row's sideways drag is put back at once. */
static void spring_back(struct toast *t) {
	if (row() && !t->sinking) {
		t->drag = 0;
		place(t);
		return;
	}
	t->slide = t->slide_from = t->drag / drag_span(t);
	t->sinking = false;
	t->drag = 0;
	t->slide_to = 0;
	t->slide_start = now_ms();
	start_animating();
}

static void press(struct toast *t, double x, double y, int32_t finger) {
	t->down = true;
	t->dragging = false;
	t->finger = finger;
	/* The compositor gives a held press's positions relative to where
	 * the toast was when it went down (c8's implicit grab, touch and
	 * the XR ray alike), so they don't move with the drag */
	t->down_x = x;
	t->down_y = y;
	t->drag_base = t->drag;
	c8ui_widget_queue_draw(t->w);
}

/* Towards the edge, or in a row (XR) down too, the way it first goes
 * further: toasts there sink away below the view */
static void drag_to(struct toast *t, double x, double y) {
	double dx = (x - t->down_x) * side();
	double dy = y - t->down_y;
	if (!t->dragging && (dx > DRAG_START ||
			(row() && dy > DRAG_START))) {
		t->dragging = true;
		if (t->drag_base == 0) {
			t->sinking = row() && dy > dx;
		}
		t->swipe = 0;
		expire_stop(t);
		c8ui_widget_queue_draw(t->w);
	}
	if (t->dragging) {
		double d = t->drag_base + (t->sinking ? dy : dx);
		t->drag = d > 0 ? d : 0;
		track_speed(t);
		place(t);
	}
}

/* How fast it's being moved, smoothed over the last few events */
static void track_speed(struct toast *t) {
	int64_t now = now_ms();
	int64_t dt = now - t->speed_at;
	if (t->speed_at == 0 || dt > FLING_STALE) {
		t->speed = 0;
	} else if (dt > 0) {
		double v = (t->drag - t->speed_drag) / dt;
		t->speed = 0.6 * v + 0.4 * t->speed;
	}
	if (dt > 0 || t->speed_at == 0) {
		t->speed_at = now;
		t->speed_drag = t->drag;
	}
}

/* Dragged or swiped, then let go: far enough, or thrown towards the
 * edge, and it's dismissed, else it goes back */
static void let_go(struct toast *t) {
	bool thrown = t->drag > DRAG_START && t->speed > FLING_SPEED &&
		now_ms() - t->speed_at <= FLING_STALE;
	t->speed = 0;
	t->speed_at = 0;
	if (t->drag > (drag_span(t) - TOAST_MARGIN) / 3.0 || thrown) {
		close_toast(t, CLOSED_DISMISSED);
	} else {
		spring_back(t);
		if (!t->w->hovered) {
			expire_resume(t);
		}
	}
}

static void release(struct toast *t, double x, double y, bool tap) {
	bool dragged = t->dragging;
	t->down = false;
	t->dragging = false;
	c8ui_widget_queue_draw(t->w);
	if (dragged) {
		let_go(t);
		return;
	}
	if (!tap) {
		return;
	}
	struct c8ui_rect cr = close_rect();
	if (t->finger < 0 && c8ui_rect_contains(&cr, x, y)) {
		close_toast(t, CLOSED_DISMISSED);
		return;
	}
	for (int i = 0; i < t->action_count; i++) {
		struct c8ui_rect r = action_rect(t, i);
		const char *key;
		if (c8ui_rect_contains(&r, x, y) && action_label(t, i, &key)) {
			invoke(t, key);
			if (!t->resident) {
				close_toast(t, CLOSED_DISMISSED);
			}
			return;
		}
	}
	activate(t);
}

static bool toast_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct toast *t = w->data;
	if (t->leaving) {
		return true;
	}
	switch (ev->type) {
	case C8UI_EVENT_ENTER:
		expire_stop(t);
		return true;
	case C8UI_EVENT_LEAVE:
		if (!t->down) {
			expire_resume(t);
		}
		return true;
	case C8UI_EVENT_PRESS:
		if (ev->button == C8UI_BUTTON_LEFT) {
			press(t, ev->x, ev->y, -1);
		} else if (ev->button == C8UI_BUTTON_RIGHT) {
			close_toast(t, CLOSED_DISMISSED);
		}
		return true;
	case C8UI_EVENT_MOTION:
		if (t->down && t->finger < 0) {
			drag_to(t, ev->x, ev->y);
		}
		return true;
	case C8UI_EVENT_RELEASE:
		if (t->down && t->finger < 0 && ev->button == C8UI_BUTTON_LEFT) {
			struct c8ui_rect r = { 0, 0, TOAST_W, t->height };
			release(t, ev->x, ev->y, c8ui_rect_contains(&r, ev->x, ev->y));
		}
		return true;
	case C8UI_EVENT_SCROLL:
		/* Two fingers on the touchpad, sideways (or in a row, down too,
		 * whichever they first go): the toast follows them, either way
		 * they go (natural scrolling flips the sign) */
		if (!ev->precise || t->down) {
			return false;
		}
		if (t->swipe == 0) {
			bool across = fabs(ev->dx) > fabs(ev->dy);
			if (!across && !row()) {
				return false;
			}
			t->sinking = !across;
		}
		t->swipe += t->sinking ? ev->dy : ev->dx;
		expire_stop(t);
		t->drag = fabs(t->swipe);
		track_speed(t);
		place(t);
		return true;
	case C8UI_EVENT_SCROLL_STOP:
		if (t->swipe == 0) {
			return false;
		}
		t->swipe = 0;
		let_go(t);
		return true;
	case C8UI_EVENT_TOUCH_DOWN:
		if (t->down) {
			return false;
		}
		expire_stop(t);
		press(t, ev->x, ev->y, ev->touch_id);
		t->last_x = ev->x;
		t->last_y = ev->y;
		return true;
	case C8UI_EVENT_TOUCH_MOTION:
		if (t->down && t->finger == ev->touch_id) {
			t->last_x = ev->x;
			t->last_y = ev->y;
			drag_to(t, ev->x, ev->y);
		}
		return true;
	case C8UI_EVENT_TOUCH_UP:
		if (t->down && t->finger == ev->touch_id) {
			release(t, t->last_x, t->last_y, true);
			if (!t->leaving) {
				expire_resume(t);
			}
		}
		return true;
	case C8UI_EVENT_TOUCH_CANCEL:
		if (t->down && t->finger >= 0) {
			release(t, 0, 0, false);
			expire_resume(t);
		}
		return true;
	default:
		return false;
	}
}

static void toast_widget_destroy(struct c8ui_widget *w) {
	struct toast *t = w->data;
	if (t) {
		t->w = NULL;
	}
}

static const struct c8ui_widget_impl toast_impl = {
	.name = "toast",
	.draw = toast_draw,
	.event = toast_event,
	.destroy = toast_widget_destroy,
};

/* Placing and animating */

static void place(struct toast *t) {
	if (row()) {
		/* Rises from below the screen's bottom edge, sideways when
		 * dragged */
		int down = (int)lround(t->slide * (t->height + TOAST_MARGIN));
		int dx = t->sinking ? 0 : (int)lround(t->drag);
		int dy = t->sinking ? (int)lround(t->drag) : 0;
		shell_surface_set_rect(t->surface, (int)lround(t->x) + dx,
			(int)lround(t->y) + down + dy, TOAST_W, t->height);
		return;
	}
	/* Slides out past the screen's edge */
	int off = (int)lround(t->slide * (TOAST_W + TOAST_MARGIN) + t->drag);
	shell_surface_set_rect(t->surface, (int)lround(t->x) + off * side(),
		(int)lround(t->y), TOAST_W, t->height);
}

static bool step(struct toast *t, int64_t now) {
	bool moving = false;
	double s = ease_out((double)(now - t->slide_start) / TOAST_SLIDE_MS);
	double slide = t->slide_from + (t->slide_to - t->slide_from) * s;
	double m = ease_out((double)(now - t->move_start) / TOAST_MOVE_MS);
	double y = t->y_from + (t->y_to - t->y_from) * m;
	double x = t->x_from + (t->x_to - t->x_from) * m;
	if (slide != t->slide || y != t->y || x != t->x) {
		t->slide = slide;
		t->y = y;
		t->x = x;
		place(t);
	}
	moving = s < 1 || m < 1;
	return moving;
}

/* What it says and shows, for new content or for good */
static void free_content(struct toast *t) {
	free(t->app_name);
	free(t->summary);
	free(t->body);
	free(t->desktop_entry);
	g_strfreev(t->actions);
	if (t->image) {
		cairo_surface_destroy(t->image);
		t->image = NULL;
	}
	c8ui_icon_destroy(t->icon);
	t->icon = NULL;
}

static void free_toast(struct toast *t) {
	expire_stop(t);
	wl_list_remove(&t->link);
	if (t->w) {
		t->w->data = NULL;
	}
	shell_surface_destroy(t->surface);
	free_content(t);
	free(t);
}

static gboolean animate(gpointer data) {
	int64_t now = now_ms();
	bool more = false;
	struct toast *t, *tmp;
	wl_list_for_each_safe(t, tmp, &n.toasts, link) {
		if (!t->shown) {
			continue;
		}
		bool moving = step(t, now);
		if (t->leaving && !moving) {
			free_toast(t);
			continue;
		}
		more |= moving;
	}
	if (!more) {
		n.anim = 0;
		/* Ones that went make room for ones waiting */
		layout_toasts();
		return G_SOURCE_REMOVE;
	}
	return G_SOURCE_CONTINUE;
}

static void start_animating(void) {
	if (n.anim == 0) {
		n.anim = g_timeout_add(16, animate, NULL);
	}
}

/* Top of a toast whose edge is `off` from the screen's top or bottom */
static double top_for(struct toast *t, double off) {
	return n.bottom ? shell.output_height - off - t->height : off;
}

/* Made and measured, sliding in; the caller says where it rests (top
 * from its height) and places it */
static void show_toast(struct toast *t) {
	t->surface = shell_surface_new(C8_SHELL_V1_ROLE_OSD);
	t->w = c8ui_widget_new(&toast_impl, t);
	t->w->fill = true;
	t->w->expand = true;
	t->w->cursor = C8UI_CURSOR_POINTER;
	c8ui_widget_set_scheme(t->w, C8UI_SCHEME_DARK);
	c8ui_root_set_child(shell_surface_root(t->surface), t->w);
	t->height = measure(t, c8ui_widget_font(t->w));
	t->shown = true;
	t->slide = t->slide_from = 1;
	t->slide_to = 0;
	t->slide_start = t->move_start = now_ms();
	expire_start(t, t->timeout);
}

static void rest_at(struct toast *t, double x, double y) {
	t->x = t->x_from = t->x_to = x;
	t->y = t->y_from = t->y_to = y;
	place(t);
}

/* Moves a shown toast to rest at x, y */
static bool move_to(struct toast *t, double x, double y, int64_t now) {
	if (t->x_to == x && t->y_to == y) {
		return false;
	}
	t->x_from = t->x;
	t->y_from = t->y;
	t->x_to = x;
	t->y_to = y;
	t->move_start = now;
	return true;
}

/* XR: side by side along the bottom, centred, critical ones
 * first (left), each queue as many as before; the rest wait */
static void layout_row(void) {
	struct toast *in[2 * TOAST_MAX_SHOWN];
	int count = 0;
	int room = (shell.output_width - TOAST_MARGIN) / (TOAST_W + TOAST_GAP);
	for (int pass = 0; pass < 2; pass++) {
		bool critical = pass == 0;
		int shown = 0;
		struct toast *t;
		wl_list_for_each(t, &n.toasts, link) {
			if (t->leaving || t->critical != critical) {
				continue;
			}
			if (shown >= TOAST_MAX_SHOWN || count >= room) {
				break; // the rest of this queue waits
			}
			in[count++] = t;
			shown++;
		}
	}
	double x = (shell.output_width - count * TOAST_W -
		(count - 1) * TOAST_GAP) / 2.0;
	int64_t now = now_ms();
	for (int i = 0; i < count; i++) {
		struct toast *t = in[i];
		if (!t->shown) {
			show_toast(t);
			rest_at(t, x, shell.output_height - TOAST_MARGIN - t->height);
		} else {
			move_to(t, x, shell.output_height - TOAST_MARGIN - t->height,
				now);
		}
		x += TOAST_W + TOAST_GAP;
	}
	if (count > 0) {
		start_animating();
	}
}

/* Top of the toasts' row in XR (the level box goes above it),
 * or of where it would be */
int notify_row_top(void) {
	int top = shell.output_height - TOAST_MARGIN;
	struct toast *t;
	if (n.toasts.next == NULL) {
		return top;
	}
	wl_list_for_each(t, &n.toasts, link) {
		if (t->shown && !t->leaving && t->y_to < top) {
			top = (int)t->y_to;
		}
	}
	return top;
}

/* Stacks the shown toasts down from the top; brings in ones waiting
 * while there is room */
static void layout_toasts(void) {
	/* Kept for after unlocking, not shown to nobody */
	if (shell.locked) {
		return;
	}
	if (shell.output_width <= 0) {
		/* Start hasn't been told the screen's size yet:
		 * notify_output_changed comes back here */
		return;
	}
	if (row()) {
		layout_row();
		return;
	}
	double y = TOAST_MARGIN; // from the edge the stack starts at
	bool moved = false;
	int64_t now = now_ms();
	/* Two queues, each with its own slots: critical ones nearest the
	 * corner, so they never wait behind (or take a place from) the rest */
	for (int pass = 0; pass < 2; pass++) {
		bool critical = pass == 0;
		int shown = 0;
		bool full = false; // the rest of this queue waits
		struct toast *t;
		wl_list_for_each(t, &n.toasts, link) {
			if (t->leaving || t->critical != critical) {
				continue;
			}
			if (!t->shown) {
				if (full || shown >= TOAST_MAX_SHOWN ||
						y + measure(t, shell.appearance.font) >
						shell.output_height) {
					full = true;
					continue;
				}
				show_toast(t);
				rest_at(t, corner_x(), top_for(t, y));
				moved = true;
			} else if (move_to(t, corner_x(), top_for(t, y), now)) {
				moved = true;
			}
			y += t->height + TOAST_GAP;
			shown++;
		}
	}
	if (moved) {
		start_animating();
	}
}

static void close_toast(struct toast *t, enum close_reason reason) {
	if (t->leaving) {
		return;
	}
	answer(t, false);
	emit("NotificationClosed", g_variant_new("(uu)", t->id, reason));
	if (!t->shown) {
		free_toast(t);
		return;
	}
	expire_stop(t);
	t->leaving = true;
	t->down = t->dragging = false;
	/* Leaves from where a drag let go of it (in a row it sinks from
	 * there) */
	if (t->sinking) {
		double span = t->height + TOAST_MARGIN;
		t->slide = (t->slide * span + t->drag) / span;
		t->drag = 0;
		t->sinking = false;
	} else if (!row()) {
		t->slide = t->slide_from = (t->slide * (TOAST_W + TOAST_MARGIN) +
			t->drag) / (TOAST_W + TOAST_MARGIN);
		t->drag = 0;
	}
	t->slide_from = t->slide;
	t->slide_to = 1;
	t->slide_start = now_ms();
	start_animating();
	layout_toasts();
}

/* Reading a notification */

static struct toast *find(uint32_t id) {
	struct toast *t;
	wl_list_for_each(t, &n.toasts, link) {
		if (t->id == id && !t->leaving) {
			return t;
		}
	}
	return NULL;
}

/* image-data: (iiibiiay) width, height, rowstride, alpha, bits, channels */
static cairo_surface_t *image_from_data(GVariant *v) {
	if (!g_variant_is_of_type(v, G_VARIANT_TYPE("(iiibiiay)"))) {
		return NULL;
	}
	gint32 w, h, stride, bits, channels;
	gboolean alpha;
	GVariant *bytes;
	g_variant_get(v, "(iiibii@ay)", &w, &h, &stride, &alpha, &bits,
		&channels, &bytes);
	gsize len;
	const guchar *src = g_variant_get_fixed_array(bytes, &len, 1);
	cairo_surface_t *img = NULL;
	if (w > 0 && h > 0 && w <= 4096 && h <= 4096 && bits == 8 &&
			channels == (alpha ? 4 : 3) && stride >= w * channels &&
			len >= (gsize)stride * (h - 1) + (gsize)w * channels) {
		img = c8ui_surface_from_pixels(src, w, h, stride, channels);
	}
	g_variant_unref(bytes);
	return img;
}

/* A path, file:// URI or icon name */
static struct c8ui_icon *load_icon(const char *ref) {
	if (ref == NULL || ref[0] == '\0') {
		return NULL;
	}
	char *path = NULL;
	if (g_str_has_prefix(ref, "file://")) {
		path = g_filename_from_uri(ref, NULL, NULL);
		if (path == NULL) {
			return NULL;
		}
		ref = path;
	}
	struct c8ui_icon *icon = c8ui_icon_load(shell.appearance.icon_theme, ref);
	g_free(path);
	return icon;
}

/* Pictures (a photo, album art) fill the square, so files that aren't
 * icons are read as images */
static cairo_surface_t *load_picture(const char *ref) {
	char *path = g_str_has_prefix(ref, "file://") ?
		g_filename_from_uri(ref, NULL, NULL) : g_strdup(ref);
	cairo_surface_t *img = NULL;
	if (path && path[0] == '/' && !g_str_has_suffix(path, ".svg")) {
		/* Big enough for the square at any scale */
		img = image_from_pixbuf(gdk_pixbuf_new_from_file_at_size(path, 256,
			256, NULL));
	}
	g_free(path);
	return img;
}

static struct c8ui_icon *desktop_icon(const char *desktop_entry) {
	if (desktop_entry == NULL) {
		return NULL;
	}
	struct tile *tile = tile_for_app(desktop_entry);
	if (tile && tile->icon) {
		return load_icon(tile->icon);
	}
	char *file = g_strconcat(desktop_entry, ".desktop", NULL);
	GDesktopAppInfo *info = g_desktop_app_info_new(file);
	g_free(file);
	struct c8ui_icon *icon = NULL;
	if (info) {
		char *name = g_desktop_app_info_get_string(info, "Icon");
		icon = load_icon(name);
		g_free(name);
		g_object_unref(info);
	}
	return icon;
}

static void set_picture(struct toast *t, const char *app_icon, GVariant *hints) {
	GVariant *v;
	const char *s;
	/* In the spec's order: image-data, image-path, app_icon, icon_data */
	if ((v = g_variant_lookup_value(hints, "image-data", NULL)) ||
			(v = g_variant_lookup_value(hints, "image_data", NULL))) {
		t->image = image_from_data(v);
		g_variant_unref(v);
		if (t->image) {
			return;
		}
	}
	if (g_variant_lookup(hints, "image-path", "&s", &s) ||
			g_variant_lookup(hints, "image_path", "&s", &s)) {
		if ((t->image = load_picture(s)) || (t->icon = load_icon(s))) {
			return;
		}
	}
	if (app_icon && app_icon[0]) {
		if (strchr(app_icon, '/') && (t->image = load_picture(app_icon))) {
			return;
		}
		if ((t->icon = load_icon(app_icon))) {
			return;
		}
	}
	if ((v = g_variant_lookup_value(hints, "icon_data", NULL))) {
		t->image = image_from_data(v);
		g_variant_unref(v);
		if (t->image) {
			return;
		}
	}
	t->icon = desktop_icon(t->desktop_entry);
}

static char *dup_nonempty(const char *s) {
	return s && s[0] ? strdup(s) : NULL;
}

/* After the reply, so the app knows the id it's told about */
static gboolean closed_unseen(gpointer data) {
	emit("NotificationClosed", g_variant_new("(uu)", GPOINTER_TO_UINT(data),
		CLOSED_UNDEFINED));
	return G_SOURCE_REMOVE;
}

static uint32_t notify(const char *app_name, uint32_t replaces,
		const char *app_icon, const char *summary, const char *body,
		const char **actions, GVariant *hints, int32_t timeout,
		bool even_hidden) {
	struct toast *t = replaces ? find(replaces) : NULL;
	if (t && n.from_bus && t->ours) {
		t = NULL; // not theirs to replace: a toast of its own
	}
	bool replacing = t != NULL;
	/* Hidden for a while: new ones are let go unseen, but not critical
	 * ones (the battery running out) */
	guchar urgency = 1;
	g_variant_lookup(hints, "urgency", "y", &urgency);
	if (!replacing && urgency < 2 && !even_hidden && notify_hidden()) {
		uint32_t id = ++n.next_id ? n.next_id : ++n.next_id;
		g_idle_add(closed_unseen, GUINT_TO_POINTER(id));
		return id;
	}
	if (t) {
		/* The same toast, new content: stays where it is */
		free_content(t);
	} else {
		t = calloc(1, sizeof(*t));
		t->id = ++n.next_id ? n.next_id : ++n.next_id;
		t->finger = -1;
		t->ours = !n.from_bus;
		t->question = n.asking;
		wl_list_insert(n.toasts.prev, &t->link);
	}
	t->app_name = dup_nonempty(app_name);
	/* Stealth mode as it comes: a toast is only ever shown */
	t->body = dup_nonempty(c8_stealth_show(body));
	t->summary = strdup(summary && summary[0] ? c8_stealth_show(summary) :
		app_name && app_name[0] ? app_name : "Notification");
	const char *s;
	t->desktop_entry = g_variant_lookup(hints, "desktop-entry", "&s", &s) ?
		dup_nonempty(s) : NULL;
	t->actions = g_strdupv((char **)actions);
	t->action_count = 0;
	t->has_default = false;
	for (int k = 0; actions[k] && actions[k + 1]; k += 2) {
		if (strcmp(actions[k], "default") == 0) {
			t->has_default = true;
		} else if (t->action_count < 3) {
			t->action_count++;
		}
	}
	gboolean b = FALSE;
	t->resident = g_variant_lookup(hints, "resident", "b", &b) && b;
	bool was_critical = t->critical;
	t->critical = urgency >= 2;
	bool requeue = replacing && t->critical != was_critical;
	/* Critical ones stay until swiped or closed, whatever the app says */
	t->timeout = t->critical || timeout == 0 ? 0 : timeout > 0 ? timeout :
		TOAST_TIMEOUT_MS;
	set_picture(t, app_icon, hints);

	if (replacing && t->shown) {
		int height = measure(t, c8ui_widget_font(t->w));
		if (height != t->height || requeue) {
			t->height = height;
			place(t);
			layout_toasts();
		}
		c8ui_widget_queue_draw(t->w);
		if (!t->w->hovered && !t->down) {
			expire_start(t, t->timeout);
		}
	} else if (!replacing || requeue) {
		layout_toasts();
	}
	return t->id;
}

void notify_ask(const char *summary, const char *body, const char *icon,
		const char *yes, const char *no, notify_ask_fn fn, void *data) {
	const char *actions[] = { "yes", yes, "no", no, NULL };
	GVariant *h = g_variant_ref_sink(g_variant_new("a{sv}", NULL));
	/* A question shows even while notifications are hidden */
	n.asking = true;
	uint32_t id = notify("Start", 0, icon, summary, body, actions, h, 20000,
		true);
	n.asking = false;
	g_variant_unref(h);
	struct toast *t = find(id);
	if (t == NULL) {
		fn(false, data);
		return;
	}
	t->ask_fn = fn;
	t->ask_data = data;
}

/* The bus */

static const char introspection[] =
	"<node>"
	" <interface name='org.freedesktop.Notifications'>"
	"  <method name='GetCapabilities'>"
	"   <arg type='as' name='capabilities' direction='out'/>"
	"  </method>"
	"  <method name='Notify'>"
	"   <arg type='s' name='app_name' direction='in'/>"
	"   <arg type='u' name='replaces_id' direction='in'/>"
	"   <arg type='s' name='app_icon' direction='in'/>"
	"   <arg type='s' name='summary' direction='in'/>"
	"   <arg type='s' name='body' direction='in'/>"
	"   <arg type='as' name='actions' direction='in'/>"
	"   <arg type='a{sv}' name='hints' direction='in'/>"
	"   <arg type='i' name='expire_timeout' direction='in'/>"
	"   <arg type='u' name='id' direction='out'/>"
	"  </method>"
	"  <method name='CloseNotification'>"
	"   <arg type='u' name='id' direction='in'/>"
	"  </method>"
	"  <method name='GetServerInformation'>"
	"   <arg type='s' name='name' direction='out'/>"
	"   <arg type='s' name='vendor' direction='out'/>"
	"   <arg type='s' name='version' direction='out'/>"
	"   <arg type='s' name='spec_version' direction='out'/>"
	"  </method>"
	"  <signal name='NotificationClosed'>"
	"   <arg type='u' name='id'/>"
	"   <arg type='u' name='reason'/>"
	"  </signal>"
	"  <signal name='ActionInvoked'>"
	"   <arg type='u' name='id'/>"
	"   <arg type='s' name='action_key'/>"
	"  </signal>"
	" </interface>"
	"</node>";

static void method_call(GDBusConnection *bus, const char *sender,
		const char *path, const char *iface, const char *method,
		GVariant *params, GDBusMethodInvocation *call, gpointer data) {
	if (strcmp(method, "GetCapabilities") == 0) {
		const char *caps[] = { "actions", "body", "icon-static", NULL };
		g_dbus_method_invocation_return_value(call,
			g_variant_new("(^as)", caps));
	} else if (strcmp(method, "Notify") == 0) {
		const char *app_name, *app_icon, *summary, *body;
		const char **actions;
		guint32 replaces;
		gint32 timeout;
		GVariant *hints;
		g_variant_get(params, "(&su&s&s&s^a&s@a{sv}i)", &app_name, &replaces,
			&app_icon, &summary, &body, &actions, &hints, &timeout);
		n.from_bus = true;
		uint32_t id = notify(app_name, replaces, app_icon, summary, body,
			actions, hints, timeout, false);
		n.from_bus = false;
		g_free(actions);
		g_variant_unref(hints);
		g_dbus_method_invocation_return_value(call, g_variant_new("(u)", id));
	} else if (strcmp(method, "CloseNotification") == 0) {
		guint32 id;
		g_variant_get(params, "(u)", &id);
		struct toast *t = find(id);
		if (t && !t->ours) {
			close_toast(t, CLOSED_BY_CALL);
		}
		g_dbus_method_invocation_return_value(call, NULL);
	} else if (strcmp(method, "GetServerInformation") == 0) {
		g_dbus_method_invocation_return_value(call, g_variant_new("(ssss)",
			"cont8nuum", "lowtide", "0.1.0", "1.2"));
	} else {
		g_dbus_method_invocation_return_error(call, G_DBUS_ERROR,
			G_DBUS_ERROR_UNKNOWN_METHOD, "No method %s", method);
	}
}

static const GDBusInterfaceVTable vtable = {
	.method_call = method_call,
};

static void bus_acquired(GDBusConnection *bus, const char *name,
		gpointer data) {
	GError *err = NULL;
	GDBusNodeInfo *info = g_dbus_node_info_new_for_xml(introspection, &err);
	if (info == NULL) {
		g_warning("notifications: %s", err->message);
		g_error_free(err);
		return;
	}
	n.bus = g_object_ref(bus);
	n.object = g_dbus_connection_register_object(bus,
		"/org/freedesktop/Notifications", info->interfaces[0], &vtable, NULL,
		NULL, &err);
	if (n.object == 0) {
		g_warning("notifications: %s", err->message);
		g_error_free(err);
	}
	g_dbus_node_info_unref(info);
}

static void name_lost(GDBusConnection *bus, const char *name, gpointer data) {
	/* Another notification daemon (mako, dunst) has it; theirs show */
	g_message("notifications: %s is taken by another program", name);
}

/* Low battery: a toast as it falls past 15, 10 and 5 per cent, each
 * replacing the last; plugging in takes it away. Critical, so it shows
 * while notifications are hidden, and it stays until dismissed. */
static const int battery_levels[] = { STATUS_BATTERY_CRITICAL, 10, 5 };

static void battery_changed(void *data) {
	bool draining = status.battery && status.on_battery &&
		!status.charging;
	if (!draining) {
		n.battery_warned = 100;
		struct toast *t = n.battery_id ? find(n.battery_id) : NULL;
		if (t) {
			close_toast(t, CLOSED_BY_CALL);
		}
		n.battery_id = 0;
		return;
	}
	int level = 100;
	for (size_t i = 0; i < G_N_ELEMENTS(battery_levels); i++) {
		if (status.percent <= battery_levels[i]) {
			level = battery_levels[i];
		}
	}
	if (level >= n.battery_warned) {
		return;
	}
	n.battery_warned = level;
	bool last = level == battery_levels[G_N_ELEMENTS(battery_levels) - 1];
	char body[96];
	snprintf(body, sizeof(body), last ?
		"%d%% left. Plug in your PC now." :
		"%d%% left. You might want to plug in your PC.", status.percent);
	const char *actions[] = { NULL };
	GVariantBuilder hints;
	g_variant_builder_init(&hints, G_VARIANT_TYPE("a{sv}"));
	g_variant_builder_add(&hints, "{sv}", "urgency", g_variant_new_byte(2));
	GVariant *h = g_variant_ref_sink(g_variant_builder_end(&hints));
	uint32_t replaces = n.battery_id && find(n.battery_id) ?
		n.battery_id : 0;
	n.battery_id = notify("Battery", replaces,
		"cont8nuum-battery",
		last ? "Your battery is very low" : "Your battery is running low",
		body, actions, h, 0, false);
	g_variant_unref(h);
}

void notify_init(void) {
	wl_list_init(&n.toasts);
	n.battery_warned = 100;
	status_listen(battery_changed, NULL);
	read_corner();
	/* Ours in our own session; one started by hand with --replace wins */
	n.owner = g_bus_own_name(G_BUS_TYPE_SESSION,
		"org.freedesktop.Notifications", G_BUS_NAME_OWNER_FLAGS_REPLACE |
		G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT, bus_acquired, NULL,
		name_lost, NULL, NULL);
}

/* Colours follow the accent and tiles */
void notify_appearance_changed(void) {
	bool right = n.right, bottom = n.bottom;
	static bool was_row;
	read_corner();
	if (right != n.right || bottom != n.bottom || was_row != row()) {
		/* Shown ones go to the new corner (or row) at once */
		was_row = row();
		layout_toasts();
		struct toast *m;
		wl_list_for_each(m, &n.toasts, link) {
			if (m->shown && !m->leaving) {
				m->slide = 0;
				m->slide_from = m->slide_to = 0;
				m->drag = 0;
				m->sinking = false;
				m->x = m->x_from = m->x_to;
				m->y = m->y_from = m->y_to;
				place(m);
			}
		}
	}
	struct toast *t;
	wl_list_for_each(t, &n.toasts, link) {
		c8ui_widget_queue_draw(t->w);
	}
}

bool notify_hidden(void) {
	if (n.quiet_until && g_get_real_time() >= n.quiet_until) {
		n.quiet_until = 0;
	}
	return n.quiet_until != 0;
}

void notify_hide_for(int hours) {
	n.quiet_until = hours > 0 ?
		g_get_real_time() + (int64_t)hours * 3600 * G_USEC_PER_SEC : 0;
}

/* The screen's size is known, or changed: the toasts go by it */
void notify_output_changed(void) {
	if (n.toasts.next != NULL) { // before notify_init there are none
		layout_toasts();
	}
}

void notify_locked_changed(void) {
	if (!shell.locked) {
		layout_toasts();
	}
}
