/*
 * c8-lock: the lock screen of the cont8nuum desktop, drawn like the SDDM
 * theme (theme/sddm): the clock and date over the Start background,
 * which slides up (drag it, click, or press a key) to the account tile
 * and password box. The password goes through PAM.
 *
 * c8 starts it over a private connection when the session locks; only
 * it sees ext-session-lock-v1. Run by hand it has nothing to talk to.
 */
#define _GNU_SOURCE
#include <locale.h>
#include <math.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <gio/gio.h>
#include <security/pam_appl.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include <c8ui/c8ui.h>
#include <c8ui/c8ui-wayland.h>
#include "ext-session-lock-v1-client-protocol.h"
#include "pattern.h"
#include "pixels.h"
#include "status.h"
#include "clock.h"

#define SLIDE_MS 450
#define IDLE_MS 60000 // back to the clock after this long untouched
#define MAX_PASSWORD 512

enum view {
	VIEW_PASSWORD,
	VIEW_BUSY,
	VIEW_ERROR,
};

struct output {
	struct wl_list link; // L.outputs, first is where the UI goes
	struct wl_output *wl_output;
	uint32_t name;
	struct ext_session_lock_surface_v1 *lock_surface;
	struct c8ui_window *win;
	struct c8ui_widget *w;
	int width, height;
	/* The pattern as drawn, kept: it's under every frame of the slide */
	cairo_surface_t *bg;
	int bg_w, bg_h;
	double bg_scale;
};

struct power_item {
	const char *label, *method;
};

static struct {
	struct c8ui_app *app;
	struct wl_display *display;
	struct ext_session_lock_manager_v1 *manager;
	struct ext_session_lock_v1 *lock;
	bool locked, unlocking;
	bool nested; // inside another desktop: its logind session isn't ours
	struct wl_list outputs;

	uint32_t accent, background;
	char *clock; // [general] clock: auto, 12 or 24
	char *pattern;

	/* The lock face over the password view: 0 down, 1 gone up */
	double lift, lift_from, lift_to;
	int64_t lift_start;
	bool dragging;
	double drag_y, drag_lift;

	enum view view;
	char password[MAX_PASSWORD];
	size_t len;
	int64_t busy_start;
	guint idle_timer, clock_timer;

	char *user, *real_name;
	cairo_surface_t *face;

	/* The power button's menu */
	struct power_item power[3];
	int power_count;
	bool menu_open;
	int menu_hover;
	bool power_hover, power_down, go_hover, ok_hover;
} L;

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

static double ease_out_cubic(double t) {
	t = t < 0 ? 0 : t > 1 ? 1 : t;
	return 1 - pow(1 - t, 3);
}

static void redraw_all(void) {
	struct output *o;
	wl_list_for_each(o, &L.outputs, link) {
		c8ui_widget_queue_draw(o->w);
	}
}

static void animate_all(void) {
	struct output *o;
	wl_list_for_each(o, &L.outputs, link) {
		if (o->w) {
			c8ui_widget_animate(o->w);
		}
	}
}

static struct output *primary(void) {
	return wl_list_empty(&L.outputs) ? NULL :
		wl_container_of(L.outputs.next, (struct output *)NULL, link);
}

static void clear_password(void) {
	explicit_bzero(L.password, sizeof(L.password));
	L.len = 0;
}

/* Settings: the colours from c8ui's theme; the [appearance] pattern and
 * [general] clock from config.ini */

static void read_appearance(const char *dir) {
	const struct c8ui_theme *theme = c8ui_app_theme(L.app);
	L.accent = theme ? theme->accent : 0x1ba1e2;
	L.background = theme ? theme->background : 0x180052;
	char *path = g_build_filename(dir, "config.ini", NULL);
	char *text = NULL;
	if (g_file_get_contents(path, &text, NULL, NULL)) {
		bool in = false, general = false;
		for (char *line = strtok(text, "\n"); line; line = strtok(NULL, "\n")) {
			g_strstrip(line);
			if (line[0] == '[') {
				in = strcmp(line, "[appearance]") == 0;
				general = strcmp(line, "[general]") == 0;
				continue;
			}
			char *eq = strchr(line, '=');
			if ((!in && !general) || line[0] == '#' || eq == NULL) {
				continue;
			}
			*eq = '\0';
			char *key = g_strstrip(line), *value = g_strstrip(eq + 1);
			if (general) {
				if (strcmp(key, "clock") == 0) {
					g_free(L.clock);
					L.clock = g_strdup(value);
				}
				continue;
			}
			if (strcmp(key, "pattern") == 0) {
				g_free(L.pattern);
				L.pattern = g_strdup(value);
			}
		}
	}
	g_free(text);
	g_free(path);
}

/* The account: name, and its picture as SDDM finds it */
static void read_account(void) {
	account_read(&L.user, &L.real_name, &L.face, 384);
}

/* logind: what the power button offers, and telling it we're locked */

static GDBusConnection *system_bus(void) {
	return g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, NULL);
}

static bool logind_can(GDBusConnection *bus, const char *method) {
	GVariant *r = g_dbus_connection_call_sync(bus, "org.freedesktop.login1",
		"/org/freedesktop/login1", "org.freedesktop.login1.Manager", method,
		NULL, G_VARIANT_TYPE("(s)"), G_DBUS_CALL_FLAGS_NONE, 1000, NULL, NULL);
	if (r == NULL) {
		return false;
	}
	const char *answer;
	g_variant_get(r, "(&s)", &answer);
	bool yes = strcmp(answer, "yes") == 0;
	g_variant_unref(r);
	return yes;
}

static void read_power(void) {
	GDBusConnection *bus = system_bus();
	if (bus == NULL) {
		return;
	}
	static const struct {
		const char *can;
		struct power_item item;
	} all[] = {
		{ "CanSuspend", { "Sleep", "Suspend" } },
		{ "CanPowerOff", { "Shut down", "PowerOff" } },
		{ "CanReboot", { "Restart", "Reboot" } },
	};
	for (int i = 0; i < 3; i++) {
		if (logind_can(bus, all[i].can)) {
			L.power[L.power_count++] = all[i].item;
		}
	}
	g_object_unref(bus);
}

static void power_run(const char *method) {
	GDBusConnection *bus = system_bus();
	if (bus) {
		g_dbus_connection_call(bus, "org.freedesktop.login1",
			"/org/freedesktop/login1", "org.freedesktop.login1.Manager", method,
			g_variant_new("(b)", FALSE), NULL, G_DBUS_CALL_FLAGS_NONE, -1,
			NULL, NULL, NULL);
		g_object_unref(bus);
	}
}

static void set_locked_hint(bool locked) {
	if (L.nested) {
		return;
	}
	GDBusConnection *bus = system_bus();
	if (bus == NULL) {
		return;
	}
	GVariant *r = g_dbus_connection_call_sync(bus, "org.freedesktop.login1",
		"/org/freedesktop/login1/session/auto",
		"org.freedesktop.login1.Session", "SetLockedHint",
		g_variant_new("(b)", locked), NULL, G_DBUS_CALL_FLAGS_NONE, 1000, NULL,
		NULL);
	if (r) {
		g_variant_unref(r);
	}
	g_object_unref(bus);
}

/* PAM, on a thread: a wrong password takes pam_unix a couple of seconds */

static int conversation(int n, const struct pam_message **msg,
		struct pam_response **resp, void *data) {
	const char *password = data;
	struct pam_response *r = calloc(n, sizeof(*r));
	if (r == NULL) {
		return PAM_BUF_ERR;
	}
	for (int i = 0; i < n; i++) {
		if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF ||
				msg[i]->msg_style == PAM_PROMPT_ECHO_ON) {
			r[i].resp = strdup(password);
		}
	}
	*resp = r;
	return PAM_SUCCESS;
}

/* Ours if installed, else the login service's rules */
static const char *pam_service(void) {
	static const char *const dirs[] = { "/etc/pam.d", "/usr/lib/pam.d",
		"/usr/etc/pam.d" };
	for (int i = 0; i < 3; i++) {
		char *path = g_build_filename(dirs[i], "c8-lock", NULL);
		bool there = access(path, R_OK) == 0;
		g_free(path);
		if (there) {
			return "c8-lock";
		}
	}
	return "login";
}

static void unlock(void);
static void set_view(enum view view);

static gboolean auth_done(gpointer data) {
	if (GPOINTER_TO_INT(data)) {
		unlock();
	} else {
		set_view(VIEW_ERROR);
	}
	return G_SOURCE_REMOVE;
}

static gpointer auth_thread(gpointer data) {
	char *password = data;
	struct pam_conv conv = { conversation, password };
	pam_handle_t *pam = NULL;
	bool ok = false;
	if (pam_start(pam_service(), L.user, &conv, &pam) == PAM_SUCCESS) {
		ok = pam_authenticate(pam, 0) == PAM_SUCCESS;
		pam_end(pam, PAM_SUCCESS);
	}
	explicit_bzero(password, strlen(password));
	free(password);
	g_idle_add(auth_done, GINT_TO_POINTER(ok));
	return NULL;
}

static void submit(void) {
	/* Nothing typed isn't worth a failed attempt (faillock counts them) */
	if (L.view != VIEW_PASSWORD || L.len == 0) {
		return;
	}
	char *copy = strndup(L.password, L.len);
	clear_password();
	set_view(VIEW_BUSY);
	g_thread_unref(g_thread_new("pam", auth_thread, copy));
}

/* The views */

static gboolean idle_timeout(gpointer data);

static void poke_idle(void) {
	if (L.idle_timer) {
		g_source_remove(L.idle_timer);
	}
	L.idle_timer = g_timeout_add(IDLE_MS, idle_timeout, NULL);
}

static void slide_to(double to) {
	L.lift_from = L.lift;
	L.lift_to = to;
	L.lift_start = now_ms();
	animate_all();
}

static void set_view(enum view view) {
	L.view = view;
	L.menu_open = false;
	if (view == VIEW_BUSY) {
		L.busy_start = now_ms();
		animate_all();
	}
	redraw_all();
}

/* Back down to the clock, forgetting what was typed */
static void relock(void) {
	if (L.view == VIEW_BUSY) {
		return;
	}
	clear_password();
	set_view(VIEW_PASSWORD);
	slide_to(0);
}

static gboolean idle_timeout(gpointer data) {
	L.idle_timer = 0;
	relock();
	return G_SOURCE_REMOVE;
}

static void lift(void) {
	if (L.lift_to < 1) {
		slide_to(1);
	}
	poke_idle();
}

/* Drawing, in the SDDM theme's units: u is 1 at 1080 pixels high */

static double units(struct output *o) {
	return fmax(0.75, o->height / 1080.0);
}

static struct c8ui_font font(double size, enum c8ui_weight weight) {
	return (struct c8ui_font){ size, weight };
}

static const char *family(struct output *o) {
	return c8ui_widget_font(o->w);
}

static void text_size(struct output *o, struct c8ui_font f, const char *text,
		double *w, double *h) {
	c8ui_text_size(family(o), f, text, 0, 0, w, h);
}

/* The glyphs of components/Glyph.qml, on a 24 unit grid */
static void glyph(cairo_t *cr, const char *name, double cx, double cy,
		double size, double stroke) {
	double s = size / 24;
	cairo_save(cr);
	cairo_translate(cr, cx - 12 * s, cy - 12 * s);
	cairo_scale(cr, s, s);
	cairo_set_line_width(cr, stroke);
	cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND);
	cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
	cairo_new_path(cr);
	if (strcmp(name, "arrow") == 0) {
		cairo_move_to(cr, 5, 12);
		cairo_line_to(cr, 19, 12);
		cairo_move_to(cr, 13, 6);
		cairo_line_to(cr, 19, 12);
		cairo_line_to(cr, 13, 18);
	} else if (strcmp(name, "power") == 0) {
		cairo_arc(cr, 12, 13, 7.5, -M_PI / 2 + 0.75, 3 * M_PI / 2 - 0.75);
		cairo_move_to(cr, 12, 3);
		cairo_line_to(cr, 12, 11);
	} else if (strcmp(name, "person") == 0) {
		cairo_arc(cr, 12, 8, 4, 0, 2 * M_PI);
		cairo_move_to(cr, 4, 21);
		cairo_arc(cr, 12, 21, 8, M_PI, 2 * M_PI);
	}
	cairo_restore(cr);
	cairo_stroke(cr);
}

static void draw_background(cairo_t *cr, struct output *o) {
	cairo_surface_t *target = cairo_get_target(cr);
	double sx, sy;
	cairo_surface_get_device_scale(target, &sx, &sy);
	if (o->bg == NULL || o->bg_w != o->width || o->bg_h != o->height ||
			o->bg_scale != sx) {
		if (o->bg) {
			cairo_surface_destroy(o->bg);
		}
		o->bg = cairo_surface_create_similar(target, CAIRO_CONTENT_COLOR,
			o->width, o->height);
		o->bg_w = o->width;
		o->bg_h = o->height;
		o->bg_scale = sx;
		cairo_t *bcr = cairo_create(o->bg);
		if (c8_draw_picture(bcr, o->width, o->height, C8_BACKGROUND_LOCK)) {
			/* The clock and date stay white over a bright picture */
			cairo_set_source_rgba(bcr, 0, 0, 0, 0.25);
			cairo_paint(bcr);
		} else {
			c8_draw_pattern(bcr, o->width, o->height, L.background,
				L.pattern);
		}
		cairo_destroy(bcr);
	}
	cairo_set_source_surface(cr, o->bg, 0, 0);
	cairo_paint(cr);
}

/* Where things are, for drawing and for clicks */
struct layout {
	double u;
	double tile_x, tile_y, tile;
	double name_y, field_x, field_y, field_w, field_h, caps_y;
	double power_x, power_y, power_r;
	double menu_x, menu_y, menu_w, item_h;
	double ok_x, ok_y, ok_w, ok_h;
};

static struct layout layout(struct output *o) {
	struct layout l;
	double u = l.u = units(o);
	double nw, nh, cw, ch;
	text_size(o, font(36 * u, C8UI_WEIGHT_LIGHT), L.real_name, &nw, &nh);
	text_size(o, font(14 * u, C8UI_WEIGHT_NORMAL), "Caps Lock is on", &cw,
		&ch);
	l.tile = 192 * u;
	l.field_w = 280 * u;
	l.field_h = 34 * u;
	double col_w = fmax(l.field_w, nw);
	double col_h = nh + 12 * u + l.field_h + 12 * u + ch;
	double row_w = l.tile + 24 * u + col_w;
	double row_h = fmax(l.tile, col_h);
	double x = (o->width - row_w) / 2, y = (o->height - row_h) / 2;
	l.tile_x = x;
	l.tile_y = y + (row_h - l.tile) / 2;
	double cx = x + l.tile + 24 * u, cy = y + (row_h - col_h) / 2;
	l.name_y = cy;
	l.field_x = cx;
	l.field_y = cy + nh + 12 * u;
	l.caps_y = l.field_y + l.field_h + 12 * u;
	l.power_r = 20 * u;
	l.power_x = o->width - 32 * u - l.power_r;
	l.power_y = o->height - 32 * u - l.power_r;
	l.menu_w = 240 * u;
	l.item_h = 40 * u;
	l.menu_x = l.power_x + l.power_r - l.menu_w;
	l.menu_y = l.power_y - l.power_r - 8 * u -
		(L.power_count * l.item_h + 8 * u);
	double tw, th;
	text_size(o, font(15 * u, C8UI_WEIGHT_SEMIBOLD), "OK", &tw, &th);
	double ew, eh;
	text_size(o, font(20 * u, C8UI_WEIGHT_NORMAL),
		"The password is incorrect. Try again.", &ew, &eh);
	l.ok_w = fmax(100 * u, tw + 32 * u);
	l.ok_h = 34 * u;
	double block = eh + 32 * u + l.ok_h;
	l.ok_x = (o->width - l.ok_w) / 2;
	l.ok_y = (o->height - block) / 2 + eh + 32 * u;
	return l;
}

static bool in_rect(double x, double y, double rx, double ry, double rw,
		double rh) {
	return x >= rx && y >= ry && x < rx + rw && y < ry + rh;
}

static void draw_text(cairo_t *cr, struct output *o, struct c8ui_font f,
		const char *text, double x, double y) {
	c8ui_text_draw(cr, family(o), f, text, x, y, 0, 0);
}

static void draw_centered(cairo_t *cr, struct output *o, struct c8ui_font f,
		const char *text, double y) {
	double w, h;
	text_size(o, f, text, &w, &h);
	draw_text(cr, o, f, text, (o->width - w) / 2, y);
}

static void draw_password(cairo_t *cr, struct output *o, struct layout *l) {
	double u = l->u;
	/* components/UserTile.qml */
	c8ui_set_source(cr, L.accent, 1);
	cairo_rectangle(cr, l->tile_x, l->tile_y, l->tile, l->tile);
	cairo_fill(cr);
	if (L.face) {
		c8ui_draw_surface_cover(cr, L.face, l->tile_x, l->tile_y, l->tile,
			l->tile);
	} else {
		cairo_set_source_rgb(cr, 1, 1, 1);
		glyph(cr, "person", l->tile_x + l->tile / 2, l->tile_y + l->tile / 2,
			l->tile * 0.55, 1.5);
	}

	cairo_set_source_rgb(cr, 1, 1, 1);
	draw_text(cr, o, font(36 * u, C8UI_WEIGHT_LIGHT), L.real_name, l->field_x,
		l->name_y);

	/* components/Field.qml: white box, accent edge, submit arrow */
	double fx = l->field_x, fy = l->field_y, fw = l->field_w, fh = l->field_h;
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_rectangle(cr, fx, fy, fw, fh);
	cairo_fill(cr);
	c8ui_set_source(cr, L.accent, 1);
	cairo_set_line_width(cr, 2 * u);
	cairo_rectangle(cr, fx + u, fy + u, fw - 2 * u, fh - 2 * u);
	cairo_stroke(cr);
	double go = fh;
	uint32_t go_color = L.go_hover ? c8ui_shade(L.accent, 1.15) : L.accent;
	c8ui_set_source(cr, go_color, 1);
	cairo_rectangle(cr, fx + fw - go, fy, go, fh);
	cairo_fill(cr);
	cairo_set_source_rgb(cr, 1, 1, 1);
	glyph(cr, "arrow", fx + fw - go / 2, fy + fh / 2, go * 0.6, 2);

	struct c8ui_font ff = font(15 * u, C8UI_WEIGHT_NORMAL);
	double tx = fx + 10 * u, max = fw - go - 20 * u;
	char dots[MAX_PASSWORD * 3 + 1] = "";
	const char *shown = dots;
	if (L.len == 0) {
		shown = "Password";
		cairo_set_source_rgb(cr, 0x7a / 255.0, 0x7a / 255.0, 0x7a / 255.0);
	} else {
		/* One dot per character, not per byte */
		size_t chars = g_utf8_strlen(L.password, L.len);
		for (size_t i = 0; i < chars && i < MAX_PASSWORD; i++) {
			strcat(dots, "●");
		}
		cairo_set_source_rgb(cr, 0, 0, 0);
	}
	double tw, th;
	text_size(o, ff, shown, &tw, &th);
	cairo_save(cr);
	cairo_rectangle(cr, tx, fy, max, fh);
	cairo_clip(cr);
	/* The end shows, as a scrolled text box would */
	double shift = L.len && tw > max ? tw - max : 0;
	draw_text(cr, o, ff, shown, tx - shift, fy + (fh - th) / 2);
	/* The caret */
	double cx = tx + (L.len ? tw - shift : 0) + 1;
	cairo_set_source_rgb(cr, 0, 0, 0);
	cairo_rectangle(cr, cx, fy + 7 * u, 1, fh - 14 * u);
	cairo_fill(cr);
	cairo_restore(cr);

	if (c8ui_app_caps_lock(L.app)) {
		cairo_set_source_rgba(cr, 1, 1, 1, 0.8);
		draw_text(cr, o, font(14 * u, C8UI_WEIGHT_NORMAL), "Caps Lock is on",
			l->field_x, l->caps_y);
	}
}

/* The five dots of "Welcome", as Qt's OutInCubic moves them */
static double out_in_cubic(double t) {
	if (t < 0.5) {
		double x = 2 * t;
		return (1 - pow(1 - x, 3)) / 2;
	}
	double x = 2 * t - 1;
	return x * x * x / 2 + 0.5;
}

static void draw_busy(cairo_t *cr, struct output *o, struct layout *l) {
	double u = l->u;
	struct c8ui_font f = font(42 * u, C8UI_WEIGHT_LIGHT);
	double tw, th;
	text_size(o, f, "Welcome", &tw, &th);
	double bw = 320 * u, bh = 6 * u;
	double top = (o->height - (th + 24 * u + bh)) / 2;
	cairo_set_source_rgb(cr, 1, 1, 1);
	draw_text(cr, o, f, "Welcome", (o->width - tw) / 2, top);
	double bx = (o->width - bw) / 2, by = top + th + 24 * u;
	int64_t t = (now_ms() - L.busy_start) % 3060;
	cairo_save(cr);
	cairo_rectangle(cr, bx, by, bw, bh);
	cairo_clip(cr);
	for (int i = 0; i < 5; i++) {
		double p = (double)(t - i * 140) / 2200;
		if (p < 0 || p >= 1) {
			continue;
		}
		double x = -bh + (bw + bh) * out_in_cubic(p);
		cairo_arc(cr, bx + x + bh / 2, by + bh / 2, bh / 2, 0, 2 * M_PI);
		cairo_fill(cr);
	}
	cairo_restore(cr);
}

static void draw_error(cairo_t *cr, struct output *o, struct layout *l) {
	double u = l->u;
	cairo_set_source_rgb(cr, 1, 1, 1);
	struct c8ui_font f = font(20 * u, C8UI_WEIGHT_NORMAL);
	double tw, th;
	text_size(o, f, "The password is incorrect. Try again.", &tw, &th);
	draw_centered(cr, o, f, "The password is incorrect. Try again.",
		l->ok_y - 32 * u - th);
	/* components/TextButton.qml */
	if (L.ok_hover) {
		cairo_set_source_rgba(cr, 1, 1, 1, 0.15);
		cairo_rectangle(cr, l->ok_x, l->ok_y, l->ok_w, l->ok_h);
		cairo_fill(cr);
	}
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_set_line_width(cr, 2 * u);
	cairo_rectangle(cr, l->ok_x + u, l->ok_y + u, l->ok_w - 2 * u,
		l->ok_h - 2 * u);
	cairo_stroke(cr);
	struct c8ui_font bf = font(15 * u, C8UI_WEIGHT_SEMIBOLD);
	text_size(o, bf, "OK", &tw, &th);
	draw_text(cr, o, bf, "OK", l->ok_x + (l->ok_w - tw) / 2,
		l->ok_y + (l->ok_h - th) / 2);
}

static void draw_power(cairo_t *cr, struct output *o, struct layout *l) {
	if (L.power_count == 0) {
		return;
	}
	double u = l->u;
	/* components/RoundButton.qml */
	cairo_new_path(cr);
	cairo_arc(cr, l->power_x, l->power_y, l->power_r - u, 0, 2 * M_PI);
	if (L.power_down) {
		cairo_set_source_rgb(cr, 1, 1, 1);
		cairo_fill_preserve(cr);
	} else if (L.power_hover) {
		cairo_set_source_rgba(cr, 1, 1, 1, 0.15);
		cairo_fill_preserve(cr);
	}
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_set_line_width(cr, 2 * u);
	cairo_stroke(cr);
	if (L.power_down) {
		c8ui_set_source(cr, L.background, 1);
	}
	glyph(cr, "power", l->power_x, l->power_y, l->power_r * 2 * 0.55, 2);

	if (!L.menu_open) {
		return;
	}
	/* components/Menu.qml */
	double mh = L.power_count * l->item_h + 8 * u;
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_rectangle(cr, l->menu_x, l->menu_y, l->menu_w, mh);
	cairo_fill(cr);
	cairo_set_source_rgb(cr, 0xd0 / 255.0, 0xd0 / 255.0, 0xd0 / 255.0);
	cairo_set_line_width(cr, 1);
	cairo_rectangle(cr, l->menu_x + 0.5, l->menu_y + 0.5, l->menu_w - 1,
		mh - 1);
	cairo_stroke(cr);
	struct c8ui_font f = font(15 * u, C8UI_WEIGHT_NORMAL);
	for (int i = 0; i < L.power_count; i++) {
		double iy = l->menu_y + 4 * u + i * l->item_h;
		if (i == L.menu_hover) {
			cairo_set_source_rgb(cr, 0xe4 / 255.0, 0xe4 / 255.0, 0xe4 / 255.0);
			cairo_rectangle(cr, l->menu_x + 1, iy, l->menu_w - 2, l->item_h);
			cairo_fill(cr);
		}
		double tw, th;
		text_size(o, f, L.power[i].label, &tw, &th);
		cairo_set_source_rgb(cr, 0, 0, 0);
		draw_text(cr, o, f, L.power[i].label, l->menu_x + 16 * u,
			iy + (l->item_h - th) / 2);
	}
}

static void draw_lock_face(cairo_t *cr, struct output *o, double u) {
	draw_background(cr, o);
	time_t t = time(NULL);
	struct tm tm;
	localtime_r(&t, &tm);
	char clock[32], date[128];
	clock_format(clock, sizeof(clock), &tm, L.clock, false);
	strftime(date, sizeof(date), "%A, %B %-d", &tm);
	struct c8ui_font cf = font(128 * u, C8UI_WEIGHT_LIGHT);
	struct c8ui_font df = font(48 * u, C8UI_WEIGHT_LIGHT);
	double cw, ch, dw, dh;
	text_size(o, cf, clock, &cw, &ch);
	text_size(o, df, date, &dw, &dh);
	double x = 96 * u, bottom = o->height - 112 * u;
	cairo_set_source_rgb(cr, 1, 1, 1);
	draw_text(cr, o, cf, clock, x, bottom - dh - ch);
	draw_text(cr, o, df, date, x, bottom - dh);

	/* Network and battery after the date, where they don't move the
	 * clock off where SDDM has it */
	double size = 32 * u, ix = x + dw + 40 * u, iy = bottom - dh +
		(dh - size) / 2;
	if (status.net != STATUS_NET_UNKNOWN) {
		status_draw_network(cr, ix, iy, size);
		ix += size + 20 * u;
	}
	status_draw_battery(cr, ix, iy, size, L.background);
}

static void status_changed(void *data) {
	redraw_all();
}

static void lock_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct output *o = w->data;
	if (o == NULL) {
		return;
	}
	if (o != primary()) {
		/* Other screens keep the pattern, as in SDDM */
		draw_background(cr, o);
		return;
	}
	struct layout l = layout(o);
	if (L.lift > 0) {
		/* Under the lock face nothing of this shows */
		draw_background(cr, o);
		switch (L.view) {
		case VIEW_PASSWORD:
			draw_password(cr, o, &l);
			break;
		case VIEW_BUSY:
			draw_busy(cr, o, &l);
			break;
		case VIEW_ERROR:
			draw_error(cr, o, &l);
			break;
		}
		if (L.view != VIEW_BUSY) {
			draw_power(cr, o, &l);
		}
	}
	if (L.lift < 1) {
		cairo_save(cr);
		cairo_translate(cr, 0, round(-L.lift * o->height));
		draw_lock_face(cr, o, l.u);
		cairo_restore(cr);
	}
}

static bool lock_tick(struct c8ui_widget *w, int64_t now) {
	bool more = false;
	if (L.lift != L.lift_to && !L.dragging) {
		double t = (double)(now - L.lift_start) / SLIDE_MS;
		L.lift = L.lift_from + (L.lift_to - L.lift_from) * ease_out_cubic(t);
		if (t >= 1) {
			L.lift = L.lift_to;
		}
		more = L.lift != L.lift_to;
	}
	more |= L.view == VIEW_BUSY;
	c8ui_widget_queue_draw(w);
	return more;
}

/* Input */

static void click(struct output *o, double x, double y) {
	struct layout l = layout(o);
	if (L.menu_open) {
		double mh = L.power_count * l.item_h + 8 * l.u;
		if (in_rect(x, y, l.menu_x, l.menu_y, l.menu_w, mh)) {
			int i = (int)((y - l.menu_y - 4 * l.u) / l.item_h);
			if (i >= 0 && i < L.power_count) {
				L.menu_open = false;
				power_run(L.power[i].method);
			}
		}
		L.menu_open = false;
		redraw_all();
		return;
	}
	if (L.power_count && L.view != VIEW_BUSY &&
			hypot(x - l.power_x, y - l.power_y) <= l.power_r) {
		L.menu_open = true;
		L.menu_hover = -1;
		redraw_all();
		return;
	}
	if (L.view == VIEW_PASSWORD &&
			in_rect(x, y, l.field_x + l.field_w - l.field_h, l.field_y,
			l.field_h, l.field_h)) {
		submit();
	} else if (L.view == VIEW_ERROR &&
			in_rect(x, y, l.ok_x, l.ok_y, l.ok_w, l.ok_h)) {
		set_view(VIEW_PASSWORD);
	}
}

static void hover(struct output *o, double x, double y) {
	struct layout l = layout(o);
	bool power = L.power_count && hypot(x - l.power_x, y - l.power_y) <=
		l.power_r;
	bool go = L.view == VIEW_PASSWORD && in_rect(x, y,
		l.field_x + l.field_w - l.field_h, l.field_y, l.field_h, l.field_h);
	bool ok = L.view == VIEW_ERROR &&
		in_rect(x, y, l.ok_x, l.ok_y, l.ok_w, l.ok_h);
	int item = -1;
	if (L.menu_open && in_rect(x, y, l.menu_x, l.menu_y + 4 * l.u, l.menu_w,
			L.power_count * l.item_h)) {
		item = (int)((y - l.menu_y - 4 * l.u) / l.item_h);
	}
	if (power != L.power_hover || go != L.go_hover || ok != L.ok_hover ||
			item != L.menu_hover) {
		L.power_hover = power;
		L.go_hover = go;
		L.ok_hover = ok;
		L.menu_hover = item;
		redraw_all();
	}
}

static bool lock_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct output *o = w->data;
	if (o == NULL || L.unlocking) {
		return true;
	}
	poke_idle();
	bool face = L.lift < 1 || L.dragging;
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		if (ev->button != C8UI_BUTTON_LEFT) {
			return true;
		}
		if (face) {
			/* Drag the clock up, as in SDDM */
			L.dragging = true;
			L.drag_y = ev->y;
			L.drag_lift = L.lift;
		} else if (o == primary()) {
			struct layout l = layout(o);
			L.power_down = L.power_count && !L.menu_open &&
				hypot(ev->x - l.power_x, ev->y - l.power_y) <= l.power_r;
			redraw_all();
		}
		return true;
	case C8UI_EVENT_MOTION:
		if (L.dragging) {
			double d = (L.drag_y - ev->y) / o->height;
			L.lift = L.lift_to = fmin(1, fmax(0, L.drag_lift + d));
			c8ui_widget_queue_draw(w);
		} else if (!face && o == primary()) {
			hover(o, ev->x, ev->y);
		}
		return true;
	case C8UI_EVENT_RELEASE:
		if (ev->button != C8UI_BUTTON_LEFT) {
			return true;
		}
		if (L.dragging) {
			L.dragging = false;
			double moved = L.lift - L.drag_lift;
			/* A click, or a drag past a sixth of the screen, lifts it */
			if (fabs(moved) * o->height < 2 * units(o) || L.lift > 1.0 / 6) {
				slide_to(1);
			} else {
				slide_to(0);
			}
		} else if (o == primary()) {
			L.power_down = false;
			click(o, ev->x, ev->y);
		}
		return true;
	case C8UI_EVENT_LEAVE:
		L.power_hover = L.go_hover = L.ok_hover = false;
		redraw_all();
		return true;
	default:
		return false;
	}
}

static bool is_modifier(uint32_t sym) {
	switch (sym) {
	case XKB_KEY_Shift_L: case XKB_KEY_Shift_R: case XKB_KEY_Control_L:
	case XKB_KEY_Control_R: case XKB_KEY_Alt_L: case XKB_KEY_Alt_R:
	case XKB_KEY_Super_L: case XKB_KEY_Super_R: case XKB_KEY_Caps_Lock:
	case XKB_KEY_Num_Lock: case XKB_KEY_ISO_Level3_Shift:
		return true;
	}
	return false;
}

static void type_text(const char *text) {
	if (text == NULL || (unsigned char)text[0] < ' ' || text[0] == 0x7f) {
		return;
	}
	size_t n = strlen(text);
	if (L.len + n < MAX_PASSWORD) {
		memcpy(L.password + L.len, text, n);
		L.len += n;
	}
}

static bool key(const struct c8ui_event *ev, void *data) {
	if (L.unlocking) {
		return true;
	}
	poke_idle();
	redraw_all(); // Caps Lock, at least
	if (is_modifier(ev->sym)) {
		return true;
	}
	if (L.menu_open) {
		L.menu_open = false;
		return true;
	}
	if (L.lift_to < 1) {
		/* What lifts the clock also starts the password */
		lift();
		if (ev->sym != XKB_KEY_Escape && ev->sym != XKB_KEY_Return &&
				ev->sym != XKB_KEY_KP_Enter) {
			type_text(ev->text);
		}
		return true;
	}
	switch (L.view) {
	case VIEW_PASSWORD:
		if (ev->sym == XKB_KEY_Return || ev->sym == XKB_KEY_KP_Enter) {
			submit();
		} else if (ev->sym == XKB_KEY_Escape) {
			relock();
		} else if (ev->sym == XKB_KEY_BackSpace) {
			if (ev->mods & C8UI_MOD_CTRL) {
				clear_password();
			} else if (L.len) {
				/* A whole character */
				const char *prev = g_utf8_find_prev_char(L.password,
					L.password + L.len);
				size_t at = prev ? (size_t)(prev - L.password) : 0;
				explicit_bzero(L.password + at, L.len - at);
				L.len = at;
			}
		} else if ((ev->mods & C8UI_MOD_CTRL) && ev->base_sym == XKB_KEY_u) {
			clear_password();
		} else if (!(ev->mods & (C8UI_MOD_CTRL | C8UI_MOD_ALT))) {
			type_text(ev->text);
		}
		break;
	case VIEW_ERROR:
		if (ev->sym == XKB_KEY_Return || ev->sym == XKB_KEY_KP_Enter ||
				ev->sym == XKB_KEY_Escape || ev->sym == XKB_KEY_space) {
			set_view(VIEW_PASSWORD);
		}
		break;
	case VIEW_BUSY:
		break;
	}
	return true;
}

static void lock_widget_destroy(struct c8ui_widget *w) {
	struct output *o = w->data;
	if (o) {
		o->w = NULL;
	}
}

static const struct c8ui_widget_impl lock_impl = {
	.name = "lock",
	.draw = lock_draw,
	.event = lock_event,
	.tick = lock_tick,
	.destroy = lock_widget_destroy,
};

/* Lock surfaces, one per output */

static void surface_configure(void *data,
		struct ext_session_lock_surface_v1 *surface, uint32_t serial,
		uint32_t width, uint32_t height) {
	struct output *o = data;
	o->width = width;
	o->height = height;
	ext_session_lock_surface_v1_ack_configure(surface, serial);
	c8ui_window_configure(o->win, width, height);
}

static const struct ext_session_lock_surface_v1_listener surface_listener = {
	.configure = surface_configure,
};

static void output_lock(struct output *o) {
	if (L.lock == NULL || o->lock_surface) {
		return;
	}
	o->win = c8ui_window_new_bare(L.app);
	c8ui_window_set_background(o->win, L.background, 1);
	o->w = c8ui_widget_new(&lock_impl, o);
	o->w->fill = true;
	o->w->expand = true;
	c8ui_widget_set_scheme(o->w, C8UI_SCHEME_DARK);
	struct c8ui_root *root = c8ui_window_root(o->win);
	c8ui_root_set_child(root, o->w);
	c8ui_root_set_key_handler(root, key, NULL);
	o->lock_surface = ext_session_lock_v1_get_lock_surface(L.lock,
		c8ui_window_surface(o->win), o->wl_output);
	ext_session_lock_surface_v1_add_listener(o->lock_surface,
		&surface_listener, o);
}

static void output_free(struct output *o) {
	if (o->lock_surface) {
		ext_session_lock_surface_v1_destroy(o->lock_surface);
	}
	if (o->w) {
		o->w->data = NULL;
	}
	if (o->win) {
		c8ui_window_destroy(o->win);
	}
	if (o->bg) {
		cairo_surface_destroy(o->bg);
	}
	wl_output_release(o->wl_output);
	wl_list_remove(&o->link);
	free(o);
}

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 >= 3) {
		struct output *o = calloc(1, sizeof(*o));
		o->name = name;
		o->wl_output = wl_registry_bind(registry, name, &wl_output_interface,
			3);
		wl_list_insert(L.outputs.prev, &o->link);
		output_lock(o);
	} else if (strcmp(interface,
			ext_session_lock_manager_v1_interface.name) == 0) {
		L.manager = wl_registry_bind(registry, name,
			&ext_session_lock_manager_v1_interface, 1);
	}
}

static void registry_global_remove(void *data, struct wl_registry *registry,
		uint32_t name) {
	struct output *o, *tmp;
	wl_list_for_each_safe(o, tmp, &L.outputs, link) {
		if (o->name == name) {
			output_free(o);
			redraw_all(); // another may be primary now
		}
	}
}

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

static void lock_locked(void *data, struct ext_session_lock_v1 *lock) {
	L.locked = true;
	set_locked_hint(true);
}

static void lock_finished(void *data, struct ext_session_lock_v1 *lock) {
	/* Refused, or already locked by another */
	fprintf(stderr, "c8-lock: the compositor would not lock\n");
	c8ui_app_quit(L.app, 1);
}

static const struct ext_session_lock_v1_listener lock_listener = {
	.locked = lock_locked,
	.finished = lock_finished,
};

static void unlock(void) {
	if (L.unlocking) {
		return;
	}
	L.unlocking = true;
	clear_password();
	if (L.lock) {
		ext_session_lock_v1_unlock_and_destroy(L.lock);
		L.lock = NULL;
	}
	wl_display_roundtrip(L.display);
	set_locked_hint(false);
	c8ui_app_quit(L.app, 0);
}

static gboolean clock_tick(gpointer data) {
	/* The clock shows minutes: draw again only when one turns over */
	static time_t shown;
	time_t minute = time(NULL) / 60;
	if (minute != shown && L.lift < 1) {
		shown = minute;
		redraw_all();
	}
	return G_SOURCE_CONTINUE;
}

int main(int argc, char *argv[]) {
	setlocale(LC_TIME, "");
	const char *config_dir = NULL;
	for (int i = 1; i < argc; i++) {
		if (strcmp(argv[i], "--config") == 0 && i + 1 < argc) {
			config_dir = argv[++i];
		} else if (strcmp(argv[i], "--nested") == 0) {
			L.nested = true;
		}
	}
	wl_list_init(&L.outputs);
	L.app = c8ui_app_new("c8-lock");
	if (L.app == NULL) {
		fprintf(stderr, "c8-lock: cannot connect to the compositor\n");
		return 1;
	}
	L.display = c8ui_app_display(L.app);
	char *dir = config_dir ? g_strdup(config_dir) :
		g_build_filename(g_get_user_config_dir(), "cont8nuum", NULL);
	read_appearance(dir);
	c8_stealth_config_dir(dir); // read_account shows the persona in it
	g_free(dir);
	read_account();
	read_power();
	L.menu_hover = -1;

	struct wl_registry *registry = wl_display_get_registry(L.display);
	wl_registry_add_listener(registry, &registry_listener, NULL);
	wl_display_roundtrip(L.display);
	if (L.manager == NULL) {
		fprintf(stderr, "c8-lock: the compositor didn't offer "
			"ext-session-lock-v1; c8 starts the locker itself\n");
		return 1;
	}
	L.lock = ext_session_lock_manager_v1_lock(L.manager);
	ext_session_lock_v1_add_listener(L.lock, &lock_listener, NULL);
	struct output *o;
	wl_list_for_each(o, &L.outputs, link) {
		output_lock(o);
	}
	L.clock_timer = g_timeout_add_seconds(1, clock_tick, NULL);
	status_init();
	status_listen(status_changed, NULL);
	int ret = c8ui_app_run(L.app);

	struct output *tmp;
	wl_list_for_each_safe(o, tmp, &L.outputs, link) {
		output_free(o);
	}
	if (L.lock) {
		/* Leaving without unlocking: the session stays locked */
		ext_session_lock_v1_destroy(L.lock);
	}
	ext_session_lock_manager_v1_destroy(L.manager);
	wl_registry_destroy(registry);
	c8ui_app_destroy(L.app);
	return ret;
}
