/*
 * The notification area: apps' tray icons, over the StatusNotifierItem
 * protocol (the org.kde.* names are only historical; it is plain D-Bus
 * and nothing of KDE is needed). We own the watcher, so we are the host;
 * each item is a bus name and path that we read icon, title and status
 * from. Menus are com.canonical.dbusmenu, shown as a menu in a flyout.
 * Drawn by panels.c under the charms clock.
 */
#define _GNU_SOURCE
#include <math.h>
#include <string.h>
#include <gio/gio.h>
#include <gio/gdesktopappinfo.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include "shell.h"
#include "pixels.h"

#define WATCHER_NAME "org.kde.StatusNotifierWatcher"
#define WATCHER_PATH "/StatusNotifierWatcher"
#define ITEM_IFACE "org.kde.StatusNotifierItem"
#define MENU_IFACE "com.canonical.dbusmenu"
#define DEFAULT_PATH "/StatusNotifierItem"

struct tray_item {
	char *key; // "bus/path", what the watcher lists
	char *bus, *path;
	guint watch, signals;
	char *id, *title, *status, *icon_name, *menu;
	char *label; // what to call it when it has no title
	bool is_menu; // a click opens the menu
	struct c8ui_icon *icon;
	cairo_surface_t *pixmap;
	bool fetching, again;
	GCancellable *gone; // cancelled when the item is freed
};

static struct {
	GDBusConnection *bus;
	GDBusNodeInfo *info;
	guint owner;
	GPtrArray *items; // struct tray_item
	tray_fn changed;
	void *changed_data;
} t;

static const char introspection[] =
	"<node><interface name='" WATCHER_NAME "'>"
	"<method name='RegisterStatusNotifierItem'>"
	"<arg type='s' direction='in'/></method>"
	"<method name='RegisterStatusNotifierHost'>"
	"<arg type='s' direction='in'/></method>"
	"<property name='RegisteredStatusNotifierItems' type='as' access='read'/>"
	"<property name='IsStatusNotifierHostRegistered' type='b' access='read'/>"
	"<property name='ProtocolVersion' type='i' access='read'/>"
	"<signal name='StatusNotifierItemRegistered'>"
	"<arg type='s'/></signal>"
	"<signal name='StatusNotifierItemUnregistered'>"
	"<arg type='s'/></signal>"
	"<signal name='StatusNotifierHostRegistered'/>"
	"<signal name='StatusNotifierHostUnregistered'/>"
	"</interface></node>";

static void notify_changed(void) {
	if (t.changed) {
		t.changed(t.changed_data);
	}
}

void tray_listen(tray_fn fn, void *data) {
	t.changed = fn;
	t.changed_data = data;
}

/* Items */

static void item_free(struct tray_item *it) {
	/* A reply still on its way must not find it */
	if (it->gone) {
		g_cancellable_cancel(it->gone);
		g_object_unref(it->gone);
	}
	if (it->watch) {
		g_bus_unwatch_name(it->watch);
	}
	if (it->signals) {
		g_dbus_connection_signal_unsubscribe(t.bus, it->signals);
	}
	if (it->icon) {
		c8ui_icon_destroy(it->icon);
	}
	if (it->pixmap) {
		cairo_surface_destroy(it->pixmap);
	}
	g_free(it->key);
	g_free(it->bus);
	g_free(it->path);
	g_free(it->id);
	g_free(it->title);
	g_free(it->status);
	g_free(it->icon_name);
	g_free(it->menu);
	g_free(it->label);
	g_free(it);
}

static struct tray_item *find(const char *key) {
	for (guint i = 0; i < t.items->len; i++) {
		struct tray_item *it = g_ptr_array_index(t.items, i);
		if (strcmp(it->key, key) == 0) {
			return it;
		}
	}
	return NULL;
}

/* ARGB32 in network order, the biggest at least `want` px or else the
 * biggest there is, as a premultiplied cairo image */
static cairo_surface_t *pixmap_pick(GVariant *list, int want) {
	GVariantIter iter;
	int w, h, best_w = 0, best_h = 0;
	GVariant *bytes, *best = NULL;
	g_variant_iter_init(&iter, list);
	while (g_variant_iter_next(&iter, "(ii@ay)", &w, &h, &bytes)) {
		bool ok = w > 0 && h > 0 && w <= 512 && h <= 512 &&
			g_variant_get_size(bytes) >= (gsize)w * h * 4;
		bool better = best == NULL ||
			(best_w < want ? w > best_w : (w >= want && w < best_w));
		if (ok && better) {
			if (best) {
				g_variant_unref(best);
			}
			best = bytes;
			best_w = w;
			best_h = h;
		} else {
			g_variant_unref(bytes);
		}
	}
	if (!best) {
		return NULL;
	}
	cairo_surface_t *img = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
		best_w, best_h);
	const guint8 *src = g_variant_get_data(best);
	uint32_t *dst = (uint32_t *)cairo_image_surface_get_data(img);
	int stride = cairo_image_surface_get_stride(img) / 4;
	for (int y = 0; y < best_h; y++) {
		for (int x = 0; x < best_w; x++) {
			const guint8 *px = src + ((gsize)y * best_w + x) * 4;
			uint32_t a = px[0], r = px[1] * a / 255, g = px[2] * a / 255,
				b = px[3] * a / 255;
			dst[y * stride + x] = a << 24 | r << 16 | g << 8 | b;
		}
	}
	cairo_surface_mark_dirty(img);
	g_variant_unref(best);
	return img;
}

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

static void fetch(struct tray_item *it) {
	if (it->fetching) {
		it->again = true;
		return;
	}
	it->fetching = true;
	g_dbus_connection_call(t.bus, it->bus, it->path,
		"org.freedesktop.DBus.Properties", "GetAll",
		g_variant_new("(s)", ITEM_IFACE), G_VARIANT_TYPE("(a{sv})"),
		G_DBUS_CALL_FLAGS_NONE, 2000, it->gone, props_got, it);
}

static const char *str_prop(GVariant *dict, const char *name) {
	const char *s = NULL;
	GVariant *v = g_variant_lookup_value(dict, name, G_VARIANT_TYPE_STRING);
	if (v) {
		s = g_variant_get_string(v, NULL);
		/* The dict owns the string: keep it alive by the caller's copy */
		g_variant_unref(v);
	}
	return s;
}

static void replace(char **dst, const char *s) {
	g_free(*dst);
	*dst = g_strdup(s ? s : "");
}

/* An image file as a premultiplied cairo image, or NULL */
static cairo_surface_t *file_image(const char *path) {
	return image_from_pixbuf(gdk_pixbuf_new_from_file_at_size(path, 128, 128,
		NULL));
}

/* The icon an item names as a file: an absolute path, or a name in the
 * folder it gave (Chromium and Electron write theirs to a temp folder) */
static cairo_surface_t *named_file(const char *dir, const char *name) {
	if (!name[0]) {
		return NULL;
	}
	if (name[0] == '/') {
		return file_image(name);
	}
	if (!dir || !dir[0]) {
		return NULL;
	}
	static const char *const exts[] = { "", ".png", ".svg" };
	for (int i = 0; i < 3; i++) {
		char *path = g_strdup_printf("%s/%s%s", dir, name, exts[i]);
		cairo_surface_t *img = g_file_test(path, G_FILE_TEST_IS_REGULAR)
			? file_image(path) : NULL;
		g_free(path);
		if (img) {
			return img;
		}
	}
	return NULL;
}

/* "discord_status_icon_1" is Discord: the app's desktop entry name if
 * there is one, else the id without the toolkit's suffix */
static char *friendly(const char *id) {
	char *base = g_strdup(id);
	char *suffix = strstr(base, "_status_icon");
	if (!suffix) {
		suffix = strstr(base, "-status-icon");
	}
	if (suffix) {
		*suffix = '\0';
	}
	char *lower = g_ascii_strdown(base, -1);
	const char *tries[] = { base, lower };
	for (int i = 0; i < 2; i++) {
		char *desktop = g_strdup_printf("%s.desktop", tries[i]);
		GDesktopAppInfo *info = g_desktop_app_info_new(desktop);
		g_free(desktop);
		if (info) {
			char *name = g_strdup(g_app_info_get_display_name(
				G_APP_INFO(info)));
			g_object_unref(info);
			g_free(base);
			g_free(lower);
			return name;
		}
	}
	g_free(lower);
	return base;
}

static void props_got(GObject *src, GAsyncResult *res, gpointer data) {
	struct tray_item *it = data;
	GError *err = NULL;
	GVariant *ret = g_dbus_connection_call_finish(G_DBUS_CONNECTION(src),
		res, &err);
	/* The item may have gone while we asked: then it's freed, and
	 * cancelled says so without looking at it */
	if (g_error_matches(err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
		g_clear_error(&err);
		return;
	}
	it->fetching = false;
	if (!ret) {
		g_clear_error(&err);
		return;
	}
	GVariant *dict = g_variant_get_child_value(ret, 0);
	replace(&it->id, str_prop(dict, "Id"));
	replace(&it->title, str_prop(dict, "Title"));
	replace(&it->status, str_prop(dict, "Status"));
	const char *name = str_prop(dict, "IconName");
	const char *att = str_prop(dict, "AttentionIconName");
	if (it->status && strcmp(it->status, "NeedsAttention") == 0 &&
			att && att[0]) {
		name = att;
	}
	replace(&it->icon_name, name);
	GVariant *menu = g_variant_lookup_value(dict, "Menu",
		G_VARIANT_TYPE_OBJECT_PATH);
	replace(&it->menu, menu ? g_variant_get_string(menu, NULL) : "");
	if (menu) {
		g_variant_unref(menu);
	}
	GVariant *im = g_variant_lookup_value(dict, "ItemIsMenu",
		G_VARIANT_TYPE_BOOLEAN);
	it->is_menu = im && g_variant_get_boolean(im);
	if (im) {
		g_variant_unref(im);
	}
	if (it->pixmap) {
		cairo_surface_destroy(it->pixmap);
		it->pixmap = NULL;
	}
	/* A file the app gave us wins, then the theme's icon, then pixels */
	const char *theme_dir = str_prop(dict, "IconThemePath");
	it->pixmap = named_file(theme_dir, it->icon_name);
	if (!it->pixmap) {
		GVariant *pm = g_variant_lookup_value(dict, "IconPixmap",
			G_VARIANT_TYPE("a(iiay)"));
		if (pm) {
			it->pixmap = pixmap_pick(pm, 32);
			g_variant_unref(pm);
		}
	}
	g_variant_unref(dict);
	g_variant_unref(ret);
	if (it->icon) {
		c8ui_icon_destroy(it->icon);
		it->icon = NULL;
	}
	if (!it->pixmap && it->icon_name[0] && it->icon_name[0] != '/') {
		it->icon = c8ui_icon_load(NULL, it->icon_name);
	}
	if (!it->label || !it->label[0]) {
		g_free(it->label);
		it->label = friendly(it->id);
	}
	notify_changed();
	if (it->again) {
		it->again = false;
		fetch(it);
	}
}

static void item_signal(GDBusConnection *c, const char *sender,
		const char *path, const char *iface, const char *name,
		GVariant *params, gpointer data) {
	fetch(data);
}

static void emit(const char *name, const char *key) {
	g_dbus_connection_emit_signal(t.bus, NULL, WATCHER_PATH, WATCHER_NAME,
		name, key ? g_variant_new("(s)", key) : NULL, NULL);
}

static void item_vanished(GDBusConnection *c, const char *name,
		gpointer data) {
	struct tray_item *it = data;
	char *key = g_strdup(it->key);
	/* The listener must not see it any more, nor use it after this */
	g_ptr_array_remove(t.items, it);
	emit("StatusNotifierItemUnregistered", key);
	g_free(key);
	notify_changed();
	item_free(it);
}

static void item_add(const char *bus, const char *path) {
	char *key = g_strdup_printf("%s%s", bus, path);
	if (find(key)) {
		g_free(key);
		return;
	}
	struct tray_item *it = g_new0(struct tray_item, 1);
	it->key = key;
	it->gone = g_cancellable_new();
	it->bus = g_strdup(bus);
	it->path = g_strdup(path);
	it->id = g_strdup("");
	it->title = g_strdup("");
	it->status = g_strdup("Passive"); // shown once we know better
	it->icon_name = g_strdup("");
	it->menu = g_strdup("");
	g_ptr_array_add(t.items, it);
	it->signals = g_dbus_connection_signal_subscribe(t.bus, bus, ITEM_IFACE,
		NULL, path, NULL, G_DBUS_SIGNAL_FLAGS_NONE, item_signal, it, NULL);
	it->watch = g_bus_watch_name_on_connection(t.bus, bus,
		G_BUS_NAME_WATCHER_FLAGS_NONE, NULL, item_vanished, it, NULL);
	emit("StatusNotifierItemRegistered", key);
	fetch(it);
}

/* Watcher */

static void watcher_call(GDBusConnection *c, const char *sender,
		const char *path, const char *iface, const char *method,
		GVariant *params, GDBusMethodInvocation *call, gpointer data) {
	if (strcmp(method, "RegisterStatusNotifierItem") == 0) {
		const char *service;
		g_variant_get(params, "(&s)", &service);
		char *bus, *obj;
		if (service[0] == '/') {
			bus = g_strdup(sender);
			obj = g_strdup(service);
		} else {
			const char *slash = strchr(service, '/');
			bus = slash ? g_strndup(service, slash - service)
				: g_strdup(service);
			obj = g_strdup(slash ? slash : DEFAULT_PATH);
		}
		item_add(bus, obj);
		g_free(bus);
		g_free(obj);
	}
	/* We are the one host, so another registering changes nothing */
	g_dbus_method_invocation_return_value(call, NULL);
}

static GVariant *watcher_get(GDBusConnection *c, const char *sender,
		const char *path, const char *iface, const char *prop,
		GError **err, gpointer data) {
	if (strcmp(prop, "RegisteredStatusNotifierItems") == 0) {
		GVariantBuilder b;
		g_variant_builder_init(&b, G_VARIANT_TYPE("as"));
		for (guint i = 0; i < t.items->len; i++) {
			g_variant_builder_add(&b, "s",
				((struct tray_item *)g_ptr_array_index(t.items, i))->key);
		}
		return g_variant_builder_end(&b);
	}
	if (strcmp(prop, "IsStatusNotifierHostRegistered") == 0) {
		return g_variant_new_boolean(TRUE);
	}
	return g_variant_new_int32(0);
}

static const GDBusInterfaceVTable watcher_vtable = {
	.method_call = watcher_call,
	.get_property = watcher_get,
};

static void bus_acquired(GDBusConnection *bus, const char *name,
		gpointer data) {
	t.bus = bus;
	GError *err = NULL;
	t.info = g_dbus_node_info_new_for_xml(introspection, &err);
	if (!t.info || !g_dbus_connection_register_object(bus, WATCHER_PATH,
			t.info->interfaces[0], &watcher_vtable, NULL, NULL, &err)) {
		g_warning("tray: %s", err ? err->message : "no interface");
		g_clear_error(&err);
	}
}

static void name_acquired(GDBusConnection *bus, const char *name,
		gpointer data) {
	emit("StatusNotifierHostRegistered", NULL);
}

static void name_lost(GDBusConnection *bus, const char *name,
		gpointer data) {
	g_warning("tray: %s is taken, no tray icons", WATCHER_NAME);
}

void tray_init(void) {
	t.items = g_ptr_array_new();
	t.owner = g_bus_own_name(G_BUS_TYPE_SESSION, WATCHER_NAME,
		G_BUS_NAME_OWNER_FLAGS_NONE, bus_acquired, name_acquired, name_lost,
		NULL, NULL);
}

/* What the panel shows: the ones that aren't passive */

static bool shown(struct tray_item *it) {
	return strcmp(it->status, "Passive") != 0;
}

int tray_count(void) {
	int n = 0;
	for (guint i = 0; t.items && i < t.items->len; i++) {
		n += shown(g_ptr_array_index(t.items, i));
	}
	return n;
}

struct tray_item *tray_nth(int n) {
	for (guint i = 0; i < t.items->len; i++) {
		struct tray_item *it = g_ptr_array_index(t.items, i);
		if (shown(it) && n-- == 0) {
			return it;
		}
	}
	return NULL;
}

const char *tray_title(struct tray_item *it) {
	if (it->title[0]) {
		return c8_stealth_show(it->title);
	}
	return c8_stealth_show(it->label ? it->label : it->id);
}

void tray_draw(struct tray_item *it, cairo_t *cr, double cx, double cy,
		double size) {
	if (it->icon) {
		c8ui_icon_draw_fit(cr, it->icon, cx, cy, size);
	} else if (it->pixmap) {
		c8ui_draw_surface_fit(cr, it->pixmap, cx - size / 2, cy - size / 2,
			size, size, 0);
	} else {
		/* Nothing to show yet: a plain dot */
		cairo_set_source_rgba(cr, 1, 1, 1, 0.5);
		cairo_arc(cr, cx, cy, size / 5, 0, 2 * M_PI);
		cairo_fill(cr);
	}
}

/* Clicks */

static void call_item(struct tray_item *it, const char *method, int x,
		int y) {
	g_dbus_connection_call(t.bus, it->bus, it->path, ITEM_IFACE, method,
		g_variant_new("(ii)", x, y), NULL, G_DBUS_CALL_FLAGS_NONE, 2000,
		NULL, NULL, NULL);
}

struct menu_node {
	int id;
	char *label;
	bool sep, enabled, visible, submenu, checked;
	enum c8ui_menu_kind kind;
	GPtrArray *kids;
};

static void node_free(struct menu_node *n) {
	for (guint i = 0; n->kids && i < n->kids->len; i++) {
		node_free(g_ptr_array_index(n->kids, i));
	}
	if (n->kids) {
		g_ptr_array_free(n->kids, TRUE);
	}
	g_free(n->label);
	g_free(n);
}

/* "_File" is File; "__" is a real underscore */
static char *strip_mnemonic(const char *s) {
	GString *out = g_string_new(NULL);
	for (; *s; s++) {
		if (*s == '_') {
			if (s[1] == '_') {
				g_string_append_c(out, '_');
				s++;
			}
			continue;
		}
		g_string_append_c(out, *s);
	}
	return g_string_free(out, FALSE);
}

static struct menu_node *node_parse(GVariant *layout) {
	int id;
	GVariant *props, *kids;
	/* A child is whatever the app put in the variant */
	if (!g_variant_is_of_type(layout, G_VARIANT_TYPE("(ia{sv}av)"))) {
		return NULL;
	}
	g_variant_get(layout, "(i@a{sv}@av)", &id, &props, &kids);
	struct menu_node *n = g_new0(struct menu_node, 1);
	n->id = id;
	n->enabled = n->visible = true;
	n->kids = g_ptr_array_new();
	const char *s;
	if (g_variant_lookup(props, "label", "&s", &s)) {
		n->label = strip_mnemonic(s);
	} else {
		n->label = g_strdup("");
	}
	if (g_variant_lookup(props, "type", "&s", &s) &&
			strcmp(s, "separator") == 0) {
		n->sep = true;
	}
	gboolean b;
	if (g_variant_lookup(props, "enabled", "b", &b)) {
		n->enabled = b;
	}
	if (g_variant_lookup(props, "visible", "b", &b)) {
		n->visible = b;
	}
	if (g_variant_lookup(props, "toggle-type", "&s", &s)) {
		n->kind = strcmp(s, "radio") == 0 ? C8UI_MENU_RADIO
			: strcmp(s, "checkmark") == 0 ? C8UI_MENU_CHECK
			: C8UI_MENU_COMMAND;
	}
	int state;
	if (g_variant_lookup(props, "toggle-state", "i", &state)) {
		n->checked = state == 1;
	}
	if (g_variant_lookup(props, "children-display", "&s", &s)) {
		n->submenu = strcmp(s, "submenu") == 0;
	}
	GVariantIter iter;
	GVariant *child;
	g_variant_iter_init(&iter, kids);
	while ((child = g_variant_iter_next_value(&iter))) {
		/* each child is a variant holding a layout */
		GVariant *inner = g_variant_get_variant(child);
		struct menu_node *kid = node_parse(inner);
		if (kid) {
			g_ptr_array_add(n->kids, kid);
		}
		g_variant_unref(inner);
		g_variant_unref(child);
	}
	g_variant_unref(props);
	g_variant_unref(kids);
	return n;
}

/* The menu's items (visible ones) as c8ui wants them; free with
 * items_free */
static struct c8ui_menu_item *items_build(struct menu_node *parent,
		int *count) {
	struct c8ui_menu_item *items = g_new0(struct c8ui_menu_item,
		parent->kids->len + 1);
	int n = 0;
	for (guint i = 0; i < parent->kids->len; i++) {
		struct menu_node *k = g_ptr_array_index(parent->kids, i);
		if (!k->visible) {
			continue;
		}
		struct c8ui_menu_item *m = &items[n++];
		if (k->sep) {
			m->kind = C8UI_MENU_SEPARATOR;
			continue;
		}
		m->label = k->label;
		m->id = k->id;
		m->kind = k->kind;
		m->checked = k->checked;
		m->disabled = !k->enabled;
		if (k->kids->len > 0) {
			m->submenu = items_build(k, &m->submenu_count);
		}
	}
	/* A separator first or last, or two in a row, is only noise */
	*count = n;
	return items;
}

static void items_free(struct c8ui_menu_item *items, int count) {
	for (int i = 0; i < count; i++) {
		if (items[i].submenu) {
			items_free((struct c8ui_menu_item *)items[i].submenu,
				items[i].submenu_count);
		}
	}
	g_free(items);
}

struct menu_page {
	struct tray_item *it;
	char *bus, *path; // where the events go: the item may be gone
	char *title;
	struct menu_node *root;
	struct c8ui_menu_item *items;
	int count;
	bool shown;
	guint idle;
};

static void page_free(struct menu_page *mp) {
	if (mp->idle) {
		g_source_remove(mp->idle);
	}
	items_free(mp->items, mp->count);
	node_free(mp->root);
	g_free(mp->bus);
	g_free(mp->path);
	g_free(mp->title);
	g_free(mp);
}

static void menu_chosen(int choice, void *data) {
	struct menu_page *mp = data;
	if (choice >= 0) {
		g_dbus_connection_call(t.bus, mp->bus, mp->path, MENU_IFACE,
			"Event", g_variant_new("(isvu)", choice, "clicked",
				g_variant_new_int32(0), (guint32)(g_get_real_time() / 1000000)),
			NULL, G_DBUS_CALL_FLAGS_NONE, 2000, NULL, NULL, NULL);
	}
	panels_close();
}

static gboolean menu_open_idle(gpointer data) {
	struct c8ui_widget *w = data;
	struct menu_page *mp = w->user_data;
	mp->idle = 0;
	if (mp->count > 0) {
		c8ui_menu_show_items(w->root, 24, 110, false, mp->items, mp->count,
			menu_chosen, mp);
	}
	return G_SOURCE_REMOVE;
}

/* The flyout under the menu: the app's name over the menu, which opens
 * once the surface has a size (the first draw) */
static void page_draw(struct c8ui_widget *w, cairo_t *cr, void *data) {
	struct menu_page *mp = data;
	cairo_set_source_rgb(cr, 1, 1, 1);
	c8ui_text_draw(cr, c8ui_widget_font(w),
		(struct c8ui_font){ 26, C8UI_WEIGHT_LIGHT }, mp->title,
		w->rect.x + 24, w->rect.y + 40, w->rect.width - 48, 0);
	if (!mp->shown) {
		mp->shown = true;
		mp->idle = g_idle_add(menu_open_idle, w);
	}
}

static void page_destroyed(struct c8ui_widget *w, void *data) {
	page_free(w->user_data);
}

static void layout_got(GObject *src, GAsyncResult *res, gpointer data) {
	struct menu_page *mp = data;
	GError *err = NULL;
	GVariant *ret = g_dbus_connection_call_finish(G_DBUS_CONNECTION(src),
		res, &err);
	if (!ret) {
		g_clear_error(&err);
		page_free(mp);
		return;
	}
	GVariant *layout = g_variant_get_child_value(ret, 1);
	mp->root = node_parse(layout);
	g_variant_unref(layout);
	g_variant_unref(ret);
	mp->items = items_build(mp->root, &mp->count);
	struct c8ui_widget *page = c8ui_canvas_new(0, 0, page_draw, NULL, mp);
	page->expand = true;
	page->user_data = mp;
	page->on_destroy = page_destroyed;
	c8ui_widget_set_scheme(page, C8UI_SCHEME_DARK);
	panels_show_flyout(page, NULL, NULL);
}

static void open_menu(struct tray_item *it, int x, int y) {
	if (!it->menu[0] || strcmp(it->menu, "/NO_DBUSMENU") == 0) {
		/* The app draws its own */
		call_item(it, "ContextMenu", x, y);
		panels_close();
		return;
	}
	struct menu_page *mp = g_new0(struct menu_page, 1);
	mp->bus = g_strdup(it->bus);
	mp->path = g_strdup(it->menu);
	mp->title = g_strdup(tray_title(it));
	/* Some apps fill the menu in when asked */
	g_dbus_connection_call(t.bus, it->bus, it->menu, MENU_IFACE,
		"AboutToShow", g_variant_new("(i)", 0), NULL,
		G_DBUS_CALL_FLAGS_NONE, 1000, NULL, NULL, NULL);
	g_dbus_connection_call(t.bus, it->bus, it->menu, MENU_IFACE, "GetLayout",
		g_variant_new("(iias)", 0, -1, NULL), G_VARIANT_TYPE("(u(ia{sv}av))"),
		G_DBUS_CALL_FLAGS_NONE, 2000, NULL, layout_got, mp);
}

void tray_click(struct tray_item *it, int button, int x, int y) {
	if (button == C8UI_BUTTON_RIGHT || it->is_menu) {
		open_menu(it, x, y);
		return;
	}
	if (button == C8UI_BUTTON_LEFT) {
		call_item(it, "Activate", x, y);
	} else {
		call_item(it, "SecondaryActivate", x, y);
	}
	panels_close();
}
