/*
 * Live tile content. Apps and scripts send it over the session bus
 * (org.cont8nuum.Tiles1, documented in c8-protocols); it is kept per tile
 * id, whether that tile is pinned or not, and saved so tiles look right
 * at the next login before their apps have run. templates.c draws it.
 */
#define _GNU_SOURCE
#include <errno.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include <gio/gio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "shell.h"
#include "pixels.h"
#include "tiles-info.h"

#define BUS_NAME "org.cont8nuum.Tiles"
#define BUS_PATH "/org/cont8nuum/Tiles"
#define BUS_IFACE "org.cont8nuum.Tiles1"

#define QUEUE_MAX 5
#define PENDING_MAX 32 // scheduled updates waiting, per tile
/* Limits, so one runaway script can't eat the shell's memory */
#define LIVES_MAX 256
#define FIELDS_MAX 64
#define VALUE_MAX 4096
#define IMAGE_MAX 640 // pixels, enough for a large tile at scale 2
/* Busy providers update every second or two while Start shows, and each
 * save writes every tile: once a minute while they keep coming, and at
 * once when Start goes or the shell leaves (live_flush) */
#define SAVE_DELAY_S 60

static struct {
	GHashTable *lives; // id -> struct live
	GDBusConnection *bus;
	guint object_id;
	guint save_timer;
	guint wake_timer; // for the next scheduled update or expiry
	int64_t wake_for; // the time it was set for
	bool launched; // the providers, once the name was ours
	/* What TileChanged last said, so only changes are sent: id -> size */
	GHashTable *announced;
	char *path;
} lv;

static const char *size_names[] = {
	[TILE_SMALL] = "small",
	[TILE_MEDIUM] = "medium",
	[TILE_WIDE] = "wide",
	[TILE_LARGE] = "large",
};

static void image_free(gpointer data) {
	if (data) {
		cairo_surface_destroy(data);
	}
}

static struct live_update *update_new(const char *tag) {
	struct live_update *u = g_new0(struct live_update, 1);
	u->tag = g_strdup(tag);
	u->fields = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
	u->images = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
		image_free);
	return u;
}

static void update_free(gpointer data) {
	struct live_update *u = data;
	g_free(u->tag);
	g_hash_table_destroy(u->fields);
	g_hash_table_destroy(u->images);
	g_free(u);
}

static void live_free(gpointer data) {
	struct live *live = data;
	g_free(live->id);
	g_ptr_array_unref(live->updates);
	g_ptr_array_unref(live->pending);
	g_free(live->badge);
	g_free(live);
}

struct live *live_find(const char *id) {
	return lv.lives ? g_hash_table_lookup(lv.lives, id) : NULL;
}

static struct live *live_get(const char *id) {
	struct live *live = live_find(id);
	if (live == NULL) {
		live = g_new0(struct live, 1);
		live->id = g_strdup(id);
		live->updates = g_ptr_array_new_with_free_func(update_free);
		live->pending = g_ptr_array_new_with_free_func(update_free);
		g_hash_table_insert(lv.lives, live->id, live);
	}
	return live;
}

const char *live_field(struct live_update *u, enum tile_size size,
		const char *key) {
	char sized[96];
	snprintf(sized, sizeof(sized), "%s.%s", size_names[size], key);
	const char *v = g_hash_table_lookup(u->fields, sized);
	return v ? v : g_hash_table_lookup(u->fields, key);
}

/* Images */

cairo_surface_t *live_load_image(const char *ref) {
	char *path = g_str_has_prefix(ref, "file://") ?
		g_filename_from_uri(ref, NULL, NULL) : g_strdup(ref);
	if (path == NULL || path[0] != '/') {
		g_free(path);
		return NULL;
	}
	GdkPixbuf *pb = gdk_pixbuf_new_from_file_at_size(path, IMAGE_MAX,
		IMAGE_MAX, NULL);
	g_free(path);
	return image_from_pixbuf(pb);
}

cairo_surface_t *live_image(struct live_update *u, const char *ref) {
	if (ref == NULL || ref[0] == '\0') {
		return NULL;
	}
	gpointer found;
	if (g_hash_table_lookup_extended(u->images, ref, NULL, &found)) {
		return found;
	}
	cairo_surface_t *s = live_load_image(ref);
	g_hash_table_insert(u->images, g_strdup(ref), s); // NULL: failed, don't retry
	return s;
}

/* Saving, to the cache: it's only a head start for the next login */

static gboolean save_now(gpointer data) {
	lv.save_timer = 0;
	GKeyFile *kf = g_key_file_new();
	GHashTableIter it;
	gpointer value;
	g_hash_table_iter_init(&it, lv.lives);
	while (g_hash_table_iter_next(&it, NULL, &value)) {
		struct live *live = value;
		char *group = g_strdup_printf("tile %s", live->id);
		if (live->badge) {
			g_key_file_set_string(kf, group, "badge", live->badge);
		}
		g_key_file_set_integer(kf, group, "updates", live->updates->len);
		g_key_file_set_integer(kf, group, "pending", live->pending->len);
		g_free(group);
		for (int kind = 0; kind < 2; kind++) {
			GPtrArray *list = kind ? live->pending : live->updates;
			for (guint i = 0; i < list->len; i++) {
				struct live_update *u = list->pdata[i];
				group = g_strdup_printf("%s %u %s", kind ? "pending" : "update",
					i, live->id);
				g_key_file_set_string(kf, group, "tag", u->tag);
				if (u->expires) {
					g_key_file_set_int64(kf, group, "expires", u->expires);
				}
				if (kind) {
					g_key_file_set_int64(kf, group, "starts", u->starts);
					g_key_file_set_int64(kf, group, "ttl", u->ttl);
				}
				GHashTableIter fit;
				gpointer k, v;
				g_hash_table_iter_init(&fit, u->fields);
				while (g_hash_table_iter_next(&fit, &k, &v)) {
					char *key = g_strdup_printf("field.%s", (char *)k);
					g_key_file_set_string(kf, group, key, v);
					g_free(key);
				}
				g_free(group);
			}
		}
	}
	GError *err = NULL;
	char *dir = g_path_get_dirname(lv.path);
	g_mkdir_with_parents(dir, 0700);
	g_free(dir);
	if (!g_key_file_save_to_file(kf, lv.path, &err)) {
		fprintf(stderr, "c8-shell: cannot save %s: %s\n", lv.path,
			err->message);
		g_error_free(err);
	}
	g_key_file_free(kf);
	return G_SOURCE_REMOVE;
}

static void save_later(void) {
	if (lv.save_timer == 0) {
		lv.save_timer = g_timeout_add_seconds(SAVE_DELAY_S, save_now, NULL);
	}
}

void live_flush(void) {
	if (lv.save_timer) {
		g_source_remove(lv.save_timer);
		save_now(NULL);
	}
}

static void load(void) {
	GKeyFile *kf = g_key_file_new();
	if (!g_key_file_load_from_file(kf, lv.path, G_KEY_FILE_NONE, NULL)) {
		g_key_file_free(kf);
		return;
	}
	char **groups = g_key_file_get_groups(kf, NULL);
	for (char **g = groups; *g; g++) {
		if (strncmp(*g, "tile ", 5) == 0) {
			struct live *live = live_get(*g + 5);
			char *badge = g_key_file_get_string(kf, *g, "badge", NULL);
			if (badge && badge[0]) {
				live->badge = badge;
			} else {
				g_free(badge);
			}
			for (int kind = 0; kind < 2; kind++) {
				int n = g_key_file_get_integer(kf, *g, kind ? "pending" : "updates",
					NULL);
				int max = kind ? PENDING_MAX : QUEUE_MAX;
				for (int i = 0; i < n && i < max; i++) {
					char *ug = g_strdup_printf("%s %d %s", kind ? "pending" :
						"update", i, live->id);
					char *tag = g_key_file_get_string(kf, ug, "tag", NULL);
					struct live_update *u = update_new(tag ? tag : "");
					g_free(tag);
					u->expires = g_key_file_get_int64(kf, ug, "expires", NULL);
					u->starts = g_key_file_get_int64(kf, ug, "starts", NULL);
					u->ttl = g_key_file_get_int64(kf, ug, "ttl", NULL);
					char **keys = g_key_file_get_keys(kf, ug, NULL, NULL);
					for (char **k = keys; k && *k; k++) {
						if (strncmp(*k, "field.", 6) == 0) {
							g_hash_table_insert(u->fields, g_strdup(*k + 6),
								g_key_file_get_string(kf, ug, *k, NULL));
						}
					}
					g_strfreev(keys);
					g_free(ug);
					g_ptr_array_add(kind ? live->pending : live->updates, u);
				}
			}
		}
	}
	g_strfreev(groups);
	g_key_file_free(kf);
}

/* Changes, to Start */

static unsigned stamp = 1;

unsigned live_stamp(void) {
	return stamp;
}

static void changed(struct live *live) {
	stamp++;
	save_later();
	struct tile *tile = tile_find(live->id);
	if (tile) {
		tile->face_dirty = true;
		if (tile->slide >= tile_slide_count(tile)) {
			tile->slide = 0;
		}
		start_tile_changed(tile);
	}
}

static void apply(struct live *live, struct live_update *u);

/* When the next scheduled update starts or the next one expires (0: none) */
static int64_t next_event(void) {
	int64_t next = 0;
	GHashTableIter it;
	gpointer value;
	g_hash_table_iter_init(&it, lv.lives);
	while (g_hash_table_iter_next(&it, NULL, &value)) {
		struct live *live = value;
		for (guint i = 0; i < live->updates->len; i++) {
			int64_t e = ((struct live_update *)live->updates->pdata[i])->expires;
			if (e && (next == 0 || e < next)) {
				next = e;
			}
		}
		if (live->pending->len > 0) {
			int64_t st = ((struct live_update *)live->pending->pdata[0])->starts;
			if (next == 0 || st < next) {
				next = st;
			}
		}
	}
	return next;
}

static gboolean wake(gpointer data);

/* Wakes at the next event if the minute timer would be late for it */
static void reschedule(void) {
	int64_t next = next_event();
	/* Busy providers update all the time: a timer already set for this
	 * moment must be left to run, or it would never get to */
	if (lv.wake_timer && lv.wake_for == next) {
		return;
	}
	g_clear_handle_id(&lv.wake_timer, g_source_remove);
	if (next == 0) {
		return;
	}
	int64_t delta = next - time(NULL);
	if (delta < 60) {
		lv.wake_for = next;
		lv.wake_timer = g_timeout_add_seconds(delta < 1 ? 1 : (guint)delta,
			wake, NULL);
	}
}

/* Drops expired updates; true if any went */
static bool live_expire(void) {
	int64_t now = time(NULL);
	bool any = false;
	GHashTableIter it;
	gpointer value;
	g_hash_table_iter_init(&it, lv.lives);
	while (g_hash_table_iter_next(&it, NULL, &value)) {
		struct live *live = value;
		bool dropped = false;
		for (guint i = live->updates->len; i-- > 0; ) {
			struct live_update *u = live->updates->pdata[i];
			if (u->expires && u->expires <= now) {
				g_ptr_array_remove_index(live->updates, i);
				dropped = true;
			}
		}
		if (dropped) {
			changed(live);
			any = true;
		}
		/* Scheduled ones whose time came, soonest first: they take their
		 * place as if sent now */
		while (live->pending->len > 0 &&
				((struct live_update *)live->pending->pdata[0])->starts <= now) {
			struct live_update *u = g_ptr_array_steal_index(live->pending, 0);
			apply(live, u);
			any = true;
		}
	}
	reschedule();
	return any;
}

static gboolean wake(gpointer data) {
	lv.wake_timer = 0;
	live_expire();
	return G_SOURCE_REMOVE;
}

/* The bus */

/* Ids end up as start.ini and tiles.ini section names */
static bool id_ok(const char *id) {
	return id[0] && strlen(id) < 256 && strpbrk(id, "[]\n") == NULL &&
		g_utf8_validate(id, -1, NULL);
}

/* The update u would take the place of, if it says the same. One that
 * has loaded pictures doesn't count: sending it again is how a provider
 * has a picture file read again. */
static struct live_update *same_update(struct live *live,
		struct live_update *u) {
	struct live_update *old = NULL;
	if (u->tag[0] == '\0') {
		old = live->updates->len == 1 ? live->updates->pdata[0] : NULL;
	} else {
		for (guint i = 0; i < live->updates->len && old == NULL; i++) {
			struct live_update *o = live->updates->pdata[i];
			old = strcmp(o->tag, u->tag) == 0 ? o : NULL;
		}
	}
	if (old == NULL || strcmp(old->tag, u->tag) != 0 ||
			g_hash_table_size(old->images) > 0 ||
			g_hash_table_size(old->fields) != g_hash_table_size(u->fields)) {
		return NULL;
	}
	GHashTableIter it;
	gpointer key, value;
	g_hash_table_iter_init(&it, u->fields);
	while (g_hash_table_iter_next(&it, &key, &value)) {
		const char *had = g_hash_table_lookup(old->fields, key);
		if (had == NULL || strcmp(had, value) != 0) {
			return NULL;
		}
	}
	return old;
}

/* Puts an update on the tile, as sent now: untagged replaces all, tagged
 * joins the queue or takes its tag's place */
static void apply(struct live *live, struct live_update *u) {
	const char *tag = u->tag;
	u->expires = u->ttl > 0 ? time(NULL) + u->ttl : 0;
	u->starts = 0;
	/* Providers on a timer send what the tile already shows: then only
	 * how long it lasts is new, and Start needn't draw it again */
	struct live_update *same = same_update(live, u);
	if (same) {
		if (same->expires != u->expires) {
			same->expires = u->expires;
			save_later();
		}
		same->ttl = u->ttl;
		update_free(u);
		reschedule();
		return;
	}
	if (tag[0] == '\0') {
		g_ptr_array_set_size(live->updates, 0);
		g_ptr_array_add(live->updates, u);
	} else {
		bool replaced = false;
		for (guint i = 0; i < live->updates->len; i++) {
			struct live_update *old = live->updates->pdata[i];
			if (strcmp(old->tag, tag) == 0) {
				live->updates->pdata[i] = u;
				update_free(old);
				replaced = true;
				break;
			}
		}
		if (!replaced) {
			/* An untagged one has no place in a queue */
			for (guint i = live->updates->len; i-- > 0; ) {
				if (((struct live_update *)live->updates->pdata[i])->tag[0] == '\0') {
					g_ptr_array_remove_index(live->updates, i);
				}
			}
			if (live->updates->len >= QUEUE_MAX) {
				g_ptr_array_remove_index(live->updates, 0);
			}
			g_ptr_array_add(live->updates, u);
		}
	}
	changed(live);
	reschedule();
}

/* Waits its turn, among the others by when it starts; a later one with
 * the same tag takes the place of one still waiting */
static void schedule(struct live *live, struct live_update *u) {
	for (guint i = 0; u->tag[0] && i < live->pending->len; i++) {
		struct live_update *old = live->pending->pdata[i];
		if (strcmp(old->tag, u->tag) == 0) {
			g_ptr_array_remove_index(live->pending, i);
			break;
		}
	}
	if (live->pending->len >= PENDING_MAX) {
		g_ptr_array_remove_index(live->pending, live->pending->len - 1);
	}
	guint at = 0;
	while (at < live->pending->len &&
			((struct live_update *)live->pending->pdata[at])->starts <= u->starts) {
		at++;
	}
	g_ptr_array_insert(live->pending, at, u);
	save_later();
	reschedule();
}

static void do_update(const char *id, const char *tag, GVariant *content) {
	struct live *live = live_find(id);
	if (live == NULL && g_hash_table_size(lv.lives) >= LIVES_MAX) {
		return;
	}
	live = live_get(id);
	struct live_update *u = update_new(tag);
	GVariantIter iter;
	const char *key, *value;
	g_variant_iter_init(&iter, content);
	while (g_variant_iter_next(&iter, "{&s&s}", &key, &value)) {
		if (g_hash_table_size(u->fields) >= FIELDS_MAX) {
			break;
		}
		if (strcmp(key, "expires") == 0) {
			long secs = strtol(value, NULL, 10);
			u->ttl = secs > 0 ? secs : 0;
			continue;
		}
		if (strcmp(key, "starts") == 0) {
			long secs = strtol(value, NULL, 10);
			u->starts = secs > 0 ? time(NULL) + secs : 0;
			continue;
		}
		g_hash_table_insert(u->fields, g_strdup(key),
			g_utf8_make_valid(value, strnlen(value, VALUE_MAX)));
	}
	if (u->starts > 0) {
		schedule(live, u);
	} else {
		apply(live, u);
	}
}

static void emit(const char *signal, GVariant *params);

/* The old provider hears Restarting and exits; the new one is started
 * after it was sent, so it doesn't hear it */
void live_restart_provider(struct tile *tile) {
	if (tile->provider == NULL) {
		return;
	}
	emit("Restarting", g_variant_new("(s)", tile->id));
	g_dbus_connection_flush_sync(lv.bus, NULL, NULL);
	c8_shell_v1_launch(shell.proto, tile->provider);
}

/* Pin requests: an app asks for a tile of its own, which opens it at
 * something inside it (a place, a document). The user is asked first. */

#define PIN_REQUESTS_MAX 4

struct pin_request {
	char *id, *name, *exec, *icon, *image, *wide_image;
	bool has_color, label;
	uint32_t color;
	enum tile_size size;
	GDBusMethodInvocation *call;
};

static int pin_requests;

/* All of it shows in the question (notify.c's ASK_LINES) */
#define PIN_EXEC_MAX 400

static bool plain_text(const char *s, size_t max) {
	size_t n = strnlen(s, max + 1);
	if (n == 0 || n > max || !g_utf8_validate(s, n, NULL)) {
		return false;
	}
	for (size_t i = 0; i < n; i++) {
		if ((unsigned char)s[i] < 0x20 || s[i] == 0x7f) {
			return false;
		}
	}
	return true;
}

/* Text the user is asked about: what is read is all there is. Nothing
 * that doesn't show or that reorders what does (zero width and
 * direction marks, blank letters, odd spaces), and no run of spaces
 * pushing the rest out of sight. */
static bool honest_text(const char *s, size_t max) {
	if (!plain_text(s, max)) {
		return false;
	}
	int spaces = 0;
	for (const char *p = s; *p; p = g_utf8_next_char(p)) {
		gunichar c = g_utf8_get_char(p);
		GUnicodeType type = g_unichar_type(c);
		if (type == G_UNICODE_FORMAT || type == G_UNICODE_CONTROL ||
				type == G_UNICODE_UNASSIGNED || type == G_UNICODE_PRIVATE_USE ||
				type == G_UNICODE_SURROGATE || type == G_UNICODE_LINE_SEPARATOR ||
				type == G_UNICODE_PARAGRAPH_SEPARATOR ||
				(type == G_UNICODE_SPACE_SEPARATOR && c != ' ') ||
				c == 0x2800 || c == 0x3164 || c == 0x115f || c == 0x1160 ||
				c == 0xffa0 || g_unichar_iszerowidth(c)) {
			return false;
		}
		spaces = c == ' ' ? spaces + 1 : 0;
		if (spaces > 2) {
			return false;
		}
	}
	return true;
}

/* What a request says about the face; the command stays as pinned */
static void pin_style(struct tile *tile, struct pin_request *r) {
	set_str(&tile->name, r->name);
	if (r->icon[0]) {
		set_str(&tile->icon, r->icon);
	} else {
		free(tile->icon);
		tile->icon = NULL;
	}
	free(tile->image);
	free(tile->wide_image);
	tile->image = r->image[0] ? strdup(r->image) : NULL;
	tile->wide_image = r->wide_image[0] ? strdup(r->wide_image) : NULL;
	tile->has_color = r->has_color;
	tile->color = r->color;
	tile->size = r->size;
	tile->label = r->label;
	tile_restyle(tile);
}

static void pin_request_free(struct pin_request *r) {
	g_free(r->id);
	g_free(r->name);
	g_free(r->exec);
	g_free(r->icon);
	g_free(r->image);
	g_free(r->wide_image);
	g_free(r);
}

static void pin_answered(bool yes, void *data) {
	struct pin_request *r = data;
	bool pinned = false;
	struct tile *tile = tile_find(r->id);
	if (yes && tile && tile->secondary) {
		/* A new command for a tile already there, now agreed to */
		set_str(&tile->exec, r->exec);
		pin_style(tile, r);
		start_pinned(tile);
		pinned = true;
	} else if (yes && tile == NULL) {
		tile = tile_pin_secondary(r->id, r->name, r->exec, r->icon,
			r->has_color, r->color, r->size);
		pin_style(tile, r);
		start_pinned(tile);
		pinned = true;
	}
	g_dbus_method_invocation_return_value(r->call,
		g_variant_new("(b)", pinned));
	pin_requests--;
	pin_request_free(r);
}

static bool picture_ok(const char *s) {
	return s == NULL || s[0] == '\0' || (s[0] == '/' && plain_text(s, 512));
}

static void request_pin(const char *id, GVariant *options,
		GDBusMethodInvocation *call) {
	const char *name = NULL, *exec = NULL, *icon = NULL, *color = NULL,
		*size = NULL, *image = NULL, *wide_image = NULL, *label = NULL;
	g_variant_lookup(options, "image", "&s", &image);
	g_variant_lookup(options, "wide_image", "&s", &wide_image);
	g_variant_lookup(options, "label", "&s", &label);
	g_variant_lookup(options, "name", "&s", &name);
	g_variant_lookup(options, "exec", "&s", &exec);
	g_variant_lookup(options, "icon", "&s", &icon);
	g_variant_lookup(options, "color", "&s", &color);
	g_variant_lookup(options, "size", "&s", &size);
	struct tile *had = tile_find(id);
	if (had && (!had->secondary || name == NULL || exec == NULL)) {
		/* Already there: nothing to ask */
		g_dbus_method_invocation_return_value(call, g_variant_new("(b)", TRUE));
		return;
	}
	if (!id_ok(id) || !plain_text(id, 200) || name == NULL ||
			!honest_text(name, 64) || exec == NULL ||
			!honest_text(exec, PIN_EXEC_MAX) || exec[0] == '@' ||
			exec[0] == ' ' || (icon && icon[0] && !plain_text(icon, 512)) ||
			!picture_ok(image) || !picture_ok(wide_image)) {
		g_dbus_method_invocation_return_error(call, G_DBUS_ERROR,
			G_DBUS_ERROR_INVALID_ARGS, "A pin request needs a name (up to "
			"64 characters) and an exec line (up to 400 bytes), each on "
			"one line of visible characters without runs of spaces, the "
			"exec not starting with @; pictures are absolute paths");
		return;
	}
	if (pin_requests >= PIN_REQUESTS_MAX) {
		g_dbus_method_invocation_return_error(call, G_DBUS_ERROR,
			G_DBUS_ERROR_LIMITS_EXCEEDED, "Too many pin requests waiting");
		return;
	}
	struct pin_request *r = g_new0(struct pin_request, 1);
	r->id = g_strdup(id);
	r->name = g_strdup(name);
	r->exec = g_strdup(exec);
	r->icon = g_strdup(icon && icon[0] ? icon : "");
	r->image = g_strdup(image ? image : "");
	r->wide_image = g_strdup(wide_image ? wide_image : "");
	r->label = label == NULL || strcmp(label, "false") != 0;
	r->call = call;
	r->has_color = color && color[0] && c8ui_parse_color(color, &r->color);
	r->size = TILE_MEDIUM;
	for (int i = 0; size && i < 4; i++) {
		if (strcmp(size, size_names[i]) == 0) {
			r->size = i;
		}
	}
	if (had && had->exec && strcmp(had->exec, exec) == 0) {
		/* An app's own tile, the same command: only its face changes,
		 * which needs no asking */
		pin_style(had, r);
		start_pinned(had);
		g_dbus_method_invocation_return_value(call, g_variant_new("(b)", TRUE));
		pin_request_free(r);
		return;
	}
	pin_requests++;
	/* Says what it will run, so a request can't pass for something else */
	char *body = g_strdup_printf("Opens: %s", exec);
	char *summary = g_strdup_printf("Pin %s to Start?", name);
	notify_ask(summary, body, r->icon, "Pin to Start", "Not now",
		pin_answered, r);
	g_free(summary);
	g_free(body);
}

static void method_call(GDBusConnection *bus, const char *sender,
		const char *path, const char *iface, const char *method,
		GVariant *params, GDBusMethodInvocation *call, gpointer data) {
	const char *id = NULL, *arg = NULL;
	if (strcmp(method, "Update") == 0) {
		GVariant *content;
		g_variant_get(params, "(&s&s@a{ss})", &id, &arg, &content);
		if (id_ok(id)) {
			do_update(id, arg, content);
		}
		g_variant_unref(content);
	} else if (strcmp(method, "Remove") == 0) {
		g_variant_get(params, "(&s&s)", &id, &arg);
		struct live *live = live_find(id);
		for (guint i = 0; live && i < live->pending->len; i++) {
			if (strcmp(((struct live_update *)live->pending->pdata[i])->tag,
					arg) == 0) {
				g_ptr_array_remove_index(live->pending, i);
				save_later();
				reschedule();
				break;
			}
		}
		for (guint i = 0; live && i < live->updates->len; i++) {
			if (strcmp(((struct live_update *)live->updates->pdata[i])->tag,
					arg) == 0) {
				g_ptr_array_remove_index(live->updates, i);
				changed(live);
				break;
			}
		}
	} else if (strcmp(method, "Clear") == 0) {
		g_variant_get(params, "(&s)", &id);
		struct live *live = live_find(id);
		if (live) {
			g_ptr_array_set_size(live->updates, 0);
			g_ptr_array_set_size(live->pending, 0);
			g_clear_pointer(&live->badge, g_free);
			changed(live);
			reschedule();
		}
	} else if (strcmp(method, "SetBadge") == 0) {
		g_variant_get(params, "(&s&s)", &id, &arg);
		if (id_ok(id) && (live_find(id) ||
				g_hash_table_size(lv.lives) < LIVES_MAX)) {
			struct live *live = live_get(id);
			g_free(live->badge);
			live->badge = arg[0] ? g_utf8_make_valid(arg, strnlen(arg, 32)) :
				NULL;
			changed(live);
		}
	} else if (strcmp(method, "Restart") == 0) {
		g_variant_get(params, "(&s)", &id);
		if (id[0] == '\0') {
			struct group *group;
			struct tile *tile;
			for_each_tile(group, tile) {
				live_restart_provider(tile);
			}
		} else {
			struct tile *tile = tile_find(id);
			if (tile == NULL || tile->provider == NULL) {
				g_dbus_method_invocation_return_error(call,
					G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
					tile ? "Tile '%s' has no provider" :
					"Tile '%s' isn't pinned", id);
				return;
			}
			live_restart_provider(tile);
		}
	} else if (strcmp(method, "RequestPin") == 0) {
		GVariant *options;
		g_variant_get(params, "(&s@a{ss})", &id, &options);
		request_pin(id, options, call);
		g_variant_unref(options);
		return; // answered when the user has
	} else if (strcmp(method, "Unpin") == 0) {
		g_variant_get(params, "(&s)", &id);
		struct tile *tile = tile_find(id);
		/* Only what an app pinned for itself: the user's own tiles are
		 * theirs to take off */
		if (tile && tile->secondary) {
			start_unpin(tile);
		}
	} else if (strcmp(method, "GetTile") == 0) {
		g_variant_get(params, "(&s)", &id);
		struct tile *tile = tile_find(id);
		g_dbus_method_invocation_return_value(call, g_variant_new("(bs)",
			tile != NULL, tile ? size_names[tile->size] : ""));
		return;
	}
	g_dbus_method_invocation_return_value(call, NULL);
}

static GVariant *get_property(GDBusConnection *bus, const char *sender,
		const char *path, const char *iface, const char *prop, GError **err,
		gpointer data) {
	if (strcmp(prop, "StartVisible") == 0) {
		return g_variant_new_boolean(shell.start_visible);
	}
	return NULL;
}

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

static void emit(const char *signal, GVariant *params) {
	if (lv.bus && lv.object_id) {
		g_dbus_connection_emit_signal(lv.bus, NULL, BUS_PATH, BUS_IFACE,
			signal, params, NULL);
	} else {
		g_variant_unref(g_variant_ref_sink(params));
	}
}

void live_tiles_changed(void) {
	if (lv.announced == NULL) {
		return;
	}
	/* Unpinned since */
	GHashTableIter it;
	gpointer key, value;
	g_hash_table_iter_init(&it, lv.announced);
	while (g_hash_table_iter_next(&it, &key, &value)) {
		if (tile_find(key) == NULL) {
			emit("TileChanged", g_variant_new("(sbs)", (char *)key, FALSE, ""));
			g_hash_table_iter_remove(&it);
		}
	}
	/* Pinned or resized */
	struct group *group;
	struct tile *tile;
	for_each_tile(group, tile) {
		const char *size = size_names[tile->size];
		const char *was = g_hash_table_lookup(lv.announced, tile->id);
		if (was == NULL || strcmp(was, size) != 0) {
			g_hash_table_insert(lv.announced, g_strdup(tile->id),
				g_strdup(size));
			emit("TileChanged", g_variant_new("(sbs)", tile->id, TRUE, size));
		}
	}
}

void live_start_visible(void) {
	if (!shell.start_visible) {
		live_flush();
	}
	if (lv.bus == NULL || lv.object_id == 0) {
		return;
	}
	GVariantBuilder changed_props;
	g_variant_builder_init(&changed_props, G_VARIANT_TYPE("a{sv}"));
	g_variant_builder_add(&changed_props, "{sv}", "StartVisible",
		g_variant_new_boolean(shell.start_visible));
	g_dbus_connection_emit_signal(lv.bus, NULL, BUS_PATH,
		"org.freedesktop.DBus.Properties", "PropertiesChanged",
		g_variant_new("(sa{sv}as)", BUS_IFACE, &changed_props, NULL), NULL);
}

void live_activated(struct tile *tile) {
	emit("Activated", g_variant_new("(s)", tile->id));
}

static void bus_acquired(GDBusConnection *bus, const char *name,
		gpointer data) {
	lv.bus = bus;
	GError *err = NULL;
	lv.object_id = g_dbus_connection_register_object(bus, BUS_PATH,
		(GDBusInterfaceInfo *)&org_cont8nuum_tiles1_interface, &vtable, NULL,
		NULL, &err);
	if (lv.object_id == 0) {
		fprintf(stderr, "c8-shell: cannot serve live tiles: %s\n",
			err->message);
		g_error_free(err);
	}
}

static void name_acquired(GDBusConnection *bus, const char *name,
		gpointer data) {
	/* A respawned shell finds its providers still running. A fresh one
	 * (a new login) may find the last session's: they only hear
	 * Restarting from the name's owner, so it's sent now, before the new
	 * ones start, or they'd pile up and all tick while Start shows */
	if (!shell.respawned && !lv.launched) {
		lv.launched = true;
		tiles_launch_providers();
	}
}

static void name_lost(GDBusConnection *bus, const char *name, gpointer data) {
	/* Another shell took over (a second nested session, say) */
	fprintf(stderr, "c8-shell: %s is someone else's now; live tiles from "
		"the bus go there\n", name);
}

static gboolean expire_timer(gpointer data) {
	live_expire();
	return G_SOURCE_CONTINUE;
}

void live_init(void) {
	lv.lives = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, live_free);
	lv.announced = g_hash_table_new_full(g_str_hash, g_str_equal, g_free,
		g_free);
	lv.path = g_build_filename(g_get_user_cache_dir(), "cont8nuum",
		"tiles.ini", NULL);
	load();
	/* The newest shell wins: it's the one on screen */
	g_bus_own_name(G_BUS_TYPE_SESSION, BUS_NAME,
		G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT |
		G_BUS_NAME_OWNER_FLAGS_REPLACE, bus_acquired, name_acquired, name_lost,
		NULL, NULL);
	live_expire();
	g_timeout_add_seconds(60, expire_timer, NULL);
}
