/*
 * The Search and Settings charms of the app in front. An app that serves
 * org.cont8nuum.Charms1 (documented in c8-protocols) under its app_id
 * gets a search pane that searches what it has, and its own commands and
 * pages in the Settings flyout. Everything else gets Start's search and
 * the usual flyout.
 *
 * Calls go out with a short timeout; a slow app gets the usual charms
 * rather than holding them up.
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include <gio/gdesktopappinfo.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include "shell.h"

#define PATH "/org/cont8nuum/Charms"
#define IFACE "org.cont8nuum.Charms1"
/* Long enough for an app that is busy for a moment, short enough that a
 * stuck one doesn't make the charm feel broken */
#define OPEN_TIMEOUT_MS 400
#define CALL_TIMEOUT_MS 2000
#define QUERY_DELAY_MS 120
#define MAX_RESULTS 50
#define ROW_H 48
#define ROW_ICON 32
#define PANE_INNER 286 // FLYOUT_WIDTH less the padding

struct command {
	char *id, *label;
	bool action;
};

struct result {
	char *id, *title, *subtitle, *icon;
};

/* A control on an app's settings page */
struct control {
	char *id, *type;
	struct c8ui_widget *widget;
};

static struct {
	GDBusConnection *bus;
	guint serial; // bumped on every open and close: stale replies drop

	/* The app the charm opened for */
	char *name; // its instance's unique bus name, or its app_id
	char *title; // what it's called

	/* Search pane */
	bool searching;
	struct c8ui_widget *pane, *entry, *list;
	struct result *results;
	int count, picked;
	guint query_timer, query_serial;
	GHashTable *icons; // name -> struct c8ui_icon, NULL if none

	/* Settings */
	bool settings;
	struct c8ui_widget *body; // the flyout's top part, ours
	char *command; // the page shown, NULL for the command list
	char *label; // its name
	bool single; // the app's only page, shown without the list
	struct control *controls;
	int ncontrols;
	struct command *commands; // the list, as last shown
	int ncommands;
	guint changed_sub;
} cx;

static GDBusConnection *bus(void) {
	if (cx.bus == NULL) {
		cx.bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL);
	}
	return cx.bus;
}

/* The app in front: Start hidden and its window on top */
static struct window *front_window(void) {
	if (shell.start_visible || wl_list_empty(&shell.windows)) {
		return NULL;
	}
	struct window *w = wl_container_of(shell.windows.next, w, link);
	/* Only a well-known name can be called by app_id */
	if (w->app_id == NULL || !g_dbus_is_name(w->app_id) ||
			g_dbus_is_unique_name(w->app_id)) {
		return NULL;
	}
	return w;
}

/* Its name as All apps shows it */
static char *app_title(struct window *w) {
	char *file = g_strconcat(w->app_id, ".desktop", NULL);
	GDesktopAppInfo *info = g_desktop_app_info_new(file);
	g_free(file);
	if (info) {
		char *name = g_strdup(g_app_info_get_name(G_APP_INFO(info)));
		g_object_unref(info);
		return name;
	}
	struct tile *tile = tile_for_app(w->app_id);
	if (tile && tile->name) {
		return g_strdup(tile->name);
	}
	return g_strdup(w->title ? w->title : w->app_id);
}

static void call(const char *method, GVariant *args, const GVariantType *ret,
		int timeout, GAsyncReadyCallback done, void *data) {
	g_dbus_connection_call(bus(), cx.name, PATH, IFACE, method, args, ret,
		G_DBUS_CALL_FLAGS_NO_AUTO_START, timeout, NULL, done, data);
}

/* A call whose answer doesn't matter, beyond a note when it fails */
static void sent(GObject *src, GAsyncResult *res, gpointer data) {
	GError *error = NULL;
	GVariant *ret = g_dbus_connection_call_finish(G_DBUS_CONNECTION(src),
		res, &error);
	if (ret) {
		g_variant_unref(ret);
	} else {
		g_message("charms: %s: %s", (char *)data, error->message);
		g_error_free(error);
	}
}

static void send(const char *method, GVariant *args) {
	call(method, args, NULL, CALL_TIMEOUT_MS, sent, (void *)method);
}

static bool unknown_method(GError *error) {
	return g_error_matches(error, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD);
}

static const char *dict_str(GVariant *dict, const char *key) {
	const char *s = NULL;
	if (!g_variant_lookup(dict, key, "&s", &s)) {
		return NULL;
	}
	return s;
}

static void unsubscribe(void) {
	if (cx.changed_sub) {
		g_dbus_connection_signal_unsubscribe(bus(), cx.changed_sub);
		cx.changed_sub = 0;
	}
}

static void free_results(void) {
	for (int i = 0; i < cx.count; i++) {
		g_free(cx.results[i].id);
		g_free(cx.results[i].title);
		g_free(cx.results[i].subtitle);
		g_free(cx.results[i].icon);
	}
	g_free(cx.results);
	cx.results = NULL;
	cx.count = 0;
	cx.picked = -1;
}

static void free_commands(void) {
	for (int i = 0; i < cx.ncommands; i++) {
		g_free(cx.commands[i].id);
		g_free(cx.commands[i].label);
	}
	g_free(cx.commands);
	cx.commands = NULL;
	cx.ncommands = 0;
}

static void free_controls(void) {
	for (int i = 0; i < cx.ncontrols; i++) {
		g_free(cx.controls[i].id);
		g_free(cx.controls[i].type);
	}
	g_free(cx.controls);
	cx.controls = NULL;
	cx.ncontrols = 0;
}

/* The pane or flyout went: forget the app and everything it said */
static void reset(void) {
	cx.serial++;
	g_clear_handle_id(&cx.query_timer, g_source_remove);
	unsubscribe();
	free_results();
	free_controls();
	free_commands();
	g_free(cx.command);
	cx.command = NULL;
	g_clear_pointer(&cx.label, g_free);
	cx.single = false;
	g_free(cx.name);
	g_free(cx.title);
	cx.name = cx.title = NULL;
	cx.searching = cx.settings = false;
	cx.pane = cx.entry = cx.list = cx.body = NULL;
}

void context_closed(void) {
	/* Also while still waiting for the app: its answer is too late now */
	if (cx.name || cx.searching || cx.settings) {
		reset();
	}
}

static void destroyed(struct c8ui_widget *w, void *data) {
	/* Replaced by another flyout without being closed (Networks) */
	if (w == cx.pane || w == cx.body) {
		reset();
	}
}

/* Which copy of the app the window in front is. Each copy of an app
 * asks for its app id as a bus name; the first has it and the rest wait
 * in the bus's queue for it. The one whose process has the window is the
 * one to ask. */
struct lookup {
	guint serial;
	void (*next)(void);
	uint32_t pid;
	int pending;
	char *primary, *found;
};

static void lookup_done(struct lookup *lk) {
	if (lk->serial == cx.serial) {
		/* No match: sandboxed apps reach the bus through a proxy with
		 * a pid of its own, so the first copy is the best guess */
		char *name = lk->found ? lk->found : lk->primary;
		if (name) {
			g_free(cx.name);
			cx.name = g_strdup(name);
		}
		lk->next();
	}
	g_free(lk->primary);
	g_free(lk->found);
	g_free(lk);
}

struct pid_call {
	struct lookup *lk;
	char *owner;
};

static void owner_pid(GObject *src, GAsyncResult *res, gpointer data) {
	struct pid_call *pc = data;
	struct lookup *lk = pc->lk;
	GVariant *ret = g_dbus_connection_call_finish(G_DBUS_CONNECTION(src),
		res, NULL);
	if (ret) {
		uint32_t pid = 0;
		g_variant_get(ret, "(u)", &pid);
		if (pid == lk->pid && lk->found == NULL) {
			lk->found = g_strdup(pc->owner);
		}
		g_variant_unref(ret);
	}
	g_free(pc->owner);
	g_free(pc);
	if (--lk->pending == 0) {
		lookup_done(lk);
	}
}

static void owners_got(GObject *src, GAsyncResult *res, gpointer data) {
	struct lookup *lk = data;
	GVariant *ret = g_dbus_connection_call_finish(G_DBUS_CONNECTION(src),
		res, NULL);
	if (ret == NULL || lk->serial != cx.serial) {
		/* Nobody has the name: the call that follows finds that out */
		if (ret) {
			g_variant_unref(ret);
		}
		lookup_done(lk);
		return;
	}
	char **owners = NULL;
	g_variant_get(ret, "(^as)", &owners);
	g_variant_unref(ret);
	lk->primary = owners && owners[0] ? g_strdup(owners[0]) : NULL;
	/* One more than there are owners, so none finishes it early */
	lk->pending = 1;
	for (int i = 0; owners && owners[i]; i++) {
		struct pid_call *pc = g_new0(struct pid_call, 1);
		pc->lk = lk;
		pc->owner = g_strdup(owners[i]);
		lk->pending++;
		g_dbus_connection_call(bus(), "org.freedesktop.DBus",
			"/org/freedesktop/DBus", "org.freedesktop.DBus",
			"GetConnectionUnixProcessID", g_variant_new("(s)", owners[i]),
			G_VARIANT_TYPE("(u)"), G_DBUS_CALL_FLAGS_NONE, OPEN_TIMEOUT_MS,
			NULL, owner_pid, pc);
	}
	g_strfreev(owners);
	if (--lk->pending == 0) {
		lookup_done(lk);
	}
}

/* Starts talking to the app in front, then runs next once it knows which
 * copy of it that is; false (and next isn't run) if there's none to ask */
static bool begin(void (*next)(void)) {
	reset();
	struct window *w = front_window();
	if (w == NULL || bus() == NULL) {
		return false;
	}
	cx.name = g_strdup(w->app_id);
	cx.title = app_title(w);
	if (w->pid == 0) {
		next(); // an older compositor: the first copy it is
		return true;
	}
	struct lookup *lk = g_new0(struct lookup, 1);
	lk->serial = cx.serial;
	lk->next = next;
	lk->pid = w->pid;
	g_dbus_connection_call(bus(), "org.freedesktop.DBus",
		"/org/freedesktop/DBus", "org.freedesktop.DBus", "ListQueuedOwners",
		g_variant_new("(s)", w->app_id), G_VARIANT_TYPE("(as)"),
		G_DBUS_CALL_FLAGS_NONE, OPEN_TIMEOUT_MS, NULL, owners_got, lk);
	return true;
}

/* Headers: "Search" or "Settings" over the app's name, or a back arrow
 * and the page's name */

static void title_block(struct c8ui_widget *box, const char *title) {
	/* Settings over XR's bar: the card's pivot says it */
	if (strcmp(title, "Settings") != 0 || panels_headed()) {
		c8ui_widget_add(box, c8ui_label_new(title, C8UI_TEXT_SUBHEADER));
	}
	struct c8ui_widget *sub = c8ui_label_new(cx.title, C8UI_TEXT_BODY_STRONG);
	c8ui_label_set_color(sub, C8UI_COLOR_SECONDARY);
	c8ui_widget_add(box, sub);
}

/* Search pane */

static void search_query(const char *text);

static struct c8ui_icon *result_icon(const char *name) {
	if (name == NULL || name[0] == '\0') {
		return NULL;
	}
	gpointer icon;
	if (g_hash_table_lookup_extended(cx.icons, name, NULL, &icon)) {
		return icon;
	}
	icon = c8ui_icon_load(shell.appearance.icon_theme, name);
	g_hash_table_insert(cx.icons, g_strdup(name), icon);
	return icon;
}

static void draw_row(struct c8ui_widget *w, cairo_t *cr, void *data) {
	int i = (int)(intptr_t)data;
	if (i >= cx.count) {
		return;
	}
	struct result *r = &cx.results[i];
	struct c8ui_rect *b = &w->rect;
	if (i == cx.picked || w->hovered) {
		cairo_set_source_rgba(cr, 1, 1, 1, i == cx.picked ? 0.22 : 0.12);
		cairo_rectangle(cr, b->x, b->y, b->width, b->height);
		cairo_fill(cr);
	}
	double tx = b->x + 8;
	struct c8ui_icon *icon = result_icon(r->icon);
	if (icon) {
		c8ui_icon_draw_fit(cr, icon, b->x + 8 + ROW_ICON / 2.0,
			b->y + b->height / 2.0, ROW_ICON);
		tx += ROW_ICON + 12;
	}
	double tw = b->x + b->width - 8 - tx;
	const char *family = c8ui_widget_font(w);
	bool two = r->subtitle && r->subtitle[0];
	cairo_set_source_rgb(cr, 1, 1, 1);
	c8ui_text_draw(cr, family, (struct c8ui_font){ 15, C8UI_WEIGHT_NORMAL },
		r->title ? r->title : "", tx, b->y + (two ? 5 : 13), tw, 1);
	if (two) {
		cairo_set_source_rgba(cr, 1, 1, 1, 0.6);
		c8ui_text_draw(cr, family,
			(struct c8ui_font){ 12, C8UI_WEIGHT_NORMAL }, r->subtitle, tx,
			b->y + 26, tw, 1);
	}
}

static void activate_result(int i) {
	if (i < 0 || i >= cx.count) {
		return;
	}
	send("ActivateResult", g_variant_new("(ss)", cx.results[i].id,
		cx.entry ? c8ui_entry_get(cx.entry) : ""));
	panels_close();
}

static bool row_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 (ev->type == C8UI_EVENT_RELEASE && ev->button == C8UI_BUTTON_LEFT &&
			c8ui_rect_contains(&w->rect, ev->x, ev->y)) {
		activate_result((int)(intptr_t)data);
		return true;
	}
	return false;
}

static void fill_list(void) {
	if (cx.list == NULL) {
		return;
	}
	c8ui_widget_clear(cx.list);
	for (int i = 0; i < cx.count; i++) {
		struct c8ui_widget *row = c8ui_canvas_new(PANE_INNER, ROW_H, draw_row,
			row_event, (void *)(intptr_t)i);
		row->fill = true;
		c8ui_widget_add(cx.list, row);
	}
	if (cx.count == 0 && cx.entry && c8ui_entry_get(cx.entry)[0]) {
		struct c8ui_widget *none = c8ui_label_new("No results",
			C8UI_TEXT_BODY);
		c8ui_label_set_color(none, C8UI_COLOR_SECONDARY);
		c8ui_widget_add(cx.list, none);
	}
}

/* Results from Search's reply, which must be (aa{sv}) */
static void take_results(GVariant *ret) {
	free_results();
	GVariant *list = g_variant_get_child_value(ret, 0);
	gsize n = g_variant_n_children(list);
	n = n > MAX_RESULTS ? MAX_RESULTS : n;
	cx.results = g_new0(struct result, n ? n : 1);
	for (gsize i = 0; i < n; i++) {
		GVariant *dict = g_variant_get_child_value(list, i);
		const char *id = dict_str(dict, "id");
		const char *title = dict_str(dict, "title");
		if (id && title) {
			struct result *r = &cx.results[cx.count++];
			r->id = g_strdup(id);
			r->title = g_strdup(title);
			r->subtitle = g_strdup(dict_str(dict, "subtitle"));
			r->icon = g_strdup(dict_str(dict, "icon"));
		}
		g_variant_unref(dict);
	}
	g_variant_unref(list);
}

static void searched(GObject *src, GAsyncResult *res, gpointer data) {
	guint serial = GPOINTER_TO_UINT(data);
	GError *error = NULL;
	GVariant *ret = g_dbus_connection_call_finish(G_DBUS_CONNECTION(src),
		res, &error);
	if (serial != cx.query_serial || !cx.searching) {
		/* An answer to something typed since, or after it closed */
	} else if (ret) {
		take_results(ret);
		fill_list();
	} else {
		g_message("charms: Search: %s", error->message);
	}
	if (ret) {
		g_variant_unref(ret);
	}
	g_clear_error(&error);
}

static gboolean query_now(gpointer data) {
	cx.query_timer = 0;
	if (cx.entry) {
		search_query(c8ui_entry_get(cx.entry));
	}
	return G_SOURCE_REMOVE;
}

static void search_query(const char *text) {
	cx.query_serial++;
	call("Search", g_variant_new("(s)", text), G_VARIANT_TYPE("(aa{sv})"),
		CALL_TIMEOUT_MS, searched, GUINT_TO_POINTER(cx.query_serial));
}

static void typed(struct c8ui_widget *w, void *data) {
	cx.picked = -1;
	if (cx.query_timer) {
		g_source_remove(cx.query_timer);
	}
	cx.query_timer = g_timeout_add(QUERY_DELAY_MS, query_now, NULL);
}

/* What Submit falls back on, carried along since the pane has closed */
struct submit {
	char *name, *query, *first; // first: the best result's id, or NULL
};

static void submitted(GObject *src, GAsyncResult *res, gpointer data) {
	struct submit *sb = data;
	GError *error = NULL;
	GVariant *ret = g_dbus_connection_call_finish(G_DBUS_CONNECTION(src),
		res, &error);
	if (ret) {
		g_variant_unref(ret);
	} else if (unknown_method(error) && sb->first) {
		/* No Submit: the best result instead */
		g_dbus_connection_call(bus(), sb->name, PATH, IFACE,
			"ActivateResult", g_variant_new("(ss)", sb->first, sb->query),
			NULL, G_DBUS_CALL_FLAGS_NO_AUTO_START, CALL_TIMEOUT_MS, NULL,
			sent, "ActivateResult");
	} else if (!unknown_method(error)) {
		g_message("charms: Submit: %s", error->message);
	}
	g_clear_error(&error);
	g_free(sb->name);
	g_free(sb->query);
	g_free(sb->first);
	g_free(sb);
}

/* Enter in the box */
static void entered(struct c8ui_widget *w, void *data) {
	if (cx.picked >= 0) {
		activate_result(cx.picked);
		return;
	}
	const char *text = c8ui_entry_get(w);
	if (text[0] == '\0') {
		return;
	}
	struct submit *sb = g_new0(struct submit, 1);
	sb->name = g_strdup(cx.name);
	sb->query = g_strdup(text);
	sb->first = cx.count > 0 ? g_strdup(cx.results[0].id) : NULL;
	call("Submit", g_variant_new("(s)", text), NULL, CALL_TIMEOUT_MS,
		submitted, sb);
	panels_close();
}

static void everywhere(struct c8ui_widget *w, void *data) {
	char *text = g_strdup(cx.entry ? c8ui_entry_get(cx.entry) : "");
	panels_close();
	start_open_search(text[0] ? text : NULL);
	g_free(text);
}

static void pick(int i) {
	cx.picked = i < -1 ? -1 : i >= cx.count ? cx.count - 1 : i;
	if (cx.list) {
		c8ui_widget_queue_draw(cx.list);
		if (cx.picked >= 0 && cx.picked < cx.list->child_count) {
			struct c8ui_widget *row = cx.list->children[cx.picked];
			c8ui_widget_reveal(row, &row->rect);
		}
	}
}

static bool pane_key(const struct c8ui_event *ev, void *data) {
	switch (ev->sym) {
	case XKB_KEY_Down:
		pick(cx.picked + 1);
		return true;
	case XKB_KEY_Up:
		pick(cx.picked - 1);
		return true;
	}
	return false;
}

static void open_pane(GVariant *first) {
	struct c8ui_widget *page = c8ui_box_new(C8UI_VERTICAL, 0);
	c8ui_widget_set_scheme(page, C8UI_SCHEME_DARK);
	page->on_destroy = destroyed;
	struct c8ui_widget *top = c8ui_box_new(C8UI_VERTICAL, 12);
	c8ui_box_set_padding(top, 30, 32, 30, 16);
	c8ui_widget_add(page, top);
	title_block(top, "Search");
	cx.entry = c8ui_entry_new(NULL, "", entered, NULL);
	c8ui_entry_set_enter_only(cx.entry, true); // not focus leaving
	char *hint = g_strdup_printf("Search %s", cx.title);
	c8ui_entry_set_placeholder(cx.entry, hint);
	g_free(hint);
	c8ui_entry_on_change(cx.entry, typed, NULL);
	cx.entry->fill = true;
	c8ui_widget_add(top, cx.entry);

	cx.list = c8ui_box_new(C8UI_VERTICAL, 0);
	c8ui_box_set_padding(cx.list, 22, 0, 22, 12);
	struct c8ui_widget *scroll = c8ui_scroll_new(cx.list);
	scroll->expand = true;
	scroll->fill = true;
	c8ui_widget_add(page, scroll);

	struct c8ui_widget *foot = c8ui_box_new(C8UI_VERTICAL, 0);
	c8ui_box_set_padding(foot, 30, 12, 30, 36);
	c8ui_widget_add(page, foot);
	c8ui_widget_add(foot, c8ui_link_new("Search everywhere", everywhere,
		NULL));

	cx.pane = page;
	cx.searching = true;
	take_results(first);
	fill_list();
	panels_show_flyout(page, pane_key, NULL);
	c8ui_widget_grab_focus(cx.entry);
}

/* The answer to opening a charm: the reply (to unref), or NULL with
 * *stale saying something else was opened meanwhile; when not, the app
 * has no such charm (or isn't answering) and Start's own is the way. */
static GVariant *opened_reply(GObject *src, GAsyncResult *res, gpointer data,
		bool *stale) {
	GError *error = NULL;
	GVariant *ret = g_dbus_connection_call_finish(G_DBUS_CONNECTION(src),
		res, &error);
	*stale = GPOINTER_TO_UINT(data) != cx.serial;
	if (*stale) {
		g_clear_pointer(&ret, g_variant_unref);
	} else if (ret == NULL) {
		if (!g_error_matches(error, G_DBUS_ERROR, G_DBUS_ERROR_SERVICE_UNKNOWN)
				&& !unknown_method(error)) {
			g_message("charms: %s: %s", cx.name, error->message);
		}
		reset();
	}
	g_clear_error(&error);
	return ret;
}

static void search_opened(GObject *src, GAsyncResult *res, gpointer data) {
	bool stale;
	GVariant *ret = opened_reply(src, res, data, &stale);
	if (ret) {
		open_pane(ret);
		g_variant_unref(ret);
	} else if (!stale) {
		start_open_search(NULL);
	}
}

static void ask_search(void) {
	call("Search", g_variant_new("(s)", ""), G_VARIANT_TYPE("(aa{sv})"),
		OPEN_TIMEOUT_MS, search_opened, GUINT_TO_POINTER(cx.serial));
}

void context_search(void) {
	if (cx.searching) {
		panels_close(); // pressed again: put it away
		return;
	}
	if (!begin(ask_search)) {
		start_open_search(NULL);
	}
}

/* Settings */

static void show_commands(GVariant *commands);
static void show_page(const char *command, const char *label,
	GVariant *controls);

static struct c8ui_widget *new_body(void) {
	struct c8ui_widget *body = c8ui_box_new(C8UI_VERTICAL, 12);
	body->on_destroy = destroyed;
	return body;
}

/* The command list runs edge to edge, like PC settings' list of pages;
 * a page of controls has the flyout's margins */
static void body_padding(struct c8ui_widget *body, bool edge) {
	if (!panels_headed()) { // XR's Settings card has margins already
		c8ui_box_set_padding(body, 0, 4, 0, 0);
		return;
	}
	c8ui_box_set_padding(body, edge ? 0 : 30, 32, edge ? 0 : 30, 24);
}

/* Puts the flyout's top part in place: the first time it opens it */
static void set_body(struct c8ui_widget *body, bool edge) {
	if (cx.body == NULL) {
		cx.body = body;
		body_padding(body, edge);
		panels_open_settings_with(body);
		return;
	}
	body_padding(cx.body, edge);
	/* A page in place of the list, or back: same flyout */
	c8ui_widget_clear(cx.body);
	for (int i = body->child_count - 1; i >= 0; i--) {
		struct c8ui_widget *child = body->children[0];
		c8ui_widget_unparent(child);
		c8ui_widget_add(cx.body, child);
	}
	c8ui_widget_destroy(body);
	c8ui_widget_enter(cx.body);
}


struct page_call {
	guint serial;
	char *id, *label;
	bool refresh;
};

static void page_reply(GObject *src, GAsyncResult *res, gpointer data) {
	struct page_call *pc = data;
	GError *error = NULL;
	GVariant *ret = g_dbus_connection_call_finish(G_DBUS_CONNECTION(src),
		res, &error);
	bool current = pc->serial == cx.serial && cx.settings;
	if (ret && current) {
		GVariant *controls = g_variant_get_child_value(ret, 0);
		if (!pc->refresh || (cx.command && strcmp(cx.command, pc->id) == 0)) {
			show_page(pc->id, pc->label, controls);
		}
		g_variant_unref(controls);
	} else if (!ret) {
		g_message("charms: GetSettingsPage: %s", error->message);
		if (current && cx.body == NULL) {
			/* Its only page, and nothing open yet: Settings as usual */
			reset();
			panels_open_settings_with(NULL);
		}
	}
	if (ret) {
		g_variant_unref(ret);
	}
	g_clear_error(&error);
	g_free(pc->id);
	g_free(pc->label);
	g_free(pc);
}

static void fetch_page(const char *id, const char *label, bool refresh) {
	struct page_call *pc = g_new0(struct page_call, 1);
	pc->serial = cx.serial;
	pc->id = g_strdup(id);
	pc->label = g_strdup(label);
	pc->refresh = refresh;
	call("GetSettingsPage", g_variant_new("(s)", id),
		G_VARIANT_TYPE("(aa{sv})"), CALL_TIMEOUT_MS, page_reply, pc);
}

static void command_chosen(struct c8ui_widget *nav, void *data) {
	int i = c8ui_nav_get(nav);
	if (i < 0 || i >= cx.ncommands) {
		return;
	}
	struct command *c = &cx.commands[i];
	if (c->action) {
		send("ActivateSettings", g_variant_new("(s)", c->id));
		panels_close();
	} else {
		fetch_page(c->id, c->label, false);
	}
}

static void commands_reply(GObject *src, GAsyncResult *res, gpointer data);

static void fetch_commands(GAsyncReadyCallback done, int timeout) {
	call("GetSettings", NULL, G_VARIANT_TYPE("(a(sss))"), timeout, done,
		GUINT_TO_POINTER(cx.serial));
}

/* Back to the command list */
static void back_clicked(struct c8ui_widget *w, void *data) {
	g_free(cx.command);
	cx.command = NULL;
	fetch_commands(commands_reply, CALL_TIMEOUT_MS);
}

static void draw_back(struct c8ui_widget *w, cairo_t *cr, void *data) {
	struct c8ui_rect *r = &w->rect;
	double cx_ = r->x + 16, cy = r->y + r->height / 2;
	cairo_set_source_rgba(cr, 1, 1, 1, w->pressed ? 0.6 : 1);
	cairo_set_line_width(cr, 2);
	cairo_arc(cr, cx_, cy, 14, 0, 2 * G_PI);
	cairo_stroke(cr);
	if (w->hovered) {
		cairo_arc(cr, cx_, cy, 13, 0, 2 * G_PI);
		cairo_set_source_rgba(cr, 1, 1, 1, 0.15);
		cairo_fill(cr);
		cairo_set_source_rgb(cr, 1, 1, 1);
	}
	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);
	cairo_set_source_rgb(cr, 1, 1, 1);
	c8ui_text_draw(cr, c8ui_widget_font(w),
		c8ui_text_font(C8UI_TEXT_SUBHEADER), data ? data : "", r->x + 44,
		r->y + 1, r->width - 44, 1);
}

static bool back_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 (ev->type == C8UI_EVENT_RELEASE && ev->button == C8UI_BUTTON_LEFT &&
			c8ui_rect_contains(&w->rect, ev->x, ev->y)) {
		back_clicked(w, NULL);
		return true;
	}
	return false;
}

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

static void show_commands(GVariant *commands) {
	free_commands();
	gsize n = g_variant_n_children(commands);
	cx.commands = g_new0(struct command, n ? n : 1);
	GVariantIter iter;
	const char *id, *label, *kind;
	g_variant_iter_init(&iter, commands);
	while (g_variant_iter_next(&iter, "(&s&s&s)", &id, &label, &kind)) {
		struct command *c = &cx.commands[cx.ncommands++];
		c->id = g_strdup(id);
		c->label = g_strdup(label);
		c->action = strcmp(kind, "action") == 0;
	}
	/* A list of one page is a click for nothing: show the page */
	if (cx.ncommands == 1 && !cx.commands[0].action) {
		bool was = cx.single && cx.command &&
			strcmp(cx.command, cx.commands[0].id) == 0;
		cx.single = true;
		fetch_page(cx.commands[0].id, cx.commands[0].label, was);
		return;
	}
	cx.single = false;
	g_free(cx.command);
	cx.command = NULL;
	free_controls();
	struct c8ui_widget *body = new_body();
	struct c8ui_widget *head = c8ui_box_new(C8UI_VERTICAL, 12);
	c8ui_box_set_padding(head, 30, 0, 30, 8);
	c8ui_widget_add(body, head);
	title_block(head, "Settings");

	struct c8ui_widget *nav = c8ui_nav_new(command_chosen, NULL);
	c8ui_nav_set_inset(nav, panels_headed() ? 30 : 0);
	for (int i = 0; i < cx.ncommands; i++) {
		c8ui_nav_add(nav, cx.commands[i].label);
	}
	c8ui_nav_set(nav, -1); // nothing chosen yet
	c8ui_widget_add(body, nav);
	set_body(body, true);
}

static void commands_reply(GObject *src, GAsyncResult *res, gpointer data) {
	guint serial = GPOINTER_TO_UINT(data);
	GError *error = NULL;
	GVariant *ret = g_dbus_connection_call_finish(G_DBUS_CONNECTION(src),
		res, &error);
	if (ret && serial == cx.serial && cx.settings &&
			(cx.command == NULL || cx.single)) {
		GVariant *commands = g_variant_get_child_value(ret, 0);
		show_commands(commands);
		g_variant_unref(commands);
	} else if (!ret) {
		g_message("charms: GetSettings: %s", error->message);
	}
	if (ret) {
		g_variant_unref(ret);
	}
	g_clear_error(&error);
}

/* Controls */

static struct control *control_of(struct c8ui_widget *w) {
	for (int i = 0; i < cx.ncontrols; i++) {
		if (cx.controls[i].widget == w) {
			return &cx.controls[i];
		}
	}
	return NULL;
}

static void set_setting(struct c8ui_widget *w, GVariant *value) {
	struct control *c = control_of(w);
	if (c == NULL || cx.command == NULL) {
		g_variant_unref(g_variant_ref_sink(value));
		return;
	}
	send("SetSetting", g_variant_new("(ssv)", cx.command, c->id, value));
}

static void toggled(struct c8ui_widget *w, void *data) {
	set_setting(w, g_variant_new_boolean(c8ui_toggle_get(w)));
}

static void chose(struct c8ui_widget *w, void *data) {
	set_setting(w, g_variant_new_int32(c8ui_combo_get(w)));
}

static void chose_button(struct c8ui_widget *w, void *data) {
	set_setting(w, g_variant_new_int32(c8ui_choice_get(w)));
}

static void slid(struct c8ui_widget *w, void *data) {
	if (!c8ui_slider_is_live(w)) {
		set_setting(w, g_variant_new_double(c8ui_slider_get(w)));
	}
}

static void edited(struct c8ui_widget *w, void *data) {
	set_setting(w, g_variant_new_string(c8ui_entry_get(w)));
}

static void pressed(struct c8ui_widget *w, void *data) {
	set_setting(w, g_variant_new_boolean(true));
}

static double dict_double(GVariant *dict, const char *key, double def) {
	double d;
	return g_variant_lookup(dict, key, "d", &d) ? d : def;
}

static int dict_int(GVariant *dict, const char *key, int def) {
	int32_t i;
	return g_variant_lookup(dict, key, "i", &i) ? i : def;
}

static bool dict_bool(GVariant *dict, const char *key, bool def) {
	gboolean b;
	return g_variant_lookup(dict, key, "b", &b) ? b : def;
}

/* Free with g_strfreev */
static char **dict_strv(GVariant *dict, const char *key, int *n) {
	char **v = NULL;
	if (!g_variant_lookup(dict, key, "^as", &v)) {
		v = g_new0(char *, 1);
	}
	*n = (int)g_strv_length(v);
	return v;
}

/* A widget for one control; NULL for a type we don't know */
static struct c8ui_widget *make_control(GVariant *dict, const char *type) {
	const char *label = dict_str(dict, "label");
	struct c8ui_widget *w = NULL;
	int n;
	char **opts;
	if (strcmp(type, "toggle") == 0) {
		w = c8ui_toggle_new(label, dict_str(dict, "description"),
			dict_bool(dict, "value", false), toggled, NULL);
	} else if (strcmp(type, "choice") == 0 || strcmp(type, "buttons") == 0) {
		opts = dict_strv(dict, "options", &n);
		int v = dict_int(dict, "value", 0);
		w = strcmp(type, "choice") == 0 ?
			c8ui_combo_new(label, (const char *const *)opts, n, v, chose,
				NULL) :
			c8ui_choice_new(label, (const char *const *)opts, n, v,
				chose_button, NULL);
		g_strfreev(opts);
	} else if (strcmp(type, "slider") == 0) {
		w = c8ui_slider_new(label, dict_double(dict, "min", 0),
			dict_double(dict, "max", 100), dict_double(dict, "step", 1),
			dict_double(dict, "value", 0), slid, NULL);
	} else if (strcmp(type, "text") == 0) {
		const char *value = dict_str(dict, "value");
		w = c8ui_entry_new(label, value ? value : "", edited, NULL);
		const char *ph = dict_str(dict, "placeholder");
		if (ph) {
			c8ui_entry_set_placeholder(w, ph);
		}
		c8ui_entry_set_password(w, dict_bool(dict, "password", false));
		w->fill = true;
	} else if (strcmp(type, "button") == 0) {
		w = c8ui_button_new(label ? label : "", pressed, NULL);
	} else if (strcmp(type, "link") == 0) {
		w = c8ui_link_new(label ? label : "", pressed, NULL);
	} else if (strcmp(type, "heading") == 0) {
		w = c8ui_label_new(label ? label : "", C8UI_TEXT_TITLE);
	} else if (strcmp(type, "paragraph") == 0) {
		w = c8ui_label_new(label ? label : "", C8UI_TEXT_BODY);
	}
	if (w && !dict_bool(dict, "enabled", true)) {
		c8ui_widget_set_disabled(w, true);
	}
	return w;
}

/* The same controls again: new values set in place, so nothing moves */
static bool update_controls(GVariant *controls) {
	gsize n = g_variant_n_children(controls);
	int shown = 0;
	for (gsize i = 0; i < n; i++) {
		GVariant *dict = g_variant_get_child_value(controls, i);
		const char *id = dict_str(dict, "id"), *type = dict_str(dict, "type");
		bool known = type && (strcmp(type, "toggle") == 0 ||
			strcmp(type, "choice") == 0 || strcmp(type, "buttons") == 0 ||
			strcmp(type, "slider") == 0 || strcmp(type, "text") == 0 ||
			strcmp(type, "button") == 0 || strcmp(type, "link") == 0 ||
			strcmp(type, "heading") == 0 || strcmp(type, "paragraph") == 0);
		bool same = !known || (shown < cx.ncontrols &&
			g_strcmp0(cx.controls[shown].id, id) == 0 &&
			strcmp(cx.controls[shown].type, type) == 0);
		g_variant_unref(dict);
		if (!same) {
			return false;
		}
		shown += known;
	}
	if (shown != cx.ncontrols) {
		return false;
	}
	shown = 0;
	for (gsize i = 0; i < n; i++) {
		GVariant *dict = g_variant_get_child_value(controls, i);
		const char *type = dict_str(dict, "type");
		struct control *c = shown < cx.ncontrols &&
			g_strcmp0(cx.controls[shown].type, type) == 0 ?
			&cx.controls[shown] : NULL;
		if (c) {
			struct c8ui_widget *w = c->widget;
			const char *value;
			int count;
			char **opts;
			shown++;
			c8ui_widget_set_disabled(w, !dict_bool(dict, "enabled", true));
			if (strcmp(type, "toggle") == 0) {
				c8ui_toggle_set(w, dict_bool(dict, "value", false));
			} else if (strcmp(type, "choice") == 0) {
				opts = dict_strv(dict, "options", &count);
				c8ui_combo_set_items(w, (const char *const *)opts, count,
					dict_int(dict, "value", 0));
				g_strfreev(opts);
			} else if (strcmp(type, "buttons") == 0) {
				c8ui_choice_set(w, dict_int(dict, "value", 0));
			} else if (strcmp(type, "slider") == 0) {
				c8ui_slider_set(w, dict_double(dict, "value", 0));
			} else if (strcmp(type, "text") == 0) {
				value = dict_str(dict, "value");
				if (!w->focused) {
					c8ui_entry_set(w, value ? value : "");
				}
			} else if (strcmp(type, "heading") == 0 ||
					strcmp(type, "paragraph") == 0) {
				value = dict_str(dict, "label");
				c8ui_label_set_text(w, value ? value : "");
			}
		}
		g_variant_unref(dict);
	}
	return true;
}

static void show_page(const char *command, const char *label,
		GVariant *controls) {
	bool same_page = cx.command && strcmp(cx.command, command) == 0;
	if (same_page && update_controls(controls)) {
		return;
	}
	free_controls();
	g_free(cx.command);
	cx.command = g_strdup(command);
	g_free(cx.label);
	cx.label = g_strdup(label);

	struct c8ui_widget *body = new_body();
	if (cx.single) {
		/* Nothing to go back to: headed like the list it stands for */
		title_block(body, "Settings");
	} else {
		char *name = g_strdup(label);
		struct c8ui_widget *back = c8ui_canvas_new(PANE_INNER, 36, draw_back,
			back_event, name);
		back->on_destroy = free_data;
		c8ui_widget_add(body, back);
		struct c8ui_widget *sub = c8ui_label_new(cx.title,
			C8UI_TEXT_BODY_STRONG);
		c8ui_label_set_color(sub, C8UI_COLOR_SECONDARY);
		c8ui_widget_add(body, sub);
	}

	gsize n = g_variant_n_children(controls);
	cx.controls = g_new0(struct control, n ? n : 1);
	for (gsize i = 0; i < n; i++) {
		GVariant *dict = g_variant_get_child_value(controls, i);
		const char *type = dict_str(dict, "type");
		struct c8ui_widget *w = type ? make_control(dict, type) : NULL;
		if (w) {
			struct control *c = &cx.controls[cx.ncontrols++];
			c->id = g_strdup(dict_str(dict, "id"));
			c->type = g_strdup(type);
			c->widget = w;
			c8ui_widget_add(body, w);
		}
		g_variant_unref(dict);
	}
	set_body(body, false);
}

static void settings_changed(GDBusConnection *conn, const char *sender,
		const char *path, const char *iface, const char *signal,
		GVariant *params, gpointer data) {
	if (!cx.settings) {
		return;
	}
	const char *command;
	g_variant_get(params, "(&s)", &command);
	if (command[0] == '\0' && (cx.command == NULL || cx.single)) {
		/* The list changed: a lone page may have company now */
		fetch_commands(commands_reply, CALL_TIMEOUT_MS);
	} else if (cx.command && strcmp(cx.command, command) == 0) {
		fetch_page(command, cx.label, true);
	}
}

static void settings_opened(GObject *src, GAsyncResult *res, gpointer data) {
	bool stale;
	GVariant *ret = opened_reply(src, res, data, &stale);
	if (ret) {
		cx.settings = true;
		/* The app's own name owner: signals come from its unique name */
		cx.changed_sub = g_dbus_connection_signal_subscribe(bus(), cx.name,
			IFACE, "SettingsChanged", PATH, NULL, G_DBUS_SIGNAL_FLAGS_NONE,
			settings_changed, NULL, NULL);
		GVariant *commands = g_variant_get_child_value(ret, 0);
		show_commands(commands);
		g_variant_unref(commands);
		g_variant_unref(ret);
	} else if (!stale) {
		panels_open_settings_with(NULL);
	}
}

static void ask_settings(void) {
	fetch_commands(settings_opened, OPEN_TIMEOUT_MS);
}

char *context_front_title(void) {
	/* Any app, not only one with a bus name */
	if (shell.start_visible || wl_list_empty(&shell.windows)) {
		return NULL;
	}
	struct window *w = wl_container_of(shell.windows.next, w, link);
	return w->app_id ? app_title(w) : NULL;
}

void context_settings(void) {
	if (!begin(ask_settings)) {
		panels_open_settings_with(NULL);
	}
}

void context_init(void) {
	cx.picked = -1;
	cx.icons = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
		(GDestroyNotify)c8ui_icon_destroy);
}
