/*
 * The bottom of the Settings flyout, as on Windows 8, with a third row
 * of our own: nine tiles for Network, Volume, Brightness, Notifications,
 * Power, Keyboard, Night light, Second screen and Airplane mode. Volume
 * and brightness open a level above the tile; Network swaps the flyout
 * for the Networks one; Night light and Airplane mode are switches, lit
 * while on.
 *
 * In XR Volume and Brightness are on the charms bar instead, Network is
 * the Settings card's Networks page (quick_networks_new) and the other
 * six stay in Settings (the flyout from the screen's right edge is no
 * use in the glasses, and nine made the bar too wide): the level is a
 * card above the bar, and what would be a menu or a flyout is a card
 * too (panels_show_card), wide and low. The bar's tiles put away what
 * they opened when pressed again.
 */
#define _GNU_SOURCE
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include "shell.h"
#include "status.h"
#include "rfkill.h"

#define TILE_W 95
#define TILE_H 80
#define LEVEL_W 72
#define LEVEL_H 250
#define LEVEL_STEP 2
#define LEVEL_ROW_H 64 // a row of the mixer, and of the bar's level
#define LEVEL_CARD_W 420 // the bar's level
#define LEVEL_ROWS_MAX 6 // apps over the bar's level before they scroll
#define LEVEL_POLL_MS 2000 // apps and levels read again while it's open
#define LEVEL_HOLD_MS 1500

enum quick {
	Q_NETWORK,
	Q_VOLUME,
	Q_BRIGHTNESS,
	Q_NOTIFY,
	Q_POWER,
	Q_KEYBOARD,
	Q_NIGHT,
	Q_SCREEN,
	Q_AIRPLANE,
	Q_COUNT,
};

static struct {
	struct c8ui_widget *tiles[Q_COUNT];
	struct c8ui_widget *level; // the open level popup
	int volume; // -1 until known
	bool muted;
	char keyboard[16];

	/* Networks flyout */
	struct c8ui_widget *net_page, *net_list, *airplane;
	char *selected; // the network opened up, by name
	enum { NET_IDLE, NET_KEY, NET_CONNECTING, NET_FAILED } stage;
	char *error;
	bool autoconnect;
	struct c8ui_widget *key_entry;
} q = { .volume = -1 };

/* bg, alpha of the way to white: hover and pressed shades */
static uint32_t mix(uint32_t bg, double alpha) {
	uint32_t out = 0;
	for (int shift = 0; shift <= 16; shift += 8) {
		double c = (bg >> shift) & 0xff;
		out |= (uint32_t)lround(c + (255 - c) * alpha * 0.4) << shift;
	}
	return out;
}

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

/* The keyboard tile: the first layout in config.ini, as "US" */
static void read_keyboard(void) {
	snprintf(q.keyboard, sizeof(q.keyboard), "US");
	char *path = g_build_filename(shell.config_dir, "config.ini", NULL);
	GKeyFile *kf = g_key_file_new();
	if (g_key_file_load_from_file(kf, path, G_KEY_FILE_NONE, NULL)) {
		char *layout = g_key_file_get_string(kf, "keyboard", "layout", NULL);
		if (layout && layout[0]) {
			layout[strcspn(layout, ", ")] = '\0';
			char *up = g_ascii_strup(layout, -1);
			snprintf(q.keyboard, sizeof(q.keyboard), "%s", up);
			g_free(up);
		}
		g_free(layout);
	}
	g_key_file_free(kf);
	g_free(path);
}

/* Icons, about 28 px, around cx, cy */

static void draw_bell(cairo_t *cr, double cx, double cy, bool off) {
	cairo_set_line_width(cr, 1.5);
	cairo_move_to(cr, cx - 9, cy + 6);
	cairo_curve_to(cr, cx - 6, cy + 2, cx - 7, cy - 10, cx, cy - 10);
	cairo_curve_to(cr, cx + 7, cy - 10, cx + 6, cy + 2, cx + 9, cy + 6);
	cairo_close_path(cr);
	cairo_stroke(cr);
	cairo_arc(cr, cx, cy + 8, 2.5, 0, M_PI);
	cairo_fill(cr);
	if (off) {
		cairo_move_to(cr, cx - 11, cy - 11);
		cairo_line_to(cr, cx + 11, cy + 11);
		cairo_stroke(cr);
	}
}

static void draw_power(cairo_t *cr, double cx, double cy) {
	cairo_set_line_width(cr, 2);
	cairo_arc(cr, cx, cy + 1, 10, -M_PI / 2 + 0.7, 3 * M_PI / 2 - 0.7);
	cairo_stroke(cr);
	cairo_move_to(cr, cx, cy - 12);
	cairo_line_to(cr, cx, cy);
	cairo_stroke(cr);
}

static void draw_keyboard(cairo_t *cr, double cx, double cy) {
	cairo_set_line_width(cr, 1.5);
	cairo_rectangle(cr, cx - 13.25, cy - 8.25, 26.5, 16.5);
	cairo_stroke(cr);
	for (int row = 0; row < 2; row++) {
		for (int col = 0; col < 6; col++) {
			cairo_rectangle(cr, cx - 10.5 + col * 3.75, cy - 5 + row * 3.75,
				2, 2);
		}
	}
	cairo_rectangle(cr, cx - 6, cy + 3.5, 12, 2);
	cairo_fill(cr);
}

/* A crescent: a disc with a bite out of its upper right */
static void draw_moon(cairo_t *cr, double cx, double cy, double alpha) {
	cairo_push_group(cr);
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_arc(cr, cx - 1, cy + 1, 10.5, 0, 2 * M_PI);
	cairo_fill(cr);
	cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
	cairo_arc(cr, cx + 4.5, cy - 3.5, 9, 0, 2 * M_PI);
	cairo_fill(cr);
	cairo_pop_group_to_source(cr);
	cairo_paint_with_alpha(cr, alpha);
}

/* Two screens, one behind the other */
static void draw_screens(cairo_t *cr, double cx, double cy) {
	cairo_set_line_width(cr, 1.5);
	cairo_move_to(cr, cx - 6.25, cy - 4);
	cairo_line_to(cr, cx - 6.25, cy - 9.25);
	cairo_line_to(cr, cx + 13.25, cy - 9.25);
	cairo_line_to(cr, cx + 13.25, cy + 3.25);
	cairo_line_to(cr, cx + 9, cy + 3.25);
	cairo_stroke(cr);
	cairo_rectangle(cr, cx - 13.25, cy - 3.25, 19.5, 12.5);
	cairo_stroke(cr);
}

/* The switches among the tiles: lit while on */
static bool quick_lit(enum quick which) {
	return (which == Q_NIGHT && shell.appearance.night_light) ||
		(which == Q_AIRPLANE && status.airplane);
}

static const char *quick_label(enum quick which, char *buf, size_t len) {
	switch (which) {
	case Q_NETWORK:
		return status_net_label();
	case Q_VOLUME:
		if (q.volume < 0) {
			return "Volume";
		}
		if (q.muted) {
			return "Muted";
		}
		snprintf(buf, len, "%d", q.volume);
		return buf;
	case Q_BRIGHTNESS:
		return "Brightness";
	case Q_NOTIFY:
		return notify_hidden() ? "Hidden" : "Notifications";
	case Q_POWER:
		return "Power";
	case Q_KEYBOARD:
		return q.keyboard;
	case Q_NIGHT:
		return "Night light";
	case Q_SCREEN:
		return "Second screen";
	case Q_AIRPLANE:
		return "Airplane mode";
	default:
		return "";
	}
}

static void draw_tile(struct c8ui_widget *w, cairo_t *cr, void *data) {
	enum quick which = (intptr_t)data;
	struct c8ui_rect r = w->rect;
	uint32_t bg = c8ui_shade(shell.appearance.background, 0.75);
	bool lit = quick_lit(which);
	if (lit) {
		bg = shell.appearance.accent;
	}
	if (lit || w->pressed || w->hovered) {
		double by = w->pressed ? 0.6 : w->hovered ? 0.3 : 0;
		c8ui_set_source(cr, mix(bg, by), 1);
		cairo_rectangle(cr, r.x, r.y, r.width, r.height);
		cairo_fill(cr);
	}
	double alpha = w->disabled ? 0.4 : 1;
	cairo_set_source_rgba(cr, 1, 1, 1, alpha);
	/* Glyph over label, the pair in the middle (80 high: as before) */
	double cx = r.x + r.width / 2, cy = r.y + r.height / 2 - 12;
	switch (which) {
	case Q_NETWORK:
		if (status.net == STATUS_NET_UNKNOWN) {
			status_draw_bars(cr, cx - 14, cy - 14, 28, 0, true);
		} else {
			status_draw_network(cr, cx - 14, cy - 14, 28);
		}
		break;
	case Q_VOLUME:
		media_draw_speaker(cr, cx, cy, q.muted);
		break;
	case Q_BRIGHTNESS:
		media_draw_sun(cr, cx, cy);
		break;
	case Q_NOTIFY:
		draw_bell(cr, cx, cy, notify_hidden());
		break;
	case Q_POWER:
		draw_power(cr, cx, cy);
		break;
	case Q_KEYBOARD:
		draw_keyboard(cr, cx, cy);
		break;
	case Q_NIGHT:
		draw_moon(cr, cx, cy, alpha);
		cairo_set_source_rgba(cr, 1, 1, 1, alpha);
		break;
	case Q_SCREEN:
		draw_screens(cr, cx, cy);
		break;
	case Q_AIRPLANE:
		status_draw_plane(cr, cx - 13, cy - 13, 26);
		break;
	default:
		break;
	}
	char buf[16];
	struct c8ui_font font = { 13, C8UI_WEIGHT_NORMAL };
	text_centered(w, cr, font, quick_label(which, buf, sizeof(buf)), cx,
		cy + 22, r.width - 8);
}

/* The level above Volume and Brightness. Volume's is a mixer once an
 * app plays sound: a row for each over the volume's own, its icon (a
 * click mutes, as the speaker does), its name over its slider, and the
 * number. More than fit scroll (the wheel off the sliders). */

/* An app in the mixer. Kept between openings, so the level opens at its
 * full size */
struct qapp {
	struct media_app app;
	struct c8ui_icon *icon;
	bool icon_tried;
	int64_t set_ms; // when we last changed it
};

static struct qapp apps[MEDIA_APPS_MAX];
static int napps;
static int64_t volume_set_ms;

struct slot {
	struct c8ui_rect box, track, icon;
};

struct level {
	enum quick which;
	bool row; // in a card above the charms bar
	guint poll; // the volume's: apps come and go
	int value; // -1 until known
	struct c8ui_rect box; // all of it
	struct slot main, apps[MEDIA_APPS_MAX];
	bool list; // rows, sliders lying down: the bar's, and the mixer
	int shown; // apps listed
	int first, vis; // the first in view, and how many are
	bool dragging;
	int grabbed; // the slider dragged: -1 the level's own, else an app's
};

/* A row: the glyph at the left, the slider, the number at the right;
 * an app's slider a little lower, under its name */
static void slot_row(struct slot *s, double x, double y, double width,
		bool app) {
	double h = LEVEL_ROW_H;
	s->box = (struct c8ui_rect){ x, y, width, h };
	s->icon = (struct c8ui_rect){ x, y, 64, h };
	s->track = (struct c8ui_rect){ x + 72, y + h / 2 - 12 + (app ? 9 : 0),
		width - 72 - 72, 24 };
}

/* Rows: in XR filling its card above the bar; else across the flyout,
 * ending over the tile unless they need the whole height. The apps, then
 * the level's own */
static void level_layout_list(struct c8ui_widget *w) {
	struct level *l = w->data;
	struct c8ui_widget *tile = q.tiles[l->which];
	double h = LEVEL_ROW_H, x, width, bottom;
	int most;
	if (l->row) {
		x = w->rect.x;
		width = w->rect.width;
		bottom = w->rect.y + w->rect.height;
		most = LEVEL_ROWS_MAX;
	} else {
		x = w->rect.x + 8;
		width = w->rect.width - 16;
		bottom = tile ? tile->rect.y - 8 : w->rect.y + w->rect.height - 8;
		most = (int)((w->rect.height - 16) / h) - 1;
	}
	most = most < 1 ? 1 : most;
	l->vis = l->shown < most ? l->shown : most;
	l->first = l->first > l->shown - l->vis ? l->shown - l->vis : l->first;
	l->first = l->first < 0 ? 0 : l->first;
	double height = (l->vis + 1) * h, y = bottom - height;
	if (!l->row && y < w->rect.y + 8) {
		y = w->rect.y + 8;
	}
	l->box = (struct c8ui_rect){ x, y, width, height };
	memset(l->apps, 0, sizeof(l->apps));
	for (int i = 0; i < l->vis; i++) {
		slot_row(&l->apps[l->first + i], x, y + i * h, width, true);
	}
	slot_row(&l->main, x, y + l->vis * h, width, false);
}

static void level_layout(struct c8ui_widget *w) {
	struct level *l = w->data;
	l->shown = l->which == Q_VOLUME ? napps : 0;
	l->list = l->row || l->shown > 0;
	if (l->list) {
		level_layout_list(w);
		return;
	}
	l->first = l->vis = 0;
	struct c8ui_widget *tile = q.tiles[l->which];
	double x = tile ? tile->rect.x + (tile->rect.width - LEVEL_W) / 2 : 0;
	double y = tile ? tile->rect.y - LEVEL_H - 8 : 0;
	x = x < w->rect.x + 8 ? w->rect.x + 8 : x;
	y = y < w->rect.y + 8 ? w->rect.y + 8 : y;
	l->box = (struct c8ui_rect){ x, y, LEVEL_W, LEVEL_H };
	l->main.box = l->box;
	l->main.track = (struct c8ui_rect){ x + LEVEL_W / 2.0 - 12, y + 48, 24,
		LEVEL_H - 48 - 56 };
	l->main.icon = (struct c8ui_rect){ x, y + LEVEL_H - 52, LEVEL_W, 48 };
}

/* An app's icon wherever its stream says it may be: the sandbox's app
 * id, the icon it names, its program */
static void app_load_icon(struct qapp *a) {
	const char *theme = shell.appearance.icon_theme;
	const char *tries[] = { a->app.app_id, a->app.icon, a->app.binary };
	a->icon_tried = true;
	for (int i = 0; i < 3 && a->icon == NULL; i++) {
		if (tries[i][0]) {
			a->icon = c8ui_icon_load(theme, app_icon_name(tries[i]));
		}
		if (a->icon == NULL && tries[i][0]) {
			a->icon = c8ui_icon_load(theme, tries[i]);
		}
	}
}

/* Its icon, or with none its first letter in a square; fainter and
 * struck through while muted */
static void draw_app(struct c8ui_widget *w, cairo_t *cr, struct qapp *a,
		double cx, double cy) {
	if (!a->icon_tried) {
		app_load_icon(a);
	}
	cairo_push_group(cr);
	if (a->icon) {
		c8ui_icon_draw_fit(cr, a->icon, cx, cy, 28);
	} else {
		char letter[8] = "";
		g_unichar_to_utf8(g_unichar_toupper(g_utf8_get_char_validated(
			a->app.name, -1) < 0x110000 ? g_utf8_get_char(a->app.name) : '?'),
			letter);
		cairo_set_source_rgb(cr, 1, 1, 1);
		cairo_set_line_width(cr, 1.5);
		cairo_rectangle(cr, cx - 13.25, cy - 13.25, 26.5, 26.5);
		cairo_stroke(cr);
		text_centered(w, cr, (struct c8ui_font){ 15, C8UI_WEIGHT_NORMAL },
			letter, cx, cy - 11, 0);
	}
	cairo_pop_group_to_source(cr);
	cairo_paint_with_alpha(cr, a->app.muted ? 0.4 : 1);
	if (a->app.muted) {
		cairo_set_source_rgb(cr, 1, 1, 1);
		cairo_set_line_width(cr, 1.5);
		cairo_move_to(cr, cx - 13, cy - 13);
		cairo_line_to(cr, cx + 13, cy + 13);
		cairo_stroke(cr);
	}
}

/* One slider: the level's own (a NULL app) or an app's */
static void draw_slot(struct c8ui_widget *w, cairo_t *cr,
		const struct slot *s, int value, bool muted, struct qapp *a) {
	struct level *l = w->data;
	struct c8ui_rect t = s->track;
	double v = value < 0 ? 0 : value / 100.0, bar = 8;
	struct c8ui_font font = { 22, C8UI_WEIGHT_LIGHT };
	char num[16];
	snprintf(num, sizeof(num), "%d", value < 0 ? 0 : value);
	if (value < 0) {
		num[0] = '\0';
	}
	if (l->list) {
		double cy = t.y + t.height / 2;
		if (a) {
			cairo_set_source_rgba(cr, 1, 1, 1, a->app.muted ? 0.5 : 1);
			c8ui_text_draw(cr, c8ui_widget_font(w),
				(struct c8ui_font){ 13, C8UI_WEIGHT_NORMAL }, a->app.name,
				t.x, s->box.y + 7, t.width, 1);
		}
		cairo_set_source_rgba(cr, 1, 1, 1, 0.25);
		cairo_rectangle(cr, t.x, cy - bar / 2, t.width, bar);
		cairo_fill(cr);
		c8ui_set_source(cr, shell.appearance.accent, muted ? 0.5 : 1);
		cairo_rectangle(cr, t.x, cy - bar / 2, t.width * v, bar);
		cairo_fill(cr);
		cairo_set_source_rgb(cr, 1, 1, 1);
		cairo_rectangle(cr, t.x + t.width * v - 4, t.y, 8, t.height);
		cairo_fill(cr);
		text_centered(w, cr, font, num, s->box.x + s->box.width - 36,
			s->box.y + s->box.height / 2 - 15, 0);
	} else {
		double cx = t.x + t.width / 2;
		cairo_set_source_rgb(cr, 1, 1, 1);
		text_centered(w, cr, font, num, cx, s->box.y + 10, 0);
		cairo_set_source_rgba(cr, 1, 1, 1, 0.25);
		cairo_rectangle(cr, cx - bar / 2, t.y, bar, t.height);
		cairo_fill(cr);
		c8ui_set_source(cr, shell.appearance.accent, muted ? 0.5 : 1);
		cairo_rectangle(cr, cx - bar / 2, t.y + t.height * (1 - v), bar,
			t.height * v);
		cairo_fill(cr);
		/* The thumb */
		cairo_set_source_rgb(cr, 1, 1, 1);
		cairo_rectangle(cr, t.x, t.y + t.height * (1 - v) - 4, t.width, 8);
		cairo_fill(cr);
	}

	double cx = s->icon.x + s->icon.width / 2;
	double cy = s->icon.y + s->icon.height / 2;
	cairo_set_source_rgb(cr, 1, 1, 1);
	if (a) {
		draw_app(w, cr, a, cx, cy);
	} else if (l->which == Q_VOLUME) {
		media_draw_speaker(cr, cx, cy, muted);
	} else {
		media_draw_sun(cr, cx, cy);
	}
}

static void level_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct level *l = w->data;
	struct c8ui_rect b = l->box;
	uint32_t bg = c8ui_shade(shell.appearance.background, 0.75);
	c8ui_set_source(cr, mix(bg, 0.35), 1);
	cairo_rectangle(cr, b.x, b.y, b.width, b.height);
	cairo_fill(cr);
	draw_slot(w, cr, &l->main, l->value, l->which == Q_VOLUME && q.muted,
		NULL);
	for (int i = l->first; i < l->first + l->vis && i < napps; i++) {
		draw_slot(w, cr, &l->apps[i], apps[i].app.level, apps[i].app.muted,
			&apps[i]);
	}
	if (l->vis > 0) {
		/* A line between the apps and the volume */
		struct c8ui_rect m = l->main.box;
		cairo_set_source_rgba(cr, 1, 1, 1, 0.2);
		cairo_rectangle(cr, m.x + 12, m.y, m.width - 24, 1);
		cairo_fill(cr);
	}
	if (l->shown > l->vis) {
		/* More than fit: where among them we are */
		double high = b.height - LEVEL_ROW_H;
		cairo_set_source_rgba(cr, 1, 1, 1, 0.5);
		cairo_rectangle(cr, b.x + b.width - 5,
			b.y + high * l->first / l->shown, 3, high * l->vis / l->shown);
		cairo_fill(cr);
	}
}

static void level_set(struct c8ui_widget *w, int value) {
	struct level *l = w->data;
	value = value < 0 ? 0 : value > 100 ? 100 : value;
	if (value == l->value) {
		return;
	}
	l->value = value;
	if (l->which == Q_VOLUME) {
		q.volume = value;
		q.muted = false;
		volume_set_ms = now_ms();
		media_volume_set(value);
		c8ui_widget_queue_draw(q.tiles[Q_VOLUME]);
	} else {
		media_brightness_set(value);
	}
	c8ui_widget_queue_draw(w);
}

static void app_set(struct c8ui_widget *w, int i, int value) {
	struct qapp *a = &apps[i];
	value = value < 0 ? 0 : value > 100 ? 100 : value;
	if (value == a->app.level && !a->app.muted) {
		return;
	}
	media_app_set(&a->app, value);
	a->app.level = value;
	a->app.muted = false;
	a->set_ms = now_ms();
	c8ui_widget_queue_draw(w);
}

/* The slider at a point: -1 the level's own, an app's, or -2 for none */
static int slot_at(struct level *l, double x, double y) {
	for (int i = l->first; i < l->first + l->vis && i < napps; i++) {
		if (c8ui_rect_contains(&l->apps[i].box, x, y)) {
			return i;
		}
	}
	return c8ui_rect_contains(&l->main.box, x, y) ? -1 : -2;
}

/* -1 while it isn't known yet */
static int slot_value(struct level *l, int i) {
	return i < 0 ? l->value : i < napps ? apps[i].app.level : -1;
}

static void slot_set(struct c8ui_widget *w, int i, int value) {
	if (slot_value(w->data, i) < 0) {
		return;
	}
	if (i < 0) {
		level_set(w, value);
	} else {
		app_set(w, i, value);
	}
}

static void slot_drag(struct c8ui_widget *w, int i, double x, double y) {
	struct level *l = w->data;
	const struct c8ui_rect *t = i < 0 ? &l->main.track : &l->apps[i].track;
	double v = l->list ? (x - t->x) / t->width :
		(t->y + t->height - y) / t->height;
	slot_set(w, i, (int)lround(v * 100));
}

static void slot_mute(struct c8ui_widget *w, int i) {
	struct level *l = w->data;
	if (i >= 0 && i < napps) {
		struct qapp *a = &apps[i];
		a->app.muted = !a->app.muted;
		a->set_ms = now_ms();
		media_app_mute(&a->app, a->app.muted);
	} else if (i < 0 && l->which == Q_VOLUME && l->value >= 0) {
		q.muted = !q.muted;
		volume_set_ms = now_ms();
		media_volume_mute(q.muted);
		c8ui_widget_queue_draw(q.tiles[Q_VOLUME]);
	}
	c8ui_widget_queue_draw(w);
}

static void level_close(struct c8ui_widget *w) {
	if (((struct level *)w->data)->row) {
		panels_close(); // its card
	} else {
		c8ui_root_remove_overlay(w->root, w);
	}
}

/* The flyout's level; the bar's goes with its card */
void quick_level_close(void) {
	if (q.level && !((struct level *)q.level->data)->row) {
		struct c8ui_widget *w = q.level;
		q.level = NULL;
		level_close(w);
	}
}

static bool level_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct level *l = w->data;
	switch (ev->type) {
	case C8UI_EVENT_PRESS: {
		int i = slot_at(l, ev->x, ev->y);
		if (!c8ui_rect_contains(&l->box, ev->x, ev->y) || i == -2) {
			level_close(w);
			return true;
		}
		const struct slot *s = i < 0 ? &l->main : &l->apps[i];
		if (c8ui_rect_contains(&s->icon, ev->x, ev->y)) {
			slot_mute(w, i);
			return true;
		}
		/* Anywhere up the box, not just on the thin track */
		if (slot_value(l, i) >= 0) {
			l->dragging = true;
			l->grabbed = i;
			slot_drag(w, i, ev->x, ev->y);
		}
		return true;
	}
	case C8UI_EVENT_MOTION:
		if (l->dragging) {
			slot_drag(w, l->grabbed, ev->x, ev->y);
		}
		return true;
	case C8UI_EVENT_RELEASE:
		l->dragging = false;
		return true;
	case C8UI_EVENT_SCROLL:
		if (ev->dy != 0) {
			/* The slider under the pointer; off them all, the level's */
			int i = slot_at(l, ev->x, ev->y);
			i = i == -2 ? -1 : i;
			const struct c8ui_rect *t = i < 0 ? &l->main.track :
				&l->apps[i].track;
			if (l->shown > l->vis && (ev->x < t->x - 8 ||
					ev->x > t->x + t->width + 8)) {
				/* Off the sliders the wheel moves the list */
				l->first += ev->dy > 0 ? 1 : -1;
				c8ui_widget_queue_layout(w);
				return true;
			}
			slot_set(w, i, slot_value(l, i) +
				(ev->dy < 0 ? LEVEL_STEP : -LEVEL_STEP));
		}
		return true;
	case C8UI_EVENT_KEY:
		switch (ev->sym) {
		case XKB_KEY_Escape:
		case XKB_KEY_Return:
			level_close(w);
			break;
		case XKB_KEY_Up:
		case XKB_KEY_Right:
			slot_set(w, -1, l->value + LEVEL_STEP);
			break;
		case XKB_KEY_Down:
		case XKB_KEY_Left:
			slot_set(w, -1, l->value - LEVEL_STEP);
			break;
		}
		return true;
	default:
		return false;
	}
}

static void level_destroy(struct c8ui_widget *w) {
	struct level *l = w->data;
	if (l->poll) {
		g_source_remove(l->poll);
	}
	if (q.level == w) {
		q.level = NULL;
	}
	free(w->data);
}

static const struct c8ui_widget_impl level_impl = {
	.name = "level",
	.layout = level_layout,
	.draw = level_draw,
	.event = level_event,
	.destroy = level_destroy,
};

/* What we set a moment ago stands: the answer may be from before it */
static bool just_set(int64_t set_ms) {
	return now_ms() - set_ms < LEVEL_HOLD_MS;
}

static void got_volume(int level, bool muted, void *data) {
	struct level *l = q.level ? q.level->data : NULL;
	bool ours = l && l->which == Q_VOLUME;
	if (just_set(volume_set_ms) || (ours && l->dragging && l->grabbed < 0)) {
		return;
	}
	q.volume = level;
	q.muted = muted;
	c8ui_widget_queue_draw(q.tiles[Q_VOLUME]);
	if (ours) {
		l->value = level;
		c8ui_widget_queue_draw(q.level);
	}
}

/* The bar's level's height: a row, and one for each app */
static int level_room(struct level *l) {
	int rows = l->which == Q_VOLUME ? napps : 0;
	return LEVEL_ROW_H * (1 + (rows < LEVEL_ROWS_MAX ? rows : LEVEL_ROWS_MAX));
}

static void got_apps(const struct media_app *list, int count, void *data) {
	struct level *l = q.level ? q.level->data : NULL;
	if (l && l->dragging && l->grabbed >= 0) {
		return; // not from under the finger
	}
	struct qapp old[MEDIA_APPS_MAX];
	int nold = napps;
	memcpy(old, apps, sizeof(old));
	for (int i = 0; i < count; i++) {
		struct qapp *a = &apps[i];
		*a = (struct qapp){ .app = list[i] };
		a->app.level = a->app.level > 100 ? 100 : a->app.level;
		for (int j = 0; j < nold; j++) {
			if (old[j].app.name[0] == '\0' ||
					strcmp(old[j].app.name, a->app.name) != 0) {
				continue;
			}
			a->icon = old[j].icon;
			a->icon_tried = old[j].icon_tried;
			a->set_ms = old[j].set_ms;
			if (just_set(a->set_ms)) {
				a->app.level = old[j].app.level;
				a->app.muted = old[j].app.muted;
			}
			old[j].icon = NULL;
			old[j].app.name[0] = '\0';
			break;
		}
	}
	for (int j = 0; j < nold; j++) {
		c8ui_icon_destroy(old[j].icon);
	}
	bool resized = napps != count;
	napps = count;
	if (l && l->which == Q_VOLUME) {
		if (resized) {
			c8ui_widget_queue_layout(q.level);
			if (l->row) {
				panels_card_height(level_room(l));
			}
		}
		c8ui_widget_queue_draw(q.level);
	}
}

static gboolean level_poll(gpointer data) {
	media_volume_get(got_volume, NULL);
	media_apps_get(got_apps, NULL);
	return G_SOURCE_CONTINUE;
}

static void open_level(struct c8ui_widget *tile, enum quick which) {
	struct level *l = calloc(1, sizeof(*l));
	l->which = which;
	l->row = shell.appearance.xr;
	l->value = which == Q_VOLUME ? q.volume : media_brightness_get();
	struct c8ui_widget *w = c8ui_widget_new(&level_impl, l);
	w->scheme = C8UI_SCHEME_DARK;
	q.level = w;
	if (l->row) {
		/* A card above the bar, with the keyboard: arrows set it,
		 * Escape, a press off the bar or looking up put it away */
		w->focusable = true;
		w->fixed_width = LEVEL_CARD_W;
		w->fixed_height = level_room(l);
		panels_show_bar_card(w, LEVEL_CARD_W, level_room(l));
		panels_mark(which == Q_VOLUME ? OPENER_VOLUME : OPENER_BRIGHTNESS);
		c8ui_widget_grab_focus(w);
	} else {
		c8ui_root_push_overlay(tile->root, w);
	}
	if (which == Q_VOLUME) {
		level_poll(NULL);
		l->poll = g_timeout_add(LEVEL_POLL_MS, level_poll, NULL);
	}
}

/* Menus */

static void notify_chosen(int choice, void *data) {
	static const int hours[] = { 1, 3, 8 };
	if (choice < 0) {
		return;
	}
	notify_hide_for(notify_hidden() ? 0 : hours[choice]);
	c8ui_widget_queue_draw(q.tiles[Q_NOTIFY]);
}

static const struct {
	uint32_t bit;
	const char *label;
	enum c8_shell_v1_command command;
} power_items[] = {
	{ C8_SHELL_V1_POWER_SIGN_OUT, "Sign out", C8_SHELL_V1_COMMAND_SIGN_OUT },
	{ C8_SHELL_V1_POWER_EXIT, "Exit", C8_SHELL_V1_COMMAND_SIGN_OUT },
	{ C8_SHELL_V1_POWER_SLEEP, "Sleep", C8_SHELL_V1_COMMAND_SLEEP },
	{ C8_SHELL_V1_POWER_SHUT_DOWN, "Shut down", C8_SHELL_V1_COMMAND_SHUT_DOWN },
	{ C8_SHELL_V1_POWER_RESTART, "Restart", C8_SHELL_V1_COMMAND_RESTART },
};
#define POWER_ITEMS (int)(sizeof(power_items) / sizeof(power_items[0]))

#define PROFILE_ID 100 // menu ids from here on are power modes
#define PROFILES_MAX 4

static const char *profile_names[PROFILES_MAX];

static void power_chosen(int choice, void *data) {
	if (choice >= PROFILE_ID && choice < PROFILE_ID + PROFILES_MAX) {
		profiles_set(profile_names[choice - PROFILE_ID]);
		return;
	}
	if (choice >= 0 && choice < POWER_ITEMS) {
		panels_close();
		c8_shell_v1_run(shell.proto, power_items[choice].command);
	}
}

/* The power modes, then the power commands */
static void open_power(struct c8ui_widget *w) {
	struct c8ui_menu_item items[PROFILES_MAX + 1 + POWER_ITEMS];
	memset(items, 0, sizeof(items));
	const char *labels[PROFILES_MAX];
	int profiles = profiles_list(profile_names, labels, PROFILES_MAX), n = 0;
	for (int i = 0; i < profiles; i++) {
		items[n++] = (struct c8ui_menu_item){ .label = labels[i],
			.id = PROFILE_ID + i, .kind = C8UI_MENU_RADIO,
			.checked = profiles_active(profile_names[i]) };
	}
	if (profiles > 0) {
		items[n++].kind = C8UI_MENU_SEPARATOR;
	}
	for (int i = 0; i < POWER_ITEMS; i++) {
		if (shell.power & power_items[i].bit) {
			items[n++] = (struct c8ui_menu_item){ .label = power_items[i].label,
				.id = i };
		}
	}
	c8ui_menu_show_items(w->root, w->rect.x, w->rect.y, true, items, n,
		power_chosen, NULL);
}

/* XR: cards in front of you instead of menus off the bar */

static void card_notify_clicked(struct c8ui_widget *w, void *data) {
	panels_close();
	notify_chosen((int)(intptr_t)data, NULL);
}

/* Wide and low, as every card over the bar: the choices in a row */
static void notify_card(void) {
	struct c8ui_widget *page = c8ui_box_new(C8UI_VERTICAL, 20);
	c8ui_widget_add(page, c8ui_label_new("Notifications",
		C8UI_TEXT_SUBHEADER));
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 12);
	c8ui_widget_add(page, row);
	if (notify_hidden()) {
		c8ui_widget_add(row, c8ui_button_new("Show notifications",
			card_notify_clicked, (void *)0));
	} else {
		static const char *hide[] = { "Hide for 1 hour", "Hide for 3 hours",
			"Hide for 8 hours" };
		for (int i = 0; i < 3; i++) {
			c8ui_widget_add(row, c8ui_button_new(hide[i],
				card_notify_clicked, (void *)(intptr_t)i));
		}
	}
	panels_show_card(page);
}

static void card_profile_changed(struct c8ui_widget *w, void *data) {
	int i = c8ui_radio_get(w);
	if (i >= 0 && i < PROFILES_MAX && profile_names[i]) {
		profiles_set(profile_names[i]);
	}
}

static void card_power_clicked(struct c8ui_widget *w, void *data) {
	power_chosen((int)(intptr_t)data, NULL); // closes the card itself
}

/* The power modes beside a row of what to do */
static void power_card(void) {
	struct c8ui_widget *page = c8ui_box_new(C8UI_VERTICAL, 20);
	c8ui_widget_add(page, c8ui_label_new("Power", C8UI_TEXT_SUBHEADER));
	struct c8ui_widget *cols = c8ui_box_new(C8UI_HORIZONTAL, 40);
	c8ui_widget_add(page, cols);
	const char *labels[PROFILES_MAX];
	int profiles = profiles_list(profile_names, labels, PROFILES_MAX);
	if (profiles > 1) {
		int on = 0;
		for (int i = 0; i < profiles; i++) {
			if (profiles_active(profile_names[i])) {
				on = i;
			}
		}
		c8ui_widget_add(cols, c8ui_radio_new("Power mode", labels, profiles,
			on, card_profile_changed, NULL));
	}
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 12);
	c8ui_widget_add(cols, row);
	for (int i = 0; i < POWER_ITEMS; i++) {
		if (shell.power & power_items[i].bit) {
			c8ui_widget_add(row, c8ui_button_new(power_items[i].label,
				card_power_clicked, (void *)(intptr_t)i));
		}
	}
	panels_show_card(page);
}

static void quick_open_networks(void);

static void tile_clicked(struct c8ui_widget *w, enum quick which) {
	bool xr = shell.appearance.xr;
	switch (which) {
	case Q_NETWORK:
		if (panels_is(OPENER_NETWORK)) {
			panels_close(); // pressed again
			break;
		}
		quick_open_networks();
		panels_mark(OPENER_NETWORK);
		break;
	case Q_VOLUME:
	case Q_BRIGHTNESS:
		if (panels_is(which == Q_VOLUME ? OPENER_VOLUME :
				OPENER_BRIGHTNESS)) {
			panels_close();
			break;
		}
		open_level(w, which);
		break;
	case Q_NOTIFY:
		if (xr) {
			notify_card();
		} else if (notify_hidden()) {
			const char *items[] = { "Show notifications" };
			c8ui_menu_show(w->root, w->rect.x, w->rect.y, true, items, 1,
				notify_chosen, NULL);
		} else {
			const char *items[] = { "Hide for 1 hour", "Hide for 3 hours",
				"Hide for 8 hours" };
			c8ui_menu_show(w->root, w->rect.x, w->rect.y, true, items, 3,
				notify_chosen, NULL);
		}
		break;
	case Q_POWER:
		if (xr) {
			power_card();
		} else {
			open_power(w);
		}
		break;
	case Q_KEYBOARD:
		panels_close();
		c8_shell_v1_launch(shell.proto, "c8-settings --page keyboard");
		break;
	case Q_NIGHT:
		/* For now: c8 holds it until the schedule next turns */
		c8_shell_v1_set_appearance(shell.proto, "night_light",
			shell.appearance.night_light ? "off" : "on");
		break;
	case Q_SCREEN:
		project_open();
		break;
	case Q_AIRPLANE:
		/* Every radio, Bluetooth too; Wi-Fi alone without rfkill */
		if (rfkill_any()) {
			rfkill_set_airplane(!status.airplane);
		} else {
			network_set_wifi(status.airplane);
		}
		break;
	default:
		break;
	}
}

static bool tile_event(struct c8ui_widget *w, const struct c8ui_event *ev,
		void *data) {
	/* Hovering and pressing redraw it already (the toolkit does) */
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		return true;
	case C8UI_EVENT_RELEASE:
		if (left_click(w, ev)) {
			tile_clicked(w, (intptr_t)data);
		}
		return true;
	case C8UI_EVENT_KEY:
		if (ev->sym == XKB_KEY_Return || ev->sym == XKB_KEY_space) {
			tile_clicked(w, (intptr_t)data);
			return true;
		}
		return false;
	default:
		return false;
	}
}

/* One of the nine, for the grid or the row */
static struct c8ui_widget *new_tile(intptr_t which, int width, int height) {
	struct c8ui_widget *t = c8ui_canvas_new(width, height, draw_tile,
		tile_event, (void *)which);
	t->focusable = true;
	c8ui_widget_track(t, &q.tiles[which]);
	if (which == Q_BRIGHTNESS && media_brightness_get() < 0) {
		c8ui_widget_set_disabled(t, true);
	}
	return t;
}

/* On XR's charms bar; the rest stay in Settings. Not Network: there
 * it's the Settings card's Networks page. */
static const enum quick on_bar[] = { Q_VOLUME, Q_BRIGHTNESS };
#define ON_BAR (int)(sizeof(on_bar) / sizeof(on_bar[0]))

static bool is_on_bar(enum quick which) {
	for (int i = 0; i < ON_BAR; i++) {
		if (on_bar[i] == which) {
			return true;
		}
	}
	return false;
}

/* Rows of three: all nine, or in XR the six not on the bar or the
 * Settings card's pivot (a tile is made once, q.tiles keeps one of
 * each) */
struct c8ui_widget *quick_tiles_new(void) {
	read_keyboard();
	bool xr = shell.appearance.xr;
	struct c8ui_widget *grid = c8ui_box_new(C8UI_VERTICAL, 4);
	struct c8ui_widget *line = NULL;
	int n = 0;
	for (int which = 0; which < Q_COUNT; which++) {
		if (xr && is_on_bar(which)) {
			continue;
		}
		if (which == Q_NETWORK && !panels_headed()) {
			continue; // the card's Networks page
		}
		if (n++ % 3 == 0) {
			line = c8ui_box_new(C8UI_HORIZONTAL, 4);
			c8ui_widget_add(grid, line);
		}
		c8ui_widget_add(line, new_tile(which, TILE_W, TILE_H));
	}
	level_poll(NULL);
	return grid;
}

/* XR's charms bar: Volume and Brightness, as tall as the bar's
 * charms */
/* Each as wide as a charm and touching, so they go on from the charms
 * evenly: narrower tiles with a pad before them read as a stray gap */
struct c8ui_widget *quick_row_new(int each, int height, int *width) {
	read_keyboard();
	struct c8ui_widget *line = c8ui_box_new(C8UI_HORIZONTAL, 0);
	for (int i = 0; i < ON_BAR; i++) {
		c8ui_widget_add(line, new_tile(on_bar[i], each, height));
	}
	level_poll(NULL);
	*width = ON_BAR * each;
	return line;
}

void quick_status_changed(void) {
	c8ui_widget_queue_draw(q.tiles[Q_NETWORK]);
	c8ui_widget_queue_draw(q.tiles[Q_AIRPLANE]);
	c8ui_widget_queue_draw(q.tiles[Q_NIGHT]);
	if (q.airplane) {
		c8ui_toggle_set(q.airplane, status.airplane);
	}
}

/* The Networks flyout */

static void rebuild_networks(void);

static const struct wifi_net *find_net(const char *ssid) {
	int count;
	bool enabled, device;
	const struct wifi_net *nets = network_list(&count, &enabled, &device);
	for (int i = 0; ssid && i < count; i++) {
		if (strcmp(nets[i].ssid, ssid) == 0) {
			return &nets[i];
		}
	}
	return NULL;
}

static void set_stage(int stage, const char *error) {
	q.stage = stage;
	g_free(q.error);
	q.error = g_strdup(error);
	q.key_entry = NULL;
	rebuild_networks();
}

static void connected(bool ok, const char *error, void *data) {
	if (q.net_page == NULL) {
		return;
	}
	const struct wifi_net *net = find_net(q.selected);
	if (ok) {
		g_free(q.selected);
		q.selected = NULL;
		set_stage(NET_IDLE, NULL);
	} else if (net && net->secured && !net->enterprise) {
		set_stage(NET_KEY, error);
	} else {
		set_stage(NET_FAILED, error);
	}
}

static void connect_clicked(struct c8ui_widget *w, void *data) {
	const struct wifi_net *net = find_net(q.selected);
	if (net == NULL) {
		return;
	}
	if (net->secured && net->conn == NULL) {
		set_stage(NET_KEY, NULL);
		return;
	}
	set_stage(NET_CONNECTING, NULL);
	network_connect(net, NULL, q.autoconnect, connected, NULL);
}

static void key_next(struct c8ui_widget *w, void *data) {
	const struct wifi_net *net = find_net(q.selected);
	if (net == NULL || q.key_entry == NULL) {
		return;
	}
	const char *key = c8ui_entry_get(q.key_entry);
	if (key[0] == '\0') {
		return;
	}
	char *copy = g_strdup(key);
	set_stage(NET_CONNECTING, NULL);
	network_connect(net, copy, q.autoconnect, connected, NULL);
	explicit_bzero(copy, strlen(copy));
	g_free(copy);
}

static void key_cancel(struct c8ui_widget *w, void *data) {
	network_cancel();
	set_stage(NET_IDLE, NULL);
}

static void disconnect_clicked(struct c8ui_widget *w, void *data) {
	network_disconnect();
	g_free(q.selected);
	q.selected = NULL;
	set_stage(NET_IDLE, NULL);
}

static void auto_changed(struct c8ui_widget *w, void *data) {
	q.autoconnect = c8ui_toggle_get(w);
}

static void airplane_changed(struct c8ui_widget *w, void *data) {
	/* Every radio, Bluetooth too; Wi-Fi alone without rfkill */
	if (rfkill_any()) {
		rfkill_set_airplane(c8ui_toggle_get(w));
	} else {
		network_set_wifi(!c8ui_toggle_get(w));
	}
}

static void draw_net(struct c8ui_widget *w, cairo_t *cr, void *data) {
	const struct wifi_net *net = find_net(w->user_data);
	if (net == NULL) {
		return;
	}
	struct c8ui_rect r = w->rect;
	uint32_t bg = c8ui_shade(shell.appearance.background, 0.75);
	bool open = q.selected && strcmp(q.selected, net->ssid) == 0;
	if (open || w->hovered) {
		c8ui_set_source(cr, mix(bg, open ? 0.45 : 0.25), 1);
		cairo_rectangle(cr, r.x, r.y, r.width, r.height);
		cairo_fill(cr);
	}
	cairo_set_source_rgb(cr, 1, 1, 1);
	status_draw_bars(cr, r.x + 10, r.y + (r.height - 24) / 2, 24,
		net->strength, false);
	const char *family = c8ui_widget_font(w);
	double tx = r.x + 48, max = r.width - 56;
	c8ui_text_draw(cr, family, c8ui_text_font(C8UI_TEXT_BODY),
		c8_stealth_alias(C8_STEALTH_WIFI, net->ssid), tx,
		r.y + 8, max, 1);
	const char *what = net->active ? "Connected" :
		net->secured ? "Secured" : "Open";
	cairo_set_source_rgba(cr, 1, 1, 1, 0.6);
	c8ui_text_draw(cr, family, (struct c8ui_font){ 13, C8UI_WEIGHT_NORMAL },
		what, tx, r.y + 32, max, 1);
}

static bool net_event(struct c8ui_widget *w, const struct c8ui_event *ev,
		void *data) {
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		return true;
	case C8UI_EVENT_RELEASE:
		if (left_click(w, ev)) {
			bool same = q.selected && strcmp(q.selected, w->user_data) == 0;
			g_free(q.selected);
			q.selected = same ? NULL : g_strdup(w->user_data);
			q.autoconnect = true;
			network_cancel();
			set_stage(NET_IDLE, NULL);
		}
		return true;
	default:
		return false;
	}
}

static void net_destroyed(struct c8ui_widget *w, void *data) {
	g_free(data);
}

static void secondary(struct c8ui_widget *box, const char *text) {
	struct c8ui_widget *l = c8ui_label_new(text, C8UI_TEXT_BODY);
	c8ui_label_set_color(l, C8UI_COLOR_SECONDARY);
	c8ui_widget_add(box, l);
}

/* What opens up under the chosen network */
static struct c8ui_widget *net_details(const struct wifi_net *net) {
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 12);
	c8ui_box_set_padding(box, 48, 4, 8, 16);
	struct c8ui_widget *buttons = c8ui_box_new(C8UI_HORIZONTAL, 10);
	buttons->align = C8UI_ALIGN_END;

	if (net->enterprise && net->conn == NULL) {
		secondary(box, "This network needs a user name and password; "
			"that kind isn't supported here yet.");
		return box;
	}
	switch (q.stage) {
	case NET_CONNECTING:
		secondary(box, "Connecting…");
		return box;
	case NET_KEY: {
		if (q.error) {
			secondary(box, q.error);
		}
		struct c8ui_widget *e = c8ui_entry_new(
			"Enter the network security key", NULL, key_next, NULL);
		/* Enter connects; leaving the box isn't a reason to */
		c8ui_entry_set_enter_only(e, true);
		c8ui_entry_set_password(e, true);
		e->fill = true;
		q.key_entry = e;
		c8ui_widget_add(box, e);
		struct c8ui_widget *next = c8ui_button_new("Next", key_next, NULL);
		c8ui_button_set_primary(next, true);
		c8ui_widget_add(buttons, next);
		c8ui_widget_add(buttons, c8ui_button_new("Cancel", key_cancel, NULL));
		c8ui_widget_add(box, buttons);
		return box;
	}
	case NET_FAILED:
		secondary(box, q.error ? q.error : "Can't connect to this network.");
		break;
	default:
		break;
	}
	if (net->active) {
		c8ui_widget_add(buttons, c8ui_button_new("Disconnect",
			disconnect_clicked, NULL));
	} else {
		if (net->conn == NULL) {
			c8ui_widget_add(box, c8ui_toggle_new(NULL, "Connect automatically",
				q.autoconnect, auto_changed, NULL));
		}
		struct c8ui_widget *b = c8ui_button_new("Connect", connect_clicked,
			NULL);
		c8ui_button_set_primary(b, true);
		c8ui_widget_add(buttons, b);
	}
	c8ui_widget_add(box, buttons);
	return box;
}

static void rebuild_networks(void) {
	if (q.net_list == NULL) {
		return;
	}
	int count;
	bool enabled, device;
	const struct wifi_net *nets = network_list(&count, &enabled, &device);
c8ui_widget_clear(q.net_list);
	q.key_entry = NULL;
	if (!device) {
		secondary(q.net_list, "There's no Wi-Fi here.");
		return;
	}
	if (!enabled) {
		secondary(q.net_list, "Wi-Fi is off.");
		return;
	}
	if (count == 0) {
		secondary(q.net_list, "Looking for networks…");
		return;
	}
	struct c8ui_widget *focus = NULL;
	for (int i = 0; i < count; i++) {
		struct c8ui_widget *row = c8ui_canvas_new(0, 60, draw_net, net_event,
			NULL);
		row->fill = true;
		row->user_data = g_strdup(nets[i].ssid);
		row->on_destroy = net_destroyed;
		c8ui_widget_add(q.net_list, row);
		if (q.selected && strcmp(q.selected, nets[i].ssid) == 0) {
		struct c8ui_widget *more = net_details(&nets[i]);
			more->fill = true;
			c8ui_widget_add(q.net_list, more);
		}
	}
	if (q.key_entry) {
		focus = q.key_entry;
	}
	if (focus) {
		c8ui_widget_grab_focus(focus);
	}
}

static void networks_changed(void *data) {
	/* Not under the fingers of someone typing a key */
	if (q.stage == NET_KEY && q.key_entry) {
		return;
	}
	if (q.selected && find_net(q.selected) == NULL) {
		g_free(q.selected);
		q.selected = NULL;
		q.stage = NET_IDLE;
	}
	if (q.airplane) {
		c8ui_toggle_set(q.airplane, status.airplane);
	}
	rebuild_networks();
}

static void back_clicked(struct c8ui_widget *w, void *data) {
	panels_open_settings();
}

static void draw_back(struct c8ui_widget *w, cairo_t *cr, void *data) {
	double cx = w->rect.x + w->rect.width / 2, cy = w->rect.y +
		w->rect.height / 2;
	cairo_set_source_rgba(cr, 1, 1, 1, w->hovered ? 1 : 0.85);
	cairo_set_line_width(cr, 2);
	cairo_arc(cr, cx, cy, 15, 0, 2 * M_PI);
	cairo_stroke(cr);
	cairo_move_to(cr, cx + 7, cy);
	cairo_line_to(cr, cx - 7, cy);
	cairo_move_to(cr, cx - 1, cy - 6);
	cairo_line_to(cr, cx - 7, cy);
	cairo_line_to(cr, cx - 1, cy + 6);
	cairo_stroke(cr);
}

static bool back_event(struct c8ui_widget *w, const struct c8ui_event *ev,
		void *data) {
	if (ev->type == C8UI_EVENT_PRESS) {
		return true;
	}
	if (left_click(w, ev)) {
		back_clicked(w, data);
		return true;
	}
	return false;
}

static void networks_destroyed(struct c8ui_widget *w, void *data) {
	if (q.net_page != w) {
		return; // a new one was made before this went
	}
	network_unwatch();
	network_cancel();
	q.net_page = q.net_list = q.airplane = q.key_entry = NULL;
	g_free(q.selected);
	q.selected = NULL;
	g_free(q.error);
	q.error = NULL;
	q.stage = NET_IDLE;
}

/* In a flyout of its own with a back arrow to Settings; in XR the
 * Settings card's second page, airplane mode beside the list (card) */
static struct c8ui_widget *networks_new(bool card) {
	/* Nothing of one still going (its key entry) carries over */
	q.key_entry = NULL;
	g_free(q.selected);
	q.selected = NULL;
	g_free(q.error);
	q.error = NULL;
	q.stage = NET_IDLE;
	struct c8ui_widget *page = c8ui_box_new(card ? C8UI_HORIZONTAL :
		C8UI_VERTICAL, card ? 40 : 0);
	c8ui_widget_set_scheme(page, C8UI_SCHEME_DARK);
	page->on_destroy = networks_destroyed;
	struct c8ui_widget *body = c8ui_box_new(C8UI_VERTICAL, 12);
	struct c8ui_widget *side = body;
	if (card) {
		side = c8ui_box_new(C8UI_VERTICAL, 12);
		side->fixed_width = 250;
		c8ui_box_set_padding(side, 0, 4, 0, 0);
		c8ui_box_set_padding(body, 0, 4, 0, 0);
		c8ui_widget_add(page, side);
	} else {
		c8ui_box_set_padding(body, 30, 32, 30, 24);
	}
	struct c8ui_widget *scroll = c8ui_scroll_new(body);
	scroll->expand = true;
	scroll->fill = true;
	c8ui_widget_add(page, scroll);

	if (!card) {
		struct c8ui_widget *head = c8ui_box_new(C8UI_HORIZONTAL, 12);
		c8ui_widget_add(head, c8ui_canvas_new(34, 34, draw_back,
			back_event, NULL));
		c8ui_widget_add(head, c8ui_label_new("Networks",
			C8UI_TEXT_SUBHEADER));
		c8ui_widget_add(body, head);
	}
	q.airplane = c8ui_toggle_new("Airplane mode", NULL, status.airplane,
		airplane_changed, NULL);
	c8ui_widget_add(side, q.airplane);
	struct c8ui_widget *sub = c8ui_label_new("Wi-Fi", C8UI_TEXT_BODY_STRONG);
	c8ui_label_set_color(sub, C8UI_COLOR_SECONDARY);
	c8ui_widget_add(body, sub);
	q.net_list = c8ui_box_new(C8UI_VERTICAL, 0);
	q.net_list->fill = true;
	c8ui_widget_add(body, q.net_list);

	q.net_page = page;
	network_watch(networks_changed, NULL);
	rebuild_networks();
	return page;
}

struct c8ui_widget *quick_networks_new(void) {
	return networks_new(true);
}

static void quick_open_networks(void) {
	panels_show_flyout(networks_new(false), NULL, NULL);
}
