/*
 * The panels: the charms bar with its clock, the Settings flyout and the
 * app switcher, and the Start hint in the bottom-left corner. One panel
 * surface shows whichever is open; the clock is a second one that comes
 * with the charms. In XR the charms are a bar of their own
 * instead, clock and tray in one row, that the glasses show below you
 * as you look down.
 */
#define _GNU_SOURCE
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <glib.h>
#include <gio/gdesktopappinfo.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include "shell.h"
#include "status.h"
#include "clock.h"

#define SLIDE_MS 180
#define MOVE_MS 250 // the pick following its rest, as the compositor's split moves
#define CHARMS_WIDTH 86
#define CHARM_HEIGHT 96
#define FLYOUT_WIDTH 346
#define SWITCHER_WIDTH 168
#define SWITCH_ITEM_W 136
#define SWITCH_PREVIEW_H 85 // the window's picture, as wide as the item
#define SWITCH_ROW_H 20 // its icon and title under it
#define SWITCH_ROW_GAP 6
#define SWITCH_ITEM_H (SWITCH_PREVIEW_H + SWITCH_ROW_GAP + SWITCH_ROW_H)
#define SWITCH_KEEP 2 // previews kept at twice their size, for HiDPI
#define PICK_ITEM_W 208 // the pictures to fill a snapped app's other side, at least
#define PICK_ITEM_MAX 400 // widened to fill their rows, at most
#define PICK_PREVIEW_H 130 // at PICK_ITEM_W; they keep that shape
#define PICK_ITEM_H (PICK_PREVIEW_H + SWITCH_ROW_GAP + SWITCH_ROW_H)
#define PICK_GAP 24
#define PICK_MARGIN 40 // the page's, left and right
#define PICK_RIM 4 // room round the grid for the outline, inside its scroll's clip
#define CLOCK_W 570
#define CLOCK_H 150
#define TRAY_ROW 2 // tray icons per row, at the foot of the charms bar
#define TRAY_CELL (CHARMS_WIDTH / TRAY_ROW) // one tray icon's square
#define TRAY_ICON 24
#define PANEL_GREY 0x121212
#define HINT_W 136 // the Start hint; as high as the screen's shape makes it
#define BAR_CLOCK_W 330
#define BAR_CHARM_W 104
#define BAR_PAD 16 // after the tray
#define BAR_SWITCH_GAP 14 // between the switcher's pictures over the bar
#define BAR_SWITCH_PAD 18 // round them
#define BAR_CARD_W 880 // a card over the bar: wide and low, so the bar
#define BAR_CARD_H 380 // under it stays in view
#define BAR_CARD_PAD 30

/* wl_keyboard modifier bits as the compositor sends them */
#define WL_MOD_SHIFT (1 << 0)
#define WL_MOD_CTRL (1 << 2)
#define WL_MOD_ALT (1 << 3)
#define WL_MOD_LOGO (1 << 6)

static const uint32_t backgrounds[] = {
	0x1d1d1d, 0x2e1700, 0x4e0000, 0x4e0038, 0x2d004e,
	0x1f0068, 0x001e4e, 0x004d60, 0x004a00, 0x15992a,
	0xe56c19, 0xb81b1b, 0xb81b6c, 0x691bb8, 0x1b58b8,
	0x569ce3, 0x00aaaa, 0x83ba1f, 0xd39d09, 0x180052,
};
#define COUNT(a) ((int)(sizeof(a) / sizeof((a)[0])))
static const char *const pattern_keys[] = {
	"none", "circles", "lines", "squares",
};
static const char *const pattern_labels[] = {
	"None", "Circles", "Lines", "Squares",
};

enum panel {
	PANEL_NONE,
	PANEL_CHARMS,
	PANEL_SETTINGS,
	PANEL_FLYOUT, // Networks, an app's search
	PANEL_SWITCHER,
	PANEL_HINT, // Start's picture in the corner
	PANEL_PICK, // an app for the other side of a snapped one
};

enum charm {
	CHARM_SEARCH,
	CHARM_SWITCH,
	CHARM_START,
	CHARM_SETTINGS,
	CHARM_COUNT,
};

static const char *const charm_labels[] = {
	[CHARM_SEARCH] = "Search",
	[CHARM_SWITCH] = "Switch",
	[CHARM_START] = "Start",
	[CHARM_SETTINGS] = "Settings",
};

static struct {
	struct shell_surface *panel, *clock;
	enum panel open;
	bool from_corner;
	int x, y, width, height; // where the panel ends up
	int from; // 1 slides in from the right, -1 from the left
	int64_t opened_at;
	guint slide_timer, clock_timer;
	int shown_x, shown_y, shown_w, shown_h; // where it is now
	int move_x, move_y, move_w, move_h; // the pick moving: from here
	int64_t move_at;
	guint move_timer;
	struct c8ui_widget *clock_face;

	/* Settings flyout controls, NULL when not built */
	struct c8ui_widget *page;
	struct c8ui_widget *accent, *background, *pattern, *more, *live;
	/* Keys a flyout wants before the usual ones */
	c8ui_key_fn flyout_key;
	void *flyout_key_data;

	/* Switcher, and the pick for a snapped app's other side */
	struct window **items;
	int count, index;
	uint32_t release; // C8UI_MOD_* to let go of to switch; 0: click
	struct c8ui_widget *list;
	struct window *exclude; // the snapped app: not in the pick
	struct c8ui_widget *grid; // the pick's pictures

	/* XR's charms bar, NULL when not in it: a column of
	 * what's above it (the switcher, a card, the level's room) and the
	 * bar itself, built again without touching what's above */
	struct shell_surface *bar;
	struct c8ui_widget *bar_col, *bar_above, *bar_main;
	int above_w, above_h, main_w, main_h;
	bool on_bar; // what's open is above the bar, which has the keyboard
	struct c8ui_widget *card; // what's open above the bar, when a card
	int open_key; // the button that opened it (panels_mark), 0 for none
	struct c8ui_widget *net_page; // the Settings card's Networks page
	guint leave_timer; // what was above the bar is dropping away
	struct c8ui_widget *bar_clock;
	guint bar_timer;
} p;

static void bar_build(void);
static void bar_above_set(struct c8ui_widget *w, int width, int height);
static void bar_above_leave(void);
static void show_on_bar(enum panel panel, struct c8ui_widget *content,
	uint32_t rgb, int width, int height);
static void switch_above(void);
static uint32_t flyout_colour(void);

static void text_centered(struct c8ui_widget *w, cairo_t *cr,
		struct c8ui_font font, const char *text, double cx, double y) {
	double tw, th;
	c8ui_text_size(c8ui_widget_font(w), font, text, 0, 0, &tw, &th);
	c8ui_text_draw(cr, c8ui_widget_font(w), font, text, cx - tw / 2, y, 0, 0);
}

/* Sliding in */

static void set_rect(int x, int y, int width, int height) {
	p.shown_x = x;
	p.shown_y = y;
	p.shown_w = width;
	p.shown_h = height;
	shell_surface_set_rect(p.panel, x, y, width, height);
}

static gboolean slide_tick(gpointer data) {
	double t = ease_out((double)(now_ms() - p.opened_at) / SLIDE_MS);
	int offset = (int)lround((1 - t) * p.width) * p.from;
	set_rect(p.x + offset, p.y, p.width, p.height);
	if (t >= 1) {
		p.slide_timer = 0;
		return G_SOURCE_REMOVE;
	}
	return G_SOURCE_CONTINUE;
}

static int lerp_int(int a, int b, double t) {
	return a + (int)lround((b - a) * t);
}

/* From where it was shown to p.x, p.y, p.width, p.height */
static gboolean move_tick(gpointer data) {
	double t = ease_out((double)(now_ms() - p.move_at) / MOVE_MS);
	set_rect(lerp_int(p.move_x, p.x, t), lerp_int(p.move_y, p.y, t),
		lerp_int(p.move_w, p.width, t), lerp_int(p.move_h, p.height, t));
	if (t >= 1) {
		p.move_timer = 0;
		return G_SOURCE_REMOVE;
	}
	return G_SOURCE_CONTINUE;
}

static void stop_timers(void) {
	g_clear_handle_id(&p.slide_timer, g_source_remove);
	g_clear_handle_id(&p.move_timer, g_source_remove);
	g_clear_handle_id(&p.clock_timer, g_source_remove);
}

static void show_at(enum panel panel, struct c8ui_widget *content,
		uint32_t rgb, double alpha, int x, int y, int width, int height,
		int from) {
	stop_timers();
	p.open = panel;
	p.open_key = 0;
	p.x = x;
	p.y = y;
	p.width = width;
	p.height = height;
	p.from = from;
	p.opened_at = now_ms();
	p.flyout_key = NULL;
	struct c8ui_window *win = shell_surface_window(p.panel);
	c8ui_window_set_background(win, rgb, alpha);
	c8ui_root_set_child(shell_surface_root(p.panel), content);
	/* The hint is only to point at: typing still goes to the app */
	shell_surface_grab_keyboard(p.panel, panel != PANEL_HINT);
	slide_tick(NULL);
	p.slide_timer = g_timeout_add(16, slide_tick, NULL);
}

/* A flyout: from the right edge, full height; in XR a card in
 * the middle of the shell's screen (which is ahead of you), three
 * quarters as high, coming up in place: the screen's edge is out of
 * view in the glasses. Over XR's charms bar a wide, low card. */
static void show_flyout(enum panel panel, struct c8ui_widget *content,
		uint32_t rgb) {
	if (p.bar) {
		show_on_bar(panel, content, rgb, BAR_CARD_W, BAR_CARD_H);
	} else if (shell.appearance.xr) {
		int h = shell.output_height * 3 / 4;
		show_at(panel, content, rgb, 1,
			(shell.output_width - FLYOUT_WIDTH) / 2,
			(shell.output_height - h) / 2, FLYOUT_WIDTH, h, 0);
	} else {
		show_at(panel, content, rgb, 1, shell.output_width - FLYOUT_WIDTH,
			0, FLYOUT_WIDTH, shell.output_height, 1);
	}
}

/* Full height, from the top */
static void show(enum panel panel, struct c8ui_widget *content, uint32_t rgb,
		double alpha, int x, int width, int from) {
	show_at(panel, content, rgb, alpha, x, 0, width, shell.output_height,
		from);
}

/* The compositor sends the open pick its window's moves until told
 * it's closed */
static void pick_done(void) {
	if (p.open == PANEL_PICK) {
		c8_shell_v1_pick_done(shell.proto,
			p.exclude ? p.exclude->proto : NULL);
	}
}

void panels_close(void) {
	if (p.open == PANEL_NONE) {
		return;
	}
	pick_done();
	bool on_bar = p.on_bar;
	p.on_bar = false;
	p.open = PANEL_NONE;
	p.open_key = 0;
	p.release = 0;
	p.flyout_key = NULL;
	stop_timers();
	shell_surface_grab_keyboard(p.panel, false);
	shell_surface_hide(p.panel);
	shell_surface_hide(p.clock);
	free(p.items);
	p.items = NULL;
	p.count = 0;
	p.exclude = NULL;
	if (on_bar && p.bar) {
		shell_surface_grab_keyboard(p.bar, false);
		bar_above_leave();
	}
	context_closed();
	project_closed();
}

/* Charms */

static void draw_charm_glyph(cairo_t *cr, int charm, double cx, double cy) {
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_set_line_width(cr, 2.5);
	switch (charm) {
	case CHARM_SEARCH:
		cairo_arc(cr, cx + 3, cy - 3, 9, 0, 2 * M_PI);
		cairo_move_to(cr, cx - 3.5, cy + 3.5);
		cairo_line_to(cr, cx - 12, cy + 12);
		cairo_stroke(cr);
		break;
	case CHARM_SWITCH:
		cairo_rectangle(cr, cx - 13, cy - 9, 18, 14);
		cairo_stroke(cr);
		cairo_rectangle(cr, cx - 5, cy - 3, 18, 14);
		cairo_fill(cr);
		break;
	case CHARM_START: {
		/* Our own mark from the cont8nuum icon theme */
		static struct c8ui_icon *logo;
		static bool tried;
		if (!tried) {
			logo = c8ui_icon_load(NULL, "cont8nuum");
			tried = true;
		}
		if (logo) {
			c8ui_icon_draw_fit(cr, logo, cx, cy, 32);
			break;
		}
		/* Same shape by hand: an 8 whose upper loop opens into a c */
		cairo_set_line_width(cr, 2.3);
		cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND);
		cairo_arc_negative(cr, cx, cy - 6.3, 5.7, -M_PI / 4, M_PI / 4);
		cairo_new_sub_path(cr);
		cairo_arc(cr, cx, cy + 6.3, 6.7, 0, 2 * M_PI);
		cairo_stroke(cr);
		break;
	}
	case CHARM_SETTINGS:
		for (int i = 0; i < 8; i++) {
			double a = i * M_PI / 4;
			cairo_move_to(cr, cx + cos(a) * 9, cy + sin(a) * 9);
			cairo_line_to(cr, cx + cos(a) * 14, cy + sin(a) * 14);
		}
		cairo_stroke(cr);
		cairo_arc(cr, cx, cy, 9, 0, 2 * M_PI);
		cairo_stroke(cr);
		cairo_arc(cr, cx, cy, 3.5, 0, 2 * M_PI);
		cairo_fill(cr);
		break;
	}
}

static void draw_charm(struct c8ui_widget *w, cairo_t *cr, void *data) {
	int charm = (int)(intptr_t)data;
	struct c8ui_rect *r = &w->rect;
	if (w->hovered) {
		c8ui_set_source(cr, 0x333333, 1);
		cairo_rectangle(cr, r->x, r->y, r->width, r->height);
		cairo_fill(cr);
	}
	double cx = r->x + r->width / 2;
	draw_charm_glyph(cr, charm, cx, r->y + 34);
	cairo_set_source_rgb(cr, 1, 1, 1);
	text_centered(w, cr, (struct c8ui_font){ 13, C8UI_WEIGHT_SEMILIGHT },
		charm_labels[charm], cx, r->y + 58);
}

static void switcher_open(int direction, uint32_t release, bool corner);
static struct c8ui_widget *build_pick(void);
static void pick_fit(int width);

static bool charm_event(struct c8ui_widget *w, const struct c8ui_event *ev,
		void *data) {
	if (ev->type == C8UI_EVENT_PRESS) {
		return ev->button == C8UI_BUTTON_LEFT;
	}
	if (!left_click(w, ev)) {
		return false;
	}
	switch ((int)(intptr_t)data) {
	case CHARM_SEARCH:
		start_action(C8_SHELL_V1_ACTION_SEARCH);
		break;
	case CHARM_SWITCH: {
		/* Each of the bar's buttons puts away what it opened */
		bool was_open = p.open == PANEL_SWITCHER;
		panels_close();
		if (!was_open) {
			switcher_open(0, 0, false);
		}
		break;
	}
	case CHARM_START:
		panels_close();
		c8_shell_v1_set_start_visible(shell.proto, !shell.start_visible);
		break;
	case CHARM_SETTINGS:
		if (panels_settings_card()) {
			// the bar's card, toggled
		} else if (p.open == PANEL_SETTINGS) {
			panels_close();
		} else {
			context_settings();
		}
		break;
	}
	return true;
}

/* What both clocks say: the time, the day and the date. Returns now. */
static time_t clock_words(char hm[16], char day[64], char date[64]) {
	time_t t = time(NULL);
	struct tm tm;
	localtime_r(&t, &tm);
	clock_format(hm, 16, &tm, shell.appearance.clock, false);
	strftime(day, 64, "%A", &tm);
	strftime(date, 64, "%e %B", &tm);
	return t;
}

/* Network over battery, left of the time, as on Windows 8: icons `size`
 * big from y down, `step` apart, one alone `alone` lower. Returns the room
 * they took. */
static double draw_clock_status(cairo_t *cr, double x, double y, double size,
		double step, double alone) {
	bool net = status.net != STATUS_NET_UNKNOWN;
	if (!net && !status.battery) {
		return 0;
	}
	y += net && status.battery ? 0 : alone;
	if (net) {
		status_draw_network(cr, x, y, size);
		y += step;
	}
	status_draw_battery(cr, x, y, size, PANEL_GREY);
	return step + 8;
}

static void draw_clock(struct c8ui_widget *w, cairo_t *cr, void *data) {
	char hm[16], day[64], date[64];
	time_t t = clock_words(hm, day, date);
	const char *family = c8ui_widget_font(w);
	struct c8ui_font big = { 96, C8UI_WEIGHT_LIGHT };
	struct c8ui_font small = { 26, C8UI_WEIGHT_LIGHT };
	double x = w->rect.x + 24, y = w->rect.y, tw, th;
	cairo_set_source_rgb(cr, 1, 1, 1);
	x += draw_clock_status(cr, x, y + 44, 30, 40, 18);
	/* The colon blinks with the seconds: drawn in pieces, its room kept
	 * while it's off so the minutes don't move */
	char *colon = strchr(hm, ':');
	if (colon) {
		*colon = '\0';
		const char *parts[] = { hm, ":", colon + 1 };
		for (int i = 0; i < 3; i++) {
			c8ui_text_size(family, big, parts[i], 0, 0, &tw, &th);
			if (i != 1 || t % 2 == 0) {
				c8ui_text_draw(cr, family, big, parts[i], x, y + 8, 0, 0);
			}
			x += tw;
		}
		x += 24;
	} else {
		c8ui_text_size(family, big, hm, 0, 0, &tw, &th);
		c8ui_text_draw(cr, family, big, hm, x, y + 8, 0, 0);
		x += tw + 24;
	}
	c8ui_text_draw(cr, family, small, day, x, y + 40, 0, 0);
	c8ui_text_draw(cr, family, small, date[0] == ' ' ? date + 1 : date, x,
		y + 76, 0, 0);
}

static gboolean clock_tick(gpointer data);

/* Just after each second turns over, so the colon keeps time */
static void clock_arm(void) {
	gint64 us = g_get_real_time() % G_USEC_PER_SEC;
	p.clock_timer = g_timeout_add((guint)((G_USEC_PER_SEC - us) / 1000) + 5,
		clock_tick, NULL);
}

static gboolean clock_tick(gpointer data) {
	c8ui_widget_queue_draw(p.clock_face);
	clock_arm();
	return G_SOURCE_REMOVE;
}

/* Tray icons */

static void draw_tray(struct c8ui_widget *w, cairo_t *cr, void *data) {
	struct c8ui_rect *r = &w->rect;
	if (w->hovered) {
		c8ui_set_source(cr, 0x333333, 1);
		cairo_rectangle(cr, r->x, r->y, r->width, r->height);
		cairo_fill(cr);
	}
	tray_draw(data, cr, r->x + r->width / 2, r->y + r->height / 2, TRAY_ICON);
}

static bool tray_event(struct c8ui_widget *w, const struct c8ui_event *ev,
		void *data) {
	if (ev->type == C8UI_EVENT_PRESS) {
		return true;
	}
	if (ev->type != C8UI_EVENT_RELEASE ||
			!c8ui_rect_contains(&w->rect, ev->x, ev->y)) {
		return false;
	}
	/* Where the icon is on the screen, for apps that place windows by it */
	int x = shell.output_width - CHARMS_WIDTH +
		(int)(w->rect.x + w->rect.width / 2);
	int y = (int)(w->rect.y + w->rect.height / 2);
	tray_click(data, ev->button, x, y);
	return true;
}

static void build_clock(void) {
	struct c8ui_widget *face = c8ui_canvas_new(CLOCK_W, CLOCK_H, draw_clock,
		NULL, NULL);
	/* Opening the charms again builds a new face before the old one
	 * goes: tracked, so only the one that's still ours is forgotten */
	c8ui_widget_track(face, &p.clock_face);
	c8ui_widget_set_scheme(face, C8UI_SCHEME_DARK);
	c8ui_root_set_child(shell_surface_root(p.clock), face);
	shell_surface_set_rect(p.clock, 48, shell.output_height - CLOCK_H - 48,
		CLOCK_W, CLOCK_H);
}

static struct c8ui_widget *charms_bar(void);

/* Rebuilt when icons come or go while the bar is up */
static bool panel_key(const struct c8ui_event *ev, void *data);
static void panel_modifiers(struct c8ui_window *win, uint32_t mods,
	void *data);
static void dismissed(struct shell_surface *surface, void *data);

static void tray_changed(void *data) {
	if (p.open == PANEL_CHARMS) {
		c8ui_root_set_child(shell_surface_root(p.panel), charms_bar());
	}
	if (p.bar) {
		bar_build();
	}
}

/* The charms in the middle, the tray's icons at the foot in two columns */
static struct c8ui_widget *charms_bar(void) {
	struct c8ui_widget *bar = c8ui_box_new(C8UI_VERTICAL, 0);
	c8ui_widget_set_scheme(bar, C8UI_SCHEME_DARK);
	struct c8ui_widget *above = c8ui_spacer_new(0, 0);
	above->expand = true;
	c8ui_widget_add(bar, above);
	for (int i = 0; i < CHARM_COUNT; i++) {
		struct c8ui_widget *c = c8ui_canvas_new(CHARMS_WIDTH, CHARM_HEIGHT,
			draw_charm, charm_event, (void *)(intptr_t)i);
		c8ui_widget_add(bar, c);
	}
	struct c8ui_widget *below = c8ui_spacer_new(0, 0);
	below->expand = true;
	c8ui_widget_add(bar, below);
	int icons = tray_count();
	for (int i = 0; i < icons; i += TRAY_ROW) {
		struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 0);
		for (int j = i; j < icons && j < i + TRAY_ROW; j++) {
			struct tray_item *it = tray_nth(j);
			struct c8ui_widget *c = c8ui_canvas_new(TRAY_CELL, TRAY_CELL,
				draw_tray, tray_event, it);
			c8ui_widget_set_tooltip(c, tray_title(it));
			c8ui_widget_add(row, c);
		}
		c8ui_widget_add(bar, row);
	}
	return bar;
}

static void open_charms(bool corner) {
	struct c8ui_widget *bar = charms_bar();

	p.from_corner = corner;
	show(PANEL_CHARMS, bar, PANEL_GREY, 1,
		shell.output_width - CHARMS_WIDTH, CHARMS_WIDTH, 1);

	build_clock();
	clock_arm(); // show() stopped the one before
}

/* XR's charms bar: one row, clock and status, the charms,
 * quick settings, the tray. The compositor shows it in the glasses as you look down. */

static void draw_bar_line(struct c8ui_widget *w, cairo_t *cr, void *data) {
	c8ui_set_source(cr, shell.appearance.accent, 1);
	cairo_rectangle(cr, w->rect.x, w->rect.y, w->rect.width, w->rect.height);
	cairo_fill(cr);
}

static void draw_bar_clock(struct c8ui_widget *w, cairo_t *cr, void *data) {
	char hm[16], day[64], date[64];
	clock_words(hm, day, date);
	const char *family = c8ui_widget_font(w);
	struct c8ui_font big = { 54, C8UI_WEIGHT_LIGHT };
	struct c8ui_font small = { 17, C8UI_WEIGHT_LIGHT };
	double x = w->rect.x + 24, y = w->rect.y, tw, th;
	cairo_set_source_rgb(cr, 1, 1, 1);
	x += draw_clock_status(cr, x, y + 22, 22, 30, 14);
	c8ui_text_size(family, big, hm, 0, 0, &tw, &th);
	c8ui_text_draw(cr, family, big, hm, x, y + (w->rect.height - th) / 2,
		0, 0);
	x += tw + 18;
	c8ui_text_draw(cr, family, small, day, x, y + 24, 0, 0);
	c8ui_text_draw(cr, family, small, date[0] == ' ' ? date + 1 : date, x,
		y + 48, 0, 0);
}

/* At each minute's turn */
static gboolean bar_tick(gpointer data) {
	c8ui_widget_queue_draw(p.bar_clock);
	gint64 us = g_get_real_time() % (60 * G_USEC_PER_SEC);
	p.bar_timer = g_timeout_add((guint)((60 * G_USEC_PER_SEC - us) / 1000) +
		5, bar_tick, NULL);
	return G_SOURCE_REMOVE;
}

static bool bar_tray_event(struct c8ui_widget *w, const struct c8ui_event *ev,
		void *data) {
	if (ev->type == C8UI_EVENT_PRESS) {
		return true;
	}
	if (ev->type != C8UI_EVENT_RELEASE ||
			!c8ui_rect_contains(&w->rect, ev->x, ev->y)) {
		return false;
	}
	/* Off every screen: an app placing a window by it gets the middle of
	 * the shell's, which is ahead of you */
	tray_click(data, ev->button, shell.output_width / 2,
		shell.output_height / 2);
	return true;
}

static struct c8ui_widget *bar_main_new(int *width, int *height) {
	struct c8ui_widget *col = c8ui_box_new(C8UI_VERTICAL, 0);
	c8ui_widget_set_scheme(col, C8UI_SCHEME_DARK);
	c8ui_widget_set_background(col, PANEL_GREY);
	col->align = C8UI_ALIGN_CENTER;
	*height = BAR_LINE + CHARM_HEIGHT;
	c8ui_widget_add(col, c8ui_canvas_new(0, BAR_LINE, draw_bar_line, NULL,
		NULL));
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 0);
	c8ui_widget_add(col, row);
	struct c8ui_widget *face = c8ui_canvas_new(BAR_CLOCK_W, CHARM_HEIGHT,
		draw_bar_clock, NULL, NULL);
	c8ui_widget_track(face, &p.bar_clock);
	c8ui_widget_add(row, face);
	/* No Search: from the bar it only went to Start's search, behind
	 * the bar, and typing on Start does that */
	int charms = 0;
	for (int i = 0; i < CHARM_COUNT; i++) {
		if (i == CHARM_SEARCH) {
			continue;
		}
		c8ui_widget_add(row, c8ui_canvas_new(BAR_CHARM_W, CHARM_HEIGHT,
			draw_charm, charm_event, (void *)(intptr_t)i));
		charms++;
	}
	/* Quick settings most often wanted; the rest are in Settings. Right
	 * after Settings, as more charms. */
	int quick_w;
	c8ui_widget_add(row, quick_row_new(BAR_CHARM_W, CHARM_HEIGHT, &quick_w));
	/* The tray two high, in columns */
	int icons = tray_count(), cols = (icons + 1) / 2;
	if (icons > 0) {
		c8ui_widget_add(row, c8ui_spacer_new(BAR_PAD, 0));
	}
	for (int c = 0; c < cols; c++) {
		struct c8ui_widget *stack = c8ui_box_new(C8UI_VERTICAL, 0);
		c8ui_widget_add(stack, c8ui_spacer_new(0,
			(CHARM_HEIGHT - 2 * TRAY_CELL) / 2));
		for (int j = c * 2; j < icons && j < c * 2 + 2; j++) {
			struct tray_item *it = tray_nth(j);
			struct c8ui_widget *cell = c8ui_canvas_new(TRAY_CELL, TRAY_CELL,
				draw_tray, bar_tray_event, it);
			c8ui_widget_set_tooltip(cell, tray_title(it));
			c8ui_widget_add(stack, cell);
		}
		c8ui_widget_add(row, stack);
	}
	*width = BAR_CLOCK_W + charms * BAR_CHARM_W + quick_w +
		(icons > 0 ? BAR_PAD + cols * TRAY_CELL : 0) + BAR_PAD;
	col->fixed_width = *width;
	return col;
}

/* As big as what's above and the bar under it; clear round them */
static void bar_size(void) {
	int w = p.above_w > p.main_w ? p.above_w : p.main_w;
	shell_surface_set_rect(p.bar, 0, 0, w, p.above_h + p.main_h);
}

static void bar_build(void) {
	if (p.bar_col == NULL) {
		p.bar_col = c8ui_box_new(C8UI_VERTICAL, 0);
		c8ui_widget_set_scheme(p.bar_col, C8UI_SCHEME_DARK);
		p.bar_above = c8ui_box_new(C8UI_VERTICAL, 0);
		p.bar_above->align = C8UI_ALIGN_CENTER;
		c8ui_widget_add(p.bar_col, p.bar_above);
		c8ui_root_set_child(shell_surface_root(p.bar), p.bar_col);
	}
	if (p.bar_main) {
		c8ui_widget_destroy(p.bar_main);
	}
	p.bar_main = bar_main_new(&p.main_w, &p.main_h);
	c8ui_widget_add(p.bar_col, p.bar_main);
	bar_size();
}

/* Above the bar, centred over it, a little apart: the switcher, a card,
 * or room for the level (NULL, height: quick.c draws it there) */
static void bar_above_set(struct c8ui_widget *w, int width, int height) {
	if (p.bar == NULL) {
		return;
	}
	g_clear_handle_id(&p.leave_timer, g_source_remove);
	c8ui_widget_clear(p.bar_above);
	p.card = NULL;
	p.above_w = p.above_h = 0;
	if (w || height > 0) {
		c8ui_widget_add(p.bar_above, w ? w : c8ui_spacer_new(width, height));
		c8ui_widget_add(p.bar_above, c8ui_spacer_new(0, BAR_ABOVE_GAP));
		p.above_w = width;
		p.above_h = height + BAR_ABOVE_GAP;
	}
	bar_size();
}

static gboolean above_left(gpointer data) {
	p.leave_timer = 0;
	bar_above_set(NULL, 0, 0);
	return G_SOURCE_REMOVE;
}

/* What's above the bar closing drops away first (c8ui_widget_leave_down)
 * and the surface shrinks after; anything shown meanwhile replaces it */
static void bar_above_leave(void) {
	if (p.bar_above->child_count == 0 || p.leave_timer) {
		return;
	}
	c8ui_widget_leave_down(p.bar_above->children[0]);
	p.card = NULL;
	p.leave_timer = g_timeout_add(C8UI_LEAVE_MS + 30, above_left, NULL);
}

/* A card above the bar, with the keyboard; it rises into place. Whatever
 * was there goes. */
static void show_on_bar(enum panel panel, struct c8ui_widget *content,
		uint32_t rgb, int width, int height) {
	quick_level_close();
	stop_timers();
	p.open = panel;
	p.open_key = 0;
	p.flyout_key = NULL;
	struct c8ui_widget *card = c8ui_box_new(C8UI_VERTICAL, 0);
	c8ui_widget_set_scheme(card, C8UI_SCHEME_DARK);
	c8ui_widget_set_background(card, rgb);
	card->fixed_width = width;
	card->fixed_height = height;
	content->expand = true;
	content->fill = true;
	c8ui_widget_add(card, content);
	p.on_bar = true;
	bar_above_set(card, width, height);
	p.card = card;
	c8ui_widget_enter_up(card);
	shell_surface_grab_keyboard(p.bar, true);
}

void panels_show_bar_card(struct c8ui_widget *content, int width,
		int height) {
	shell_surface_hide(p.clock);
	p.from_corner = false;
	if (p.bar == NULL) { // a compositor without the bar
		show_at(PANEL_FLYOUT, content, flyout_colour(), 1,
			(shell.output_width - width) / 2,
			(shell.output_height - height) / 2, width, height, 0);
		return;
	}
	show_on_bar(PANEL_FLYOUT, content, flyout_colour(), width, height);
}

/* The card above the bar grew or shrank (apps came to the mixer) */
void panels_card_height(int height) {
	if (p.card == NULL || p.card->fixed_height == height) {
		return;
	}
	p.card->fixed_height = height;
	p.above_h = height + BAR_ABOVE_GAP;
	c8ui_widget_queue_layout(p.card);
	bar_size();
}

/* What a button opened, so pressing it again puts it away */
void panels_mark(int key) {
	p.open_key = key;
}

bool panels_is(int key) {
	return p.open != PANEL_NONE && key != 0 && p.open_key == key;
}

/* Made in XR, gone out of it */
static void bar_update(void) {
	bool want = shell.appearance.xr;
	if (want && p.bar == NULL) {
		p.bar = shell_surface_new(C8_SHELL_V1_ROLE_BAR);
		struct c8ui_window *win = shell_surface_window(p.bar);
		/* Clear: only the bar and what's above it are drawn */
		c8ui_window_set_background(win, PANEL_GREY, 0);
		/* The switcher is on it in XR, with the keyboard */
		c8ui_root_set_key_handler(shell_surface_root(p.bar), panel_key,
			NULL);
		c8ui_window_on_modifiers(win, panel_modifiers, NULL);
		shell_surface_on_dismiss(p.bar, dismissed, NULL);
		bar_build();
		bar_tick(NULL);
	} else if (!want && p.bar) {
		if (p.on_bar) {
			panels_close();
		}
		g_clear_handle_id(&p.bar_timer, g_source_remove);
		shell_surface_destroy(p.bar);
		p.bar = NULL;
		p.bar_col = p.bar_above = p.bar_main = NULL;
		p.above_w = p.above_h = p.main_w = p.main_h = 0;
		p.bar_clock = NULL;
	} else if (p.bar) {
		bar_build(); // the accent, the clock's format
	}
}

/* Settings flyout */

static void set_appearance(const char *key, const char *value) {
	c8_shell_v1_set_appearance(shell.proto, key, value);
}

static void set_colour(const char *key, uint32_t rgb) {
	char value[16];
	snprintf(value, sizeof(value), "#%06x", rgb & 0xffffff);
	set_appearance(key, value);
}

static void accent_changed(struct c8ui_widget *w, void *data) {
	set_colour("accent", c8ui_swatches_get(w));
}

static void background_changed(struct c8ui_widget *w, void *data) {
	set_colour("background", c8ui_swatches_get(w));
}

static void pattern_changed(struct c8ui_widget *w, void *data) {
	int i = c8ui_combo_get(w);
	if (i >= 0 && i < COUNT(pattern_keys)) {
		set_appearance("pattern", pattern_keys[i]);
	}
}

static void toggle_changed(struct c8ui_widget *w, void *data) {
	set_appearance(data, c8ui_toggle_get(w) ? "true" : "false");
}

static void pc_settings_clicked(struct c8ui_widget *w, void *data) {
	panels_close();
	c8_shell_v1_run(shell.proto, C8_SHELL_V1_COMMAND_PC_SETTINGS);
}

static int pattern_index(void) {
	const char *cur = shell.appearance.pattern ?
		shell.appearance.pattern : "circles";
	for (int i = 0; i < COUNT(pattern_keys); i++) {
		if (strcmp(cur, pattern_keys[i]) == 0) {
			return i;
		}
	}
	return 0;
}

static uint32_t flyout_colour(void) {
	return c8ui_shade(shell.appearance.background, 0.75);
}

static void caption(struct c8ui_widget *box, const char *text) {
	c8ui_widget_add(box, c8ui_label_new(text, C8UI_TEXT_CAPTION));
}

/* Over XR's charms bar the Settings card's pivot names its pages, so
 * what goes in them has no "Settings" heading of its own */
bool panels_headed(void) {
	return p.bar == NULL;
}

/* A page's heading: "Settings" over what it's for */
static void heading(struct c8ui_widget *box, const char *what) {
	if (panels_headed()) {
		c8ui_widget_add(box, c8ui_label_new("Settings", C8UI_TEXT_SUBHEADER));
	}
	struct c8ui_widget *sub = c8ui_label_new(what, C8UI_TEXT_BODY_STRONG);
	c8ui_label_set_color(sub, C8UI_COLOR_SECONDARY);
	c8ui_widget_add(box, sub);
}

/* Start's part of the flyout: Personalise. Over the bar in two
 * columns, as the card is wide and low. */
static struct c8ui_widget *personalise_new(void) {
	struct appearance *a = &shell.appearance;
	struct c8ui_widget *body = c8ui_box_new(C8UI_VERTICAL, 12);
	heading(body, "Personalise");
	struct c8ui_widget *left = body, *right = body;
	if (!panels_headed()) {
		struct c8ui_widget *cols = c8ui_box_new(C8UI_HORIZONTAL, 40);
		left = c8ui_box_new(C8UI_VERTICAL, 12);
		right = c8ui_box_new(C8UI_VERTICAL, 12);
		left->fixed_width = right->fixed_width = 250;
		c8ui_widget_add(cols, left);
		c8ui_widget_add(cols, right);
		c8ui_widget_add(body, cols);
	}

	caption(left, "Accent colour");
	c8ui_widget_track(c8ui_swatches_new(metro_palette, METRO_PALETTE_LEN, a->accent,
		accent_changed, NULL), &p.accent);
	c8ui_swatches_set_size(p.accent, 24);
	c8ui_widget_add(left, p.accent);
	caption(left, "Background");
	c8ui_widget_track(c8ui_swatches_new(backgrounds, COUNT(backgrounds),
		a->background, background_changed, NULL), &p.background);
	c8ui_swatches_set_size(p.background, 24);
	c8ui_widget_add(left, p.background);
	c8ui_widget_track(c8ui_combo_new("Pattern", pattern_labels,
		COUNT(pattern_labels), pattern_index(), pattern_changed, NULL),
		&p.pattern);
	c8ui_widget_add(right, p.pattern);
	c8ui_widget_track(c8ui_toggle_new("Show more tiles", NULL, a->more_tiles,
		toggle_changed, "more_tiles"), &p.more);
	c8ui_widget_add(right, p.more);
	c8ui_widget_track(c8ui_toggle_new("Live tiles", NULL, a->live_tiles,
		toggle_changed, "live_tiles"), &p.live);
	c8ui_widget_add(right, p.live);
	return body;
}

/* An app without settings of its own: Personalise is Start's, so not
 * here; only the quick settings under it */
static struct c8ui_widget *plain_new(void) {
	struct c8ui_widget *body = c8ui_box_new(C8UI_VERTICAL, 12);
	char *title = context_front_title();
	heading(body, title ? title : "Desktop");
	g_free(title);
	struct c8ui_widget *none = c8ui_label_new("This app has no settings "
		"here.", C8UI_TEXT_BODY);
	c8ui_label_set_max_lines(none, 3);
	c8ui_widget_add(body, none);
	return body;
}

/* The quick settings and the way to the rest */
static struct c8ui_widget *settings_foot(int spacing) {
	struct c8ui_widget *foot = c8ui_box_new(C8UI_VERTICAL, spacing);
	c8ui_widget_add(foot, quick_tiles_new());
	c8ui_widget_add(foot, c8ui_link_new("Change PC settings",
		pc_settings_clicked, NULL));
	return foot;
}

/* The Networks page is made when it's first shown: it scans for Wi-Fi */
static void settings_page_fill(int index) {
	if (index == 1 && p.net_page && p.net_page->child_count == 0) {
		struct c8ui_widget *net = quick_networks_new();
		net->expand = true;
		net->fill = true;
		c8ui_widget_add(p.net_page, net);
	}
}

static void settings_page_chosen(struct c8ui_widget *w, void *data) {
	settings_page_fill(c8ui_pivot_get(w));
}

/* XR: Settings and Networks as the pages of one wide card over the bar,
 * side by side within each: what the app or Start has beside the quick
 * settings; airplane mode beside the Wi-Fi list */
static void settings_card(struct c8ui_widget *body) {
	struct c8ui_widget *card = c8ui_box_new(C8UI_VERTICAL, 0);
	c8ui_box_set_padding(card, BAR_CARD_PAD, 24, BAR_CARD_PAD, 24);
	struct c8ui_widget *pivot = c8ui_pivot_new(settings_page_chosen, NULL);
	pivot->expand = true;
	c8ui_widget_add(card, pivot);

	struct c8ui_widget *page = c8ui_box_new(C8UI_HORIZONTAL, 40);
	c8ui_widget_track(page, &p.page);
	struct c8ui_widget *scroll = c8ui_scroll_new(body);
	scroll->expand = true;
	scroll->fill = true;
	c8ui_widget_add(page, scroll);
	c8ui_widget_add(page, settings_foot(16));
	c8ui_pivot_add(pivot, "Settings", page);

	struct c8ui_widget *net = c8ui_box_new(C8UI_VERTICAL, 0);
	c8ui_widget_track(net, &p.net_page);
	c8ui_pivot_add(pivot, "Networks", net);

	show_on_bar(PANEL_SETTINGS, card, flyout_colour(), BAR_CARD_W,
		BAR_CARD_H);
	c8ui_widget_grab_focus(pivot); // Ctrl+Tab and the arrows turn it
}

void panels_open_settings_with(struct c8ui_widget *body) {
	if (body == NULL) {
		body = shell.start_visible ? personalise_new() : plain_new();
		c8ui_box_set_padding(body, panels_headed() ? 30 : 0,
			panels_headed() ? 32 : 4, panels_headed() ? 30 : 0,
			panels_headed() ? 24 : 0);
	}
	shell_surface_hide(p.clock);
	p.from_corner = false;
	if (p.bar) {
		settings_card(body);
		return;
	}

	/* The controls scroll on short screens; the footer stays put */
	struct c8ui_widget *page = c8ui_box_new(C8UI_VERTICAL, 0);
	c8ui_widget_set_scheme(page, C8UI_SCHEME_DARK);
	c8ui_widget_track(page, &p.page);
	struct c8ui_widget *scroll = c8ui_scroll_new(body);
	scroll->expand = true;
	scroll->fill = true;
	c8ui_widget_add(page, scroll);
	struct c8ui_widget *foot = settings_foot(20);
	c8ui_box_set_padding(foot, 24, 16, 24, 36);
	c8ui_widget_add(page, foot);
	show_flyout(PANEL_SETTINGS, page, flyout_colour());
	c8ui_widget_enter(page);
}

/* XR: the Settings charm and Super+I, which put the card away
 * whichever page is up. False without the charms bar. */
bool panels_settings_card(void) {
	if (p.bar == NULL) {
		return false;
	}
	if (p.open == PANEL_SETTINGS) {
		panels_close();
	} else {
		context_settings(); // the app in front may have its own
	}
	return true;
}

void panels_open_settings(void) {
	context_settings();
}

void panels_show_card(struct c8ui_widget *page) {
	struct c8ui_widget *card = c8ui_box_new(C8UI_VERTICAL, 0);
	c8ui_widget_set_scheme(card, C8UI_SCHEME_DARK);
	c8ui_box_set_padding(card, 30, 28, 30, 30);
	c8ui_widget_add(card, page);
	double w, h;
	shell_surface_hide(p.clock);
	p.from_corner = false;
	if (p.bar) {
		/* As wide as it is (the pages lie sideways there), never
		 * taller than the bar's cards */
		c8ui_widget_measure(card, BAR_CARD_W, &w, &h);
		int width = (int)ceil(w) < FLYOUT_WIDTH ? FLYOUT_WIDTH :
			(int)ceil(w);
		show_on_bar(PANEL_FLYOUT, card, flyout_colour(),
			width > BAR_CARD_W ? BAR_CARD_W : width,
			(int)ceil(h) > BAR_CARD_H ? BAR_CARD_H : (int)ceil(h));
		return;
	}
	c8ui_widget_measure(card, FLYOUT_WIDTH, &w, &h);
	int height = (int)ceil(h);
	if (height > shell.output_height * 3 / 4) {
		height = shell.output_height * 3 / 4;
	}
	show_at(PANEL_FLYOUT, card, flyout_colour(), 1,
		(shell.output_width - FLYOUT_WIDTH) / 2,
		(shell.output_height - height) / 2, FLYOUT_WIDTH, height, 0);
	c8ui_widget_enter(card);
}

void panels_show_flyout(struct c8ui_widget *page, c8ui_key_fn key,
		void *data) {
	shell_surface_hide(p.clock);
	p.from_corner = false;
	show_flyout(PANEL_FLYOUT, page, flyout_colour());
	p.flyout_key = key;
	p.flyout_key_data = data;
	if (!p.on_bar) {
		c8ui_widget_enter(page);
	}
}

static void status_changed(void *data) {
	c8ui_widget_queue_draw(p.clock_face);
	c8ui_widget_queue_draw(p.bar_clock);
	quick_status_changed();
}

void panels_appearance_changed(void) {
	struct appearance *a = &shell.appearance;
	bar_update();
	if (p.open == PANEL_FLYOUT) {
		c8ui_window_set_background(shell_surface_window(p.panel),
			flyout_colour(), 1);
	}
	if (p.card) { // over XR's bar
		c8ui_widget_set_background(p.card, flyout_colour());
	}
	if (p.page == NULL) {
		return;
	}
	c8ui_window_set_background(shell_surface_window(p.panel),
		flyout_colour(), 1);
	if (p.accent == NULL) {
		return; // an app's settings
	}
	c8ui_swatches_set(p.accent, a->accent);
	c8ui_swatches_set(p.background, a->background);
	c8ui_combo_set(p.pattern, pattern_index());
	c8ui_toggle_set(p.more, a->more_tiles);
	c8ui_toggle_set(p.live, a->live_tiles);
}

/* Switcher */

static const char *window_label(struct window *w) {
	return w->title ? w->title : w->app_id ? w->app_id : "Untitled";
}

/* The app's icon: its tile's, else its desktop entry's, else one named
 * after the app id */
static void load_icon(struct window *win) {
	if (win->icon_tried) {
		return;
	}
	win->icon_tried = true;
	if (win->app_id == NULL) {
		return;
	}
	const char *theme = shell.appearance.icon_theme;
	struct tile *tile = tile_for_app(win->app_id);
	if (tile && tile->icon) {
		win->icon = c8ui_icon_load(theme, tile->icon);
	}
	const char *entry = win->icon ? NULL : app_entry_icon(win->app_id);
	if (entry) {
		win->icon = c8ui_icon_load(theme, entry);
	}
	if (win->icon == NULL) {
		win->icon = c8ui_icon_load(theme, win->app_id);
	}
}

/* The window's picture fitted into the box, or till there is one, its
 * tile colour and icon */
static void draw_preview(cairo_t *cr, struct window *win, double x,
		double y, double w, double h) {
	cairo_surface_t *img = win->preview;
	if (img == NULL) {
		c8ui_set_source(cr, win->styled ? win->style_rgb : 0x404040, 1);
		cairo_rectangle(cr, x, y, w, h);
		cairo_fill(cr);
		if (win->icon) {
			c8ui_icon_draw_fit(cr, win->icon, x + w / 2, y + h / 2, 40);
		}
		return;
	}
	c8ui_draw_surface_fit(cr, img, x, y, w, h, 0);
}

static void draw_window_item(struct c8ui_widget *w, cairo_t *cr,
		struct window *win, double preview_h, bool outlined) {
	struct c8ui_rect *r = &w->rect;
	load_icon(win);
	draw_preview(cr, win, r->x, r->y, r->width, preview_h);

	/* The app's icon, then the window's name */
	double row = r->y + preview_h + SWITCH_ROW_GAP;
	double text_x = r->x;
	if (win->icon) {
		c8ui_icon_draw_fit(cr, win->icon, r->x + SWITCH_ROW_H / 2.0,
			row + SWITCH_ROW_H / 2.0, SWITCH_ROW_H);
		text_x += SWITCH_ROW_H + 6;
	}
	struct c8ui_font font = { 12, C8UI_WEIGHT_SEMILIGHT };
	double tw, th;
	c8ui_text_size(c8ui_widget_font(w), font, window_label(win),
		r->x + r->width - text_x, 1, &tw, &th);
	cairo_set_source_rgb(cr, 1, 1, 1);
	c8ui_text_draw(cr, c8ui_widget_font(w), font, window_label(win), text_x,
		row + round((SWITCH_ROW_H - th) / 2), r->x + r->width - text_x, 1);

	if (outlined || w->hovered) {
		cairo_set_source_rgb(cr, 1, 1, 1);
		cairo_set_line_width(cr, 3);
		cairo_rectangle(cr, r->x - 1.5, r->y - 1.5, r->width + 3,
			preview_h + 3);
		cairo_stroke(cr);
	}
}

/* A window in the switcher, or bigger in the pick for a snapped app's
 * other side */
static void draw_item(struct c8ui_widget *w, cairo_t *cr, void *data) {
	int i = (int)(intptr_t)data;
	if (i < p.count) {
		draw_window_item(w, cr, p.items[i], p.open == PANEL_PICK ?
			w->rect.height - SWITCH_ROW_GAP - SWITCH_ROW_H :
			SWITCH_PREVIEW_H, i == p.index);
	}
}

/* A fresh picture of each window every time the switcher opens; the
 * last one shows meanwhile */
static void capture_windows(void) {
	bool pick = p.open == PANEL_PICK;
	for (int i = 0; i < p.count; i++) {
		window_capture(p.items[i],
			(pick ? PICK_ITEM_MAX : SWITCH_ITEM_W) * SWITCH_KEEP,
			(pick ? PICK_ITEM_MAX * PICK_PREVIEW_H / PICK_ITEM_W :
			SWITCH_PREVIEW_H) * SWITCH_KEEP);
	}
}

void panels_preview_ready(struct window *w) {
	if ((p.open == PANEL_SWITCHER || p.open == PANEL_PICK) && p.list) {
		c8ui_widget_queue_draw(p.list);
	}
}

static void switcher_commit(void) {
	struct window *win = p.index >= 0 && p.index < p.count ?
		p.items[p.index] : NULL;
	struct c8_shell_window_v1 *proto = win ? win->proto : NULL;
	panels_close();
	if (proto) {
		c8_shell_window_v1_activate(proto);
	}
}

static bool item_event(struct c8ui_widget *w, const struct c8ui_event *ev,
		void *data) {
	if (ev->type == C8UI_EVENT_PRESS) {
		return ev->button == C8UI_BUTTON_LEFT;
	}
	if (!left_click(w, ev)) {
		return false;
	}
	p.index = (int)(intptr_t)data;
	switcher_commit();
	return true;
}

/* Every window but p.exclude, most recently used first */
static void collect_windows(void) {
	free(p.items);
	p.items = calloc(wl_list_length(&shell.windows) + 1, sizeof(*p.items));
	p.count = 0;
	struct window *w;
	wl_list_for_each(w, &shell.windows, link) {
		if (w != p.exclude) {
			p.items[p.count++] = w;
		}
	}
}

static struct c8ui_widget *build_list(void) {
	struct c8ui_widget *list = c8ui_box_new(C8UI_VERTICAL, 14);
	c8ui_box_set_padding(list, 0, 24, 0, 24);
	c8ui_widget_set_scheme(list, C8UI_SCHEME_DARK);
	for (int i = 0; i < p.count; i++) {
		struct c8ui_widget *item = c8ui_canvas_new(SWITCH_ITEM_W,
			SWITCH_ITEM_H, draw_item, item_event, (void *)(intptr_t)i);
		item->align = C8UI_ALIGN_CENTER;
		c8ui_widget_add(list, item);
	}
	c8ui_widget_track(list, &p.list);
	return list;
}

/* XR: the same pictures side by side, over the charms bar */
static struct c8ui_widget *switch_row(int *width) {
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, BAR_SWITCH_GAP);
	c8ui_box_set_padding(row, BAR_SWITCH_PAD, BAR_SWITCH_PAD,
		BAR_SWITCH_PAD, BAR_SWITCH_PAD);
	c8ui_widget_set_background(row, PANEL_GREY);
	for (int i = 0; i < p.count; i++) {
		c8ui_widget_add(row, c8ui_canvas_new(SWITCH_ITEM_W, SWITCH_ITEM_H,
			draw_item, item_event, (void *)(intptr_t)i));
	}
	*width = p.count * SWITCH_ITEM_W + (p.count - 1) * BAR_SWITCH_GAP +
		2 * BAR_SWITCH_PAD;
	c8ui_widget_track(row, &p.list);
	return row;
}

static void switch_above(void) {
	int w;
	struct c8ui_widget *row = switch_row(&w);
	bar_above_set(row, w, SWITCH_ITEM_H + 2 * BAR_SWITCH_PAD);
}

static uint32_t wl_to_c8ui_mods(uint32_t mods) {
	uint32_t out = 0;
	if (mods & WL_MOD_SHIFT) {
		out |= C8UI_MOD_SHIFT;
	}
	if (mods & WL_MOD_CTRL) {
		out |= C8UI_MOD_CTRL;
	}
	if (mods & WL_MOD_ALT) {
		out |= C8UI_MOD_ALT;
	}
	if (mods & WL_MOD_LOGO) {
		out |= C8UI_MOD_SUPER;
	}
	return out;
}

static void switcher_open(int direction, uint32_t release, bool corner) {
	p.exclude = NULL;
	collect_windows();
	if (p.count == 0) {
		free(p.items);
		p.items = NULL;
		return;
	}
	/* From an app, the first step goes to the one before it */
	int i = !shell.start_visible && direction != 0 ? direction : 0;
	p.index = (i + p.count) % p.count;
	p.release = release;
	p.from_corner = corner;
	if (p.bar) {
		/* Over the charms bar, which the compositor brings up where
		 * you look while it has the keyboard */
		quick_level_close();
		p.open = PANEL_SWITCHER;
		p.open_key = 0;
		p.on_bar = true;
		capture_windows();
		switch_above();
		c8ui_widget_enter_up(p.list);
		shell_surface_grab_keyboard(p.bar, true);
		return;
	}
	capture_windows();
	show(PANEL_SWITCHER, build_list(), PANEL_GREY, 0.94, 0, SWITCHER_WIDTH,
		-1);
}

static void switcher_step(int direction) {
	if (p.count > 0) {
		p.index = (p.index + direction + p.count) % p.count;
	}
	c8ui_widget_queue_draw(p.list);
}

void panels_switcher(int direction, uint32_t modifiers) {
	uint32_t release = wl_to_c8ui_mods(modifiers);
	if (p.open != PANEL_SWITCHER) {
		panels_close();
		switcher_open(direction, release, false);
		return;
	}
	if (release) {
		p.release = release;
	}
	switcher_step(direction);
}

void panels_windows_changed(void) {
	if (p.open != PANEL_SWITCHER && p.open != PANEL_PICK) {
		return;
	}
	/* The snapped app itself went: the compositor's snap 0 follows,
	 * but its window must not be looked for meanwhile */
	bool gone = p.exclude != NULL;
	struct window *ex;
	wl_list_for_each(ex, &shell.windows, link) {
		if (ex == p.exclude) {
			gone = false;
		}
	}
	if (gone) {
		p.exclude = NULL; // its window may be freed: pick_done names none
		panels_close();
		return;
	}
	struct window *cur = p.index < p.count ? p.items[p.index] : NULL;
	/* Only titles changed (apps retitle as the switcher takes the
	 * keyboard): redraw, keep the list and where we are in it */
	bool same = true;
	int n = 0;
	struct window *w;
	wl_list_for_each(w, &shell.windows, link) {
		if (w == p.exclude) {
			continue;
		}
		if (n >= p.count || p.items[n++] != w) {
			same = false;
			break;
		}
	}
	if (same && n == p.count) {
		c8ui_widget_queue_draw(p.list);
		return;
	}
	collect_windows();
	if (p.count == 0) {
		panels_close();
		return;
	}
	p.index = 0;
	for (int i = 0; i < p.count; i++) {
		if (p.items[i] == cur) {
			p.index = i;
		}
	}
	capture_windows(); // the new ones too
	if (p.on_bar) {
		switch_above();
		return;
	}
	c8ui_root_set_child(shell_surface_root(p.panel),
		p.open == PANEL_PICK ? build_pick() : build_list());
	if (p.open == PANEL_PICK) {
		pick_fit(p.width);
	}
}

/* Picking an app for the other side of a snapped one: the compositor
 * says which app is snapped and where the rest of the screen is; the
 * other apps' pictures go there, and clicking one activates it, which
 * puts it beside the snapped app */

static struct c8ui_widget *build_pick(void) {
	struct c8ui_widget *page = c8ui_box_new(C8UI_VERTICAL, 28);
	c8ui_box_set_padding(page, PICK_MARGIN - PICK_RIM, 48,
		PICK_MARGIN - PICK_RIM, 40);
	c8ui_widget_set_scheme(page, C8UI_SCHEME_DARK);
	struct c8ui_widget *title = c8ui_label_new("Choose an app for this side",
		C8UI_TEXT_SUBHEADER);
	c8ui_widget_add(page, title);
	struct c8ui_widget *grid = c8ui_box_new(C8UI_HORIZONTAL, PICK_GAP);
	c8ui_box_set_wrap(grid, true);
	/* The outline is drawn round a picture: room for it, or the
	 * scroll's clip cuts it off the first row and column */
	c8ui_box_set_padding(grid, PICK_RIM, PICK_RIM, PICK_RIM, PICK_RIM);
	for (int i = 0; i < p.count; i++) {
		struct c8ui_widget *item = c8ui_canvas_new(PICK_ITEM_W, PICK_ITEM_H,
			draw_item, item_event, (void *)(intptr_t)i);
		c8ui_widget_add(grid, item);
	}
	struct c8ui_widget *scroll = c8ui_scroll_new(grid);
	scroll->expand = true;
	c8ui_widget_add(page, scroll);
	c8ui_widget_track(page, &p.list);
	c8ui_widget_track(grid, &p.grid);
	return page;
}

/* The pictures for a pick width wide: as many to a row as fit at
 * their smallest, the rows evened out (five are three and two, not
 * four and one), then widened to fill the row, so no column of dead
 * space is left at the right */
static void pick_fit(int width) {
	if (p.grid == NULL || p.grid->child_count == 0) {
		return;
	}
	int n = p.grid->child_count;
	int avail = width - 2 * PICK_MARGIN;
	int cols = (avail + PICK_GAP) / (PICK_ITEM_W + PICK_GAP);
	cols = cols < 1 ? 1 : cols > n ? n : cols;
	int rows = (n + cols - 1) / cols;
	cols = (n + rows - 1) / rows;
	double w = (double)(avail - (cols - 1) * PICK_GAP) / cols;
	w = floor(fmax(fmin(w, PICK_ITEM_MAX), fmin(PICK_ITEM_W, avail)));
	double h = round(w * PICK_PREVIEW_H / PICK_ITEM_W) + SWITCH_ROW_GAP +
		SWITCH_ROW_H;
	for (int i = 0; i < n; i++) {
		p.grid->children[i]->fixed_width = w;
		p.grid->children[i]->fixed_height = h;
	}
	c8ui_widget_queue_layout(p.grid);
}

/* An arrow in the pick: Up and Down go to the nearest picture in the
 * row above or below, as the grid wrapped them for its width (one
 * column when snapped narrow); Left and Right along the order */
static void pick_arrow(int dx, int dy) {
	if (p.grid == NULL || p.index < 0 || p.index >= p.grid->child_count) {
		return;
	}
	if (dy == 0) {
		switcher_step(dx);
	} else {
		struct c8ui_rect *r = &p.grid->children[p.index]->rect;
		struct rect from = { r->x, r->y, r->width, r->height };
		double best = INFINITY;
		for (int i = 0; i < p.grid->child_count; i++) {
			r = &p.grid->children[i]->rect;
			struct rect to = { r->x, r->y, r->width, r->height };
			double d = focus_distance(&from, &to, 0, dy);
			if (d < best) {
				best = d;
				p.index = i;
			}
		}
		c8ui_widget_queue_draw(p.list);
	}
	struct c8ui_widget *item = p.grid->children[p.index];
	c8ui_widget_reveal(item, &item->rect);
}

void panels_snap(struct window *snapped, int side, int x, int y, int width,
		int height) {
	if (side == 0 || width <= 0 || height <= 0) {
		if (p.open == PANEL_PICK) {
			panels_close();
		}
		return;
	}
	/* The app the pick is for moved side or split: the pick goes
	 * with it to the rest, still open until one is picked */
	if (p.open == PANEL_PICK && snapped == p.exclude) {
		g_clear_handle_id(&p.slide_timer, g_source_remove);
		g_clear_handle_id(&p.move_timer, g_source_remove);
		p.move_x = p.shown_x;
		p.move_y = p.shown_y;
		p.move_w = p.shown_w;
		p.move_h = p.shown_h;
		p.x = x;
		p.y = y;
		p.width = width;
		p.height = height;
		p.from = side < 0 ? 1 : -1;
		pick_fit(width);
		p.move_at = now_ms();
		move_tick(NULL);
		p.move_timer = g_timeout_add(16, move_tick, NULL);
		return;
	}
	/* A pick open for another app closes (its pick_done names that
	 * app, so the compositor keeps this one open) */
	panels_close();
	p.exclude = snapped;
	collect_windows();
	if (p.count == 0) {
		free(p.items);
		p.items = NULL;
		p.exclude = NULL;
		return;
	}
	p.index = 0;
	p.release = 0;
	p.from_corner = false;
	p.open = PANEL_PICK; // capture_windows sizes the pictures by it
	capture_windows();
	/* In from the edge the free side is on */
	show_at(PANEL_PICK, build_pick(), PANEL_GREY, 1, x, y, width, height,
		side < 0 ? 1 : -1);
	pick_fit(width);
}

/* The Start hint: pushing into the bottom-left corner shows a small
 * picture of where a click there goes, as on Windows 8: Start from an
 * app, the last app from Start */

static struct window *last_window(void) {
	if (wl_list_empty(&shell.windows)) {
		return NULL;
	}
	return wl_container_of(shell.windows.next, (struct window *)NULL, link);
}

static void draw_hint_start(struct c8ui_widget *w, cairo_t *cr) {
	struct c8ui_rect *r = &w->rect;
	double s = (double)r->width / shell.output_width;
	c8ui_set_source(cr, shell.appearance.background, 1);
	cairo_rectangle(cr, r->x, r->y, r->width, r->height);
	cairo_fill(cr);
	cairo_set_source_rgb(cr, 1, 1, 1);
	c8ui_text_draw(cr, c8ui_widget_font(w),
		(struct c8ui_font){ fmax(48 * s, 6), C8UI_WEIGHT_LIGHT }, "Start",
		r->x + START_MARGIN_X * s, r->y + 36 * s, 0, 0);
	/* The first screenful of tiles, as Start lays them out */
	struct group *g;
	struct tile *t;
	for_each_tile(g, t) {
		if (t->box.width <= 0 || t->box.x >= shell.output_width) {
			continue;
		}
		c8ui_set_source(cr, tile_color(t), 1);
		cairo_rectangle(cr, r->x + t->box.x * s, r->y + t->box.y * s,
			fmax(t->box.width * s, 1), fmax(t->box.height * s, 1));
		cairo_fill(cr);
	}
}

static void draw_hint_app(struct c8ui_widget *w, cairo_t *cr,
		struct window *win) {
	struct c8ui_rect *r = &w->rect;
	/* No picture of the window: its tile colour and icon, as the
	 * switcher shows it till its picture comes */
	c8ui_set_source(cr, win->styled ? win->style_rgb : 0x404040, 1);
	cairo_rectangle(cr, r->x, r->y, r->width, r->height);
	cairo_fill(cr);
	load_icon(win);
	if (win->icon) {
		c8ui_icon_draw_fit(cr, win->icon, r->x + r->width / 2,
			r->y + r->height / 2, fmin(40, r->height * 0.6));
	}
}

static void draw_hint(struct c8ui_widget *w, cairo_t *cr, void *data) {
	struct window *win = last_window();
	if (shell.start_visible && win) {
		draw_hint_app(w, cr, win);
	} else {
		draw_hint_start(w, cr);
	}
	/* A rim, so it shows against a Start of the same colour */
	struct c8ui_rect *r = &w->rect;
	cairo_set_source_rgba(cr, 1, 1, 1, w->hovered ? 0.6 : 0.3);
	cairo_set_line_width(cr, 1);
	cairo_rectangle(cr, r->x + 0.5, r->y + 0.5, r->width - 1, r->height - 1);
	cairo_stroke(cr);
}

static bool hint_event(struct c8ui_widget *w, const struct c8ui_event *ev,
		void *data) {
	if (ev->type == C8UI_EVENT_PRESS) {
		return ev->button == C8UI_BUTTON_LEFT;
	}
	if (!left_click(w, ev)) {
		return false;
	}
	panels_close();
	c8_shell_v1_set_start_visible(shell.proto, !shell.start_visible);
	return true;
}

static void open_hint(void) {
	if (shell.start_visible && last_window() == NULL) {
		return; // nowhere to go
	}
	int w = HINT_W;
	int h = shell.output_width > 0 ?
		w * shell.output_height / shell.output_width : w;
	struct c8ui_widget *face = c8ui_canvas_new(w, h, draw_hint, hint_event,
		NULL);
	p.from_corner = true;
	show_at(PANEL_HINT, face, shell.appearance.background, 1, 0,
		shell.output_height - h, w, h, -1);
}

/* Input */

static bool panel_key(const struct c8ui_event *ev, void *data) {
	if (p.flyout_key && p.flyout_key(ev, p.flyout_key_data)) {
		return true;
	}
	switch (ev->sym) {
	case XKB_KEY_Escape:
		panels_close();
		return true;
	case XKB_KEY_Up:
	case XKB_KEY_Down:
		if (p.open == PANEL_SWITCHER) {
			switcher_step(ev->sym == XKB_KEY_Up ? -1 : 1);
			return true;
		}
		if (p.open == PANEL_PICK) {
			pick_arrow(0, ev->sym == XKB_KEY_Up ? -1 : 1);
			return true;
		}
		return false;
	case XKB_KEY_Left:
	case XKB_KEY_Right:
	case XKB_KEY_Tab:
		if (p.open == PANEL_PICK || (p.open == PANEL_SWITCHER && p.on_bar)) {
			int step = ev->sym == XKB_KEY_Left ||
				(ev->sym == XKB_KEY_Tab && (ev->mods & C8UI_MOD_SHIFT)) ?
				-1 : 1;
			if (p.open == PANEL_PICK) {
				pick_arrow(step, 0);
			} else {
				switcher_step(step);
			}
			return true;
		}
		return false;
	case XKB_KEY_Return:
	case XKB_KEY_KP_Enter:
		if (p.open == PANEL_SWITCHER || p.open == PANEL_PICK) {
			switcher_commit();
			return true;
		}
		return false;
	}
	return false;
}

static void panel_modifiers(struct c8ui_window *win, uint32_t mods,
		void *data) {
	/* Alt+Tab: letting go of Alt switches */
	if (p.open == PANEL_SWITCHER && p.release && (mods & p.release) == 0) {
		switcher_commit();
	}
}

static void panel_left(struct c8ui_window *win, void *data) {
	/* Opened by pushing into a corner: moving away puts it back */
	if (p.from_corner && (p.open == PANEL_CHARMS ||
			p.open == PANEL_SWITCHER || p.open == PANEL_HINT)) {
		panels_close();
	}
}

static void dismissed(struct shell_surface *surface, void *data) {
	panels_close();
}

void panels_action(enum c8_shell_v1_action action) {
	switch (action) {
	case C8_SHELL_V1_ACTION_CHARMS:
	{
		bool was_open = p.open == PANEL_CHARMS;
		panels_close();
		if (!was_open) {
			open_charms(false);
		}
		break;
	}
	case C8_SHELL_V1_ACTION_CORNER_CHARMS:
		if (p.open == PANEL_NONE) {
			open_charms(true);
		}
		break;
	case C8_SHELL_V1_ACTION_SETTINGS:
	{
		if (panels_settings_card()) {
			break; // as the bar's Settings charm
		}
		bool was_open = p.open == PANEL_SETTINGS;
		panels_close();
		if (!was_open) {
			context_settings();
		}
		break;
	}
	case C8_SHELL_V1_ACTION_CORNER_SWITCHER:
		if (p.open == PANEL_NONE) {
			switcher_open(0, 0, true);
		}
		break;
	case C8_SHELL_V1_ACTION_CORNER_START:
		if (p.open == PANEL_NONE) {
			open_hint();
		}
		break;
	case C8_SHELL_V1_ACTION_PROJECT:
		panels_close();
		project_open();
		break;
	default:
		break;
	}
}

void panels_init(void) {
	p.panel = shell_surface_new(C8_SHELL_V1_ROLE_PANEL);
	p.clock = shell_surface_new(C8_SHELL_V1_ROLE_PANEL);
	shell_surface_hide(p.panel);
	shell_surface_hide(p.clock);
	shell_surface_on_dismiss(p.panel, dismissed, NULL);
	shell_surface_on_dismiss(p.clock, dismissed, NULL);
	c8ui_window_set_background(shell_surface_window(p.clock), PANEL_GREY,
		0.94);
	struct c8ui_window *win = shell_surface_window(p.panel);
	c8ui_root_set_key_handler(shell_surface_root(p.panel), panel_key, NULL);
	c8ui_window_on_modifiers(win, panel_modifiers, NULL);
	c8ui_window_on_pointer_leave(win, panel_left, NULL);
	status_listen(status_changed, NULL);
	tray_listen(tray_changed, NULL);
}
