/*
 * The media keys: volume (PipeWire, through wpctl), screen brightness
 * (through logind, which lets the session's own user set it) and
 * play/pause/next/previous (MPRIS). Volume and brightness changes show
 * the level in a small box at the top left, as Windows 8 does.
 */
#define _GNU_SOURCE
#include <dirent.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include "shell.h"
#include "json.h"

#define OSD_X 40
#define OSD_Y 40
#define OSD_W 64
#define OSD_H 214
#define OSD_SHOW_MS 2500
/* In XR: lying down, at the bottom middle of the view (the
 * compositor keeps the screen's bottom there), above any toasts */
#define OSD_ROW_W 320
#define OSD_ROW_H 64
#define OSD_ROW_GAP 16
#define VOLUME_STEP "5%"
#define BRIGHTNESS_STEPS 20
#define SINK "@DEFAULT_AUDIO_SINK@"
#define SOURCE "@DEFAULT_AUDIO_SOURCE@"

enum osd_kind {
	OSD_VOLUME,
	OSD_MIC,
	OSD_BRIGHTNESS,
};

static struct {
	struct shell_surface *surface;
	struct c8ui_widget *w;
	guint hide_timer;
	enum osd_kind kind;
	int level; // 0..100
	bool muted;

	/* Brightness: the device, and what we last asked for, since sysfs
	 * may not have caught up by the next key press */
	char *backlight;
	int max, wanted;
	int64_t wanted_at;

	/* Volume from a slider: one wpctl at a time, the latest level next */
	bool volume_busy;
	int volume_next; // -1: none waiting
} m = { .volume_next = -1 };

/* The box */

void media_draw_speaker(cairo_t *cr, double cx, double cy, bool muted) {
	cairo_move_to(cr, cx - 11, cy - 4);
	cairo_line_to(cr, cx - 6, cy - 4);
	cairo_line_to(cr, cx + 1, cy - 10);
	cairo_line_to(cr, cx + 1, cy + 10);
	cairo_line_to(cr, cx - 6, cy + 4);
	cairo_line_to(cr, cx - 11, cy + 4);
	cairo_close_path(cr);
	cairo_fill(cr);
	cairo_set_line_width(cr, 1.5);
	if (muted) {
		cairo_move_to(cr, cx + 5, cy - 4);
		cairo_line_to(cr, cx + 12, cy + 4);
		cairo_move_to(cr, cx + 12, cy - 4);
		cairo_line_to(cr, cx + 5, cy + 4);
	} else {
		cairo_arc(cr, cx + 1, cy, 6, -M_PI / 4, M_PI / 4);
		cairo_new_sub_path(cr);
		cairo_arc(cr, cx + 1, cy, 11, -M_PI / 4, M_PI / 4);
	}
	cairo_stroke(cr);
}

static void draw_mic(cairo_t *cr, double cx, double cy, bool muted) {
	cairo_set_line_width(cr, 1.5);
	cairo_new_sub_path(cr);
	cairo_arc(cr, cx, cy - 6, 4, M_PI, 0);
	cairo_arc(cr, cx, cy + 1, 4, 0, M_PI);
	cairo_close_path(cr);
	cairo_fill(cr);
	cairo_arc(cr, cx, cy, 8, 0, M_PI);
	cairo_move_to(cr, cx, cy + 8);
	cairo_line_to(cr, cx, cy + 12);
	if (muted) {
		cairo_move_to(cr, cx - 10, cy + 10);
		cairo_line_to(cr, cx + 10, cy - 10);
	}
	cairo_stroke(cr);
}

void media_draw_sun(cairo_t *cr, double cx, double cy) {
	cairo_arc(cr, cx, cy, 5, 0, 2 * M_PI);
	cairo_fill(cr);
	cairo_set_line_width(cr, 1.5);
	for (int i = 0; i < 8; i++) {
		double a = i * M_PI / 4;
		cairo_move_to(cr, cx + cos(a) * 8, cy + sin(a) * 8);
		cairo_line_to(cr, cx + cos(a) * 11, cy + sin(a) * 11);
	}
	cairo_stroke(cr);
}

static void osd_glyph(cairo_t *cr, double cx, double cy) {
	cairo_set_source_rgb(cr, 1, 1, 1);
	switch (m.kind) {
	case OSD_VOLUME:
		media_draw_speaker(cr, cx, cy, m.muted);
		break;
	case OSD_MIC:
		draw_mic(cr, cx, cy, m.muted);
		break;
	case OSD_BRIGHTNESS:
		media_draw_sun(cr, cx, cy);
		break;
	}
}

/* The level as a number, centred on cx; y is its top, or its middle */
static void osd_number(struct c8ui_widget *w, cairo_t *cr, double cx,
		double y, bool middle) {
	char num[8];
	snprintf(num, sizeof(num), "%d", m.level);
	struct c8ui_font font = { 20, C8UI_WEIGHT_LIGHT };
	double tw, th;
	c8ui_text_size(c8ui_widget_font(w), font, num, 0, 0, &tw, &th);
	cairo_set_source_rgba(cr, 1, 1, 1, m.muted ? 0.5 : 1);
	c8ui_text_draw(cr, c8ui_widget_font(w), font, num, cx - tw / 2,
		middle ? y - th / 2 : y, 0, 0);
}

/* XR's: the glyph, the level filling to the right, the number */
static void osd_draw_row(struct c8ui_widget *w, cairo_t *cr) {
	double cy = OSD_ROW_H / 2.0;
	c8ui_set_source(cr, shell.appearance.background, 1);
	cairo_paint(cr);
	osd_glyph(cr, 32, cy);
	double left = 64, right = OSD_ROW_W - 64, bh = 6;
	double fill = (right - left) * m.level / 100.0;
	cairo_set_source_rgba(cr, 1, 1, 1, 0.25);
	cairo_rectangle(cr, left, cy - bh / 2, right - left, bh);
	cairo_fill(cr);
	c8ui_set_source(cr, shell.appearance.accent, m.muted ? 0.4 : 1);
	cairo_rectangle(cr, left, cy - bh / 2, fill, bh);
	cairo_fill(cr);

	osd_number(w, cr, OSD_ROW_W - 32, cy, true);
}

static void osd_draw(struct c8ui_widget *w, cairo_t *cr) {
	if (shell.appearance.xr) {
		osd_draw_row(w, cr);
		return;
	}
	double cx = OSD_W / 2.0;
	c8ui_set_source(cr, shell.appearance.background, 1);
	cairo_paint(cr);
	osd_glyph(cr, cx, 28);

	/* The level, filling up from the bottom */
	double top = 56, bottom = OSD_H - 44, bw = 6;
	double fill = (bottom - top) * m.level / 100.0;
	cairo_set_source_rgba(cr, 1, 1, 1, 0.25);
	cairo_rectangle(cr, cx - bw / 2, top, bw, bottom - top);
	cairo_fill(cr);
	c8ui_set_source(cr, shell.appearance.accent, m.muted ? 0.4 : 1);
	cairo_rectangle(cr, cx - bw / 2, bottom - fill, bw, fill);
	cairo_fill(cr);

	osd_number(w, cr, cx, OSD_H - 36, false);
}

static void osd_destroy(struct c8ui_widget *w) {
	m.w = NULL;
}

static const struct c8ui_widget_impl osd_impl = {
	.name = "osd",
	.draw = osd_draw,
	.destroy = osd_destroy,
};

static gboolean hide_osd(gpointer data) {
	m.hide_timer = 0;
	shell_surface_hide(m.surface);
	return G_SOURCE_REMOVE;
}

static void show_osd(enum osd_kind kind, int level, bool muted) {
	m.kind = kind;
	m.level = level < 0 ? 0 : level > 100 ? 100 : level;
	m.muted = muted;
	if (shell.appearance.xr) {
		shell_surface_set_rect(m.surface,
			(shell.output_width - OSD_ROW_W) / 2,
			notify_row_top() - OSD_ROW_GAP - OSD_ROW_H, OSD_ROW_W,
			OSD_ROW_H);
	} else {
		shell_surface_set_rect(m.surface, OSD_X, OSD_Y, OSD_W, OSD_H);
	}
	c8ui_widget_queue_draw(m.w);
	if (m.hide_timer) {
		g_source_remove(m.hide_timer);
	}
	m.hide_timer = g_timeout_add(OSD_SHOW_MS, hide_osd, NULL);
}

/* Volume */

typedef void (*run_done)(const char *out, void *data);

struct run {
	run_done done;
	void *data;
};

static void run_finished(GObject *source, GAsyncResult *res, gpointer data) {
	struct run *r = data;
	char *out = NULL;
	GError *err = NULL;
	if (!g_subprocess_communicate_utf8_finish(G_SUBPROCESS(source), res, &out,
			NULL, &err)) {
		g_warning("media keys: %s", err->message);
		g_error_free(err);
	} else if (r->done) {
		r->done(out ? out : "", r->data);
	}
	g_free(out);
	g_object_unref(source);
	g_free(r);
}

/* Runs argv without blocking; done gets its output */
static void run(const char *const *argv, run_done done, void *data) {
	GError *err = NULL;
	GSubprocess *proc = g_subprocess_newv(argv, G_SUBPROCESS_FLAGS_STDOUT_PIPE |
		G_SUBPROCESS_FLAGS_STDERR_SILENCE, &err);
	if (proc == NULL) {
		g_warning("media keys: %s: %s", argv[0], err->message);
		g_error_free(err);
		return;
	}
	struct run *r = g_new0(struct run, 1);
	r->done = done;
	r->data = data;
	g_subprocess_communicate_utf8_async(proc, NULL, NULL, run_finished, r);
}

/* "Volume: 0.45 [MUTED]" */
static void got_volume(const char *out, void *data) {
	enum osd_kind kind = GPOINTER_TO_INT(data);
	double v;
	if (sscanf(out, "Volume: %lf", &v) != 1) {
		return;
	}
	show_osd(kind, (int)lround(v * 100), strstr(out, "[MUTED]") != NULL);
}

static void changed_volume(const char *out, void *data) {
	enum osd_kind kind = GPOINTER_TO_INT(data);
	const char *argv[] = { "wpctl", "get-volume",
		kind == OSD_MIC ? SOURCE : SINK, NULL };
	run(argv, got_volume, data);
}

static const char *const volume_up[] = { "wpctl", "set-volume", "-l", "1",
	SINK, VOLUME_STEP "+", NULL };
static const char *const volume_down[] = { "wpctl", "set-volume", SINK,
	VOLUME_STEP "-", NULL };

/* Changing the volume unmutes first, as it does on Windows */
static void unmuted(const char *out, void *data) {
	run(data ? volume_up : volume_down, changed_volume,
		GINT_TO_POINTER(OSD_VOLUME));
}

static void volume(enum c8_shell_v1_action action) {
	static const char *const unmute[] = { "wpctl", "set-mute", SINK, "0",
		NULL };
	static const char *const mute[] = { "wpctl", "set-mute", SINK, "toggle",
		NULL };
	static const char *const mic[] = { "wpctl", "set-mute", SOURCE, "toggle",
		NULL };
	switch (action) {
	case C8_SHELL_V1_ACTION_VOLUME_UP:
	case C8_SHELL_V1_ACTION_VOLUME_DOWN:
		run(unmute, unmuted, action == C8_SHELL_V1_ACTION_VOLUME_UP ?
			GINT_TO_POINTER(1) : NULL);
		break;
	case C8_SHELL_V1_ACTION_MIC_MUTE:
		run(mic, changed_volume, GINT_TO_POINTER(OSD_MIC));
		break;
	default:
		run(mute, changed_volume, GINT_TO_POINTER(OSD_VOLUME));
		break;
	}
}

/* For the Settings flyout */

struct level_req {
	media_level_fn fn;
	void *data;
};

static void got_level(const char *out, void *data) {
	struct level_req *r = data;
	double v;
	if (sscanf(out, "Volume: %lf", &v) == 1) {
		r->fn((int)lround(v * 100), strstr(out, "[MUTED]") != NULL, r->data);
	}
	g_free(r);
}

void media_volume_get(media_level_fn fn, void *data) {
	static const char *const argv[] = { "wpctl", "get-volume", SINK, NULL };
	struct level_req *r = g_new0(struct level_req, 1);
	r->fn = fn;
	r->data = data;
	run(argv, got_level, r);
}

static void volume_send(int level);

static void volume_sent(const char *out, void *data) {
	m.volume_busy = false;
	if (m.volume_next >= 0) {
		int level = m.volume_next;
		m.volume_next = -1;
		volume_send(level);
	}
}

static void volume_send(int level) {
	if (m.volume_busy) {
		m.volume_next = level;
		return;
	}
	m.volume_busy = true;
	char value[16];
	snprintf(value, sizeof(value), "%d%%", level < 0 ? 0 :
		level > 100 ? 100 : level);
	const char *argv[] = { "wpctl", "set-volume", SINK, value, NULL };
	run(argv, volume_sent, NULL);
}

void media_volume_set(int level) {
	static const char *const unmute[] = { "wpctl", "set-mute", SINK, "0",
		NULL };
	run(unmute, NULL, NULL);
	volume_send(level);
}

void media_volume_mute(bool muted) {
	const char *argv[] = { "wpctl", "set-mute", SINK, muted ? "1" : "0",
		NULL };
	run(argv, NULL, NULL);
}

/* The apps playing sound, for the mixer beside the flyout's level. pactl
 * because wpctl has no list a program can read; without it, no apps. */

static bool have_pactl(void) {
	static int have = -1;
	if (have < 0) {
		char *path = g_find_program_in_path("pactl");
		have = path != NULL;
		g_free(path);
	}
	return have;
}

struct apps_req {
	media_apps_fn fn;
	void *data;
};

static void copy_prop(char *to, size_t len, const struct json *props,
		const char *key) {
	snprintf(to, len, "%s", json_str(json_get(props, key), ""));
}

static int by_name(const void *a, const void *b) {
	const struct media_app *x = a, *y = b;
	int order = g_ascii_strcasecmp(x->name, y->name);
	return order ? order : strcmp(x->name, y->name);
}

static void got_apps(const char *out, void *data) {
	struct apps_req *r = data;
	struct media_app *apps = g_new0(struct media_app, MEDIA_APPS_MAX);
	int count = 0;
	struct json *list = json_parse(out);
	struct json *in = list && list->type == JSON_ARRAY ? list->child : NULL;
	for (; in; in = in->next) {
		const struct json *props = json_get(in, "properties");
		const char *name = json_str(json_get(props, "application.name"),
			json_str(json_get(props, "application.process.binary"), ""));
		if (name[0] == '\0') {
			continue;
		}
		double sum = 0;
		int channels = 0;
		const struct json *volume = json_get(in, "volume");
		for (struct json *ch = volume ? volume->child : NULL; ch;
				ch = ch->next) {
			sum += json_num(json_get(ch, "value"), 0);
			channels++;
		}
		int level = channels ? (int)lround(sum / channels * 100 / 65536) : 0;
		bool muted = json_bool(json_get(in, "mute"));

		/* A browser has a stream per tab: one slider for them all */
		struct media_app *app = NULL;
		for (int i = 0; i < count; i++) {
			if (strncmp(apps[i].name, name, sizeof(apps[i].name) - 1) == 0) {
				app = &apps[i];
			}
		}
		if (app == NULL) {
			if (count == MEDIA_APPS_MAX) {
				continue;
			}
			app = &apps[count++];
			snprintf(app->name, sizeof(app->name), "%s", name);
			copy_prop(app->app_id, sizeof(app->app_id), props,
				"pipewire.access.portal.app_id");
			copy_prop(app->icon, sizeof(app->icon), props,
				"application.icon_name");
			copy_prop(app->binary, sizeof(app->binary), props,
				"application.process.binary");
			app->muted = true;
		}
		if (app->nstreams < MEDIA_APP_STREAMS) {
			app->streams[app->nstreams++] =
				(unsigned)json_num(json_get(in, "index"), 0);
		}
		app->level = level > app->level ? level : app->level;
		app->muted = app->muted && muted;
	}
	json_free(list);
	/* pactl's order isn't one, and changes: rows mustn't swap under the
	 * pointer */
	qsort(apps, count, sizeof(*apps), by_name);
	r->fn(apps, count, r->data);
	g_free(apps);
	g_free(r);
}

void media_apps_get(media_apps_fn fn, void *data) {
	static const char *const argv[] = { "pactl", "-f", "json", "list",
		"sink-inputs", NULL };
	if (!have_pactl()) {
		return;
	}
	struct apps_req *r = g_new0(struct apps_req, 1);
	r->fn = fn;
	r->data = data;
	run(argv, got_apps, r);
}

/* As the volume: one change at a time, the latest next */
static struct {
	int busy; // pactls yet to finish
	bool waiting;
	struct media_app app;
	int level;
} sending;

static void app_send(const struct media_app *app, int level);

static void app_sent(const char *out, void *data) {
	if (--sending.busy > 0 || !sending.waiting) {
		return;
	}
	sending.waiting = false;
	struct media_app app = sending.app;
	app_send(&app, sending.level);
}

static void app_send(const struct media_app *app, int level) {
	if (sending.busy > 0) {
		sending.waiting = true;
		sending.app = *app;
		sending.level = level;
		return;
	}
	char value[16];
	snprintf(value, sizeof(value), "%d%%", level < 0 ? 0 :
		level > 100 ? 100 : level);
	for (int i = 0; i < app->nstreams; i++) {
		char id[16];
		snprintf(id, sizeof(id), "%u", app->streams[i]);
		const char *argv[] = { "pactl", "set-sink-input-volume", id, value,
			NULL };
		sending.busy++;
		run(argv, app_sent, NULL);
	}
}

void media_app_mute(const struct media_app *app, bool muted) {
	for (int i = 0; i < app->nstreams; i++) {
		char id[16];
		snprintf(id, sizeof(id), "%u", app->streams[i]);
		const char *argv[] = { "pactl", "set-sink-input-mute", id,
			muted ? "1" : "0", NULL };
		run(argv, NULL, NULL);
	}
}

void media_app_set(const struct media_app *app, int level) {
	if (app->muted) {
		media_app_mute(app, false);
	}
	app_send(app, level);
}

/* Brightness */

static int read_int(const char *dir, const char *file) {
	char path[512];
	snprintf(path, sizeof(path), "%s/%s", dir, file);
	char *text = NULL;
	int v = -1;
	if (g_file_get_contents(path, &text, NULL, NULL)) {
		v = atoi(text);
	}
	g_free(text);
	return v;
}

/* The panel's own control (firmware), else the driver's, else raw */
static bool find_backlight(void) {
	if (m.backlight) {
		return true;
	}
	DIR *d = opendir("/sys/class/backlight");
	if (d == NULL) {
		return false;
	}
	static const char *const order[] = { "firmware", "platform", "raw" };
	int best_rank = 99;
	struct dirent *ent;
	while ((ent = readdir(d)) != NULL) {
		if (ent->d_name[0] == '.') {
			continue;
		}
		char *dir = g_build_filename("/sys/class/backlight", ent->d_name, NULL);
		char *path = g_build_filename(dir, "type", NULL), *type = NULL;
		int rank = 3;
		if (g_file_get_contents(path, &type, NULL, NULL)) {
			for (int i = 0; i < 3; i++) {
				if (strncmp(type, order[i], strlen(order[i])) == 0) {
					rank = i;
				}
			}
		}
		if (rank < best_rank && read_int(dir, "max_brightness") > 0) {
			best_rank = rank;
			g_free(m.backlight);
			m.backlight = g_strdup(ent->d_name);
		}
		g_free(type);
		g_free(path);
		g_free(dir);
	}
	closedir(d);
	return m.backlight != NULL;
}

static void brightness_set(GObject *source, GAsyncResult *res, gpointer data) {
	GError *err = NULL;
	GVariant *r = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res,
		&err);
	if (r == NULL) {
		g_warning("brightness: %s", err->message);
		g_error_free(err);
		return;
	}
	g_variant_unref(r);
}

/* The level now (or what we last asked for, if sysfs may lag behind),
 * in the device's own units; -1 without a backlight */
static int brightness_now(void) {
	if (!find_backlight()) {
		return -1;
	}
	char *dir = g_build_filename("/sys/class/backlight", m.backlight, NULL);
	m.max = read_int(dir, "max_brightness");
	int now = read_int(dir, "brightness");
	g_free(dir);
	if (m.max <= 0 || now < 0) {
		return -1;
	}
	if (now_ms() - m.wanted_at < 1000) {
		now = m.wanted;
	}
	return now;
}

/* Never all the way off, which on some panels turns the light off
 * altogether */
static void brightness_apply(int value, bool osd) {
	int min = m.max / 100 > 0 ? m.max / 100 : 1;
	value = value < min ? min : value > m.max ? m.max : value;
	m.wanted = value;
	m.wanted_at = now_ms();

	GDBusConnection *bus = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, NULL);
	if (bus == NULL) {
		return;
	}
	g_dbus_connection_call(bus, "org.freedesktop.login1",
		"/org/freedesktop/login1/session/auto",
		"org.freedesktop.login1.Session", "SetBrightness",
		g_variant_new("(ssu)", "backlight", m.backlight, (guint32)value),
		NULL, G_DBUS_CALL_FLAGS_NONE, 2000, NULL, brightness_set, NULL);
	g_object_unref(bus);
	if (osd) {
		show_osd(OSD_BRIGHTNESS, (int)lround(value * 100.0 / m.max), false);
	}
}

/* Even steps of the whole range */
static void brightness(int direction) {
	int now = brightness_now();
	if (now < 0) {
		return;
	}
	double step = (double)m.max / BRIGHTNESS_STEPS;
	int n = (int)lround(now / step) + direction;
	brightness_apply((int)lround(n * step), true);
}

int media_brightness_get(void) {
	int now = brightness_now();
	return now < 0 ? -1 : (int)lround(now * 100.0 / m.max);
}

void media_brightness_set(int level) {
	if (brightness_now() >= 0) {
		brightness_apply((int)lround(level * m.max / 100.0), false);
	}
}

/* Players */

static GDBusConnection *session_bus(void) {
	return g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL);
}

static char *playback_status(GDBusConnection *bus, const char *name) {
	GVariant *r = g_dbus_connection_call_sync(bus, name,
		"/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties", "Get",
		g_variant_new("(ss)", "org.mpris.MediaPlayer2.Player",
		"PlaybackStatus"), G_VARIANT_TYPE("(v)"), G_DBUS_CALL_FLAGS_NONE, 250,
		NULL, NULL);
	if (r == NULL) {
		return NULL;
	}
	GVariant *v;
	g_variant_get(r, "(v)", &v);
	char *status = g_variant_is_of_type(v, G_VARIANT_TYPE_STRING) ?
		g_variant_dup_string(v, NULL) : NULL;
	g_variant_unref(v);
	g_variant_unref(r);
	return status;
}

/* The player that's playing, else a paused one, else any */
static char *pick_player(GDBusConnection *bus) {
	GVariant *r = g_dbus_connection_call_sync(bus, "org.freedesktop.DBus",
		"/org/freedesktop/DBus", "org.freedesktop.DBus", "ListNames", NULL,
		G_VARIANT_TYPE("(as)"), G_DBUS_CALL_FLAGS_NONE, 1000, NULL, NULL);
	if (r == NULL) {
		return NULL;
	}
	char *best = NULL;
	int best_rank = 99;
	GVariantIter *iter;
	const char *name;
	g_variant_get(r, "(as)", &iter);
	while (g_variant_iter_next(iter, "&s", &name)) {
		if (!g_str_has_prefix(name, "org.mpris.MediaPlayer2.")) {
			continue;
		}
		char *status = playback_status(bus, name);
		int rank = status == NULL ? 3 : strcmp(status, "Playing") == 0 ? 0 :
			strcmp(status, "Paused") == 0 ? 1 : 2;
		g_free(status);
		if (rank < best_rank) {
			best_rank = rank;
			g_free(best);
			best = g_strdup(name);
		}
	}
	g_variant_iter_free(iter);
	g_variant_unref(r);
	return best;
}

static void player_do(gpointer data, gpointer unused) {
	const char *method = data;
	GDBusConnection *bus = session_bus();
	if (bus == NULL) {
		return;
	}
	char *name = pick_player(bus);
	if (name) {
		g_dbus_connection_call(bus, name, "/org/mpris/MediaPlayer2",
			"org.mpris.MediaPlayer2.Player", method, NULL, NULL,
			G_DBUS_CALL_FLAGS_NONE, 2000, NULL, NULL, NULL);
		g_free(name);
	}
	g_object_unref(bus);
}

/* Finding the player asks every one on the bus and waits for each: on a
 * thread, so a player that's stuck doesn't hold up Start. One thread,
 * so the keys act in the order they were pressed. method: a literal. */
static void player(const char *method) {
	static GThreadPool *pool;
	if (pool == NULL) {
		pool = g_thread_pool_new(player_do, NULL, 1, FALSE, NULL);
	}
	g_thread_pool_push(pool, (gpointer)method, NULL);
}

void media_action(enum c8_shell_v1_action action) {
	switch (action) {
	case C8_SHELL_V1_ACTION_VOLUME_UP:
	case C8_SHELL_V1_ACTION_VOLUME_DOWN:
	case C8_SHELL_V1_ACTION_VOLUME_MUTE:
	case C8_SHELL_V1_ACTION_MIC_MUTE:
		volume(action);
		break;
	case C8_SHELL_V1_ACTION_BRIGHTNESS_UP:
		brightness(1);
		break;
	case C8_SHELL_V1_ACTION_BRIGHTNESS_DOWN:
		brightness(-1);
		break;
	case C8_SHELL_V1_ACTION_MEDIA_PLAY_PAUSE:
		player("PlayPause");
		break;
	case C8_SHELL_V1_ACTION_MEDIA_NEXT:
		player("Next");
		break;
	case C8_SHELL_V1_ACTION_MEDIA_PREVIOUS:
		player("Previous");
		break;
	case C8_SHELL_V1_ACTION_MEDIA_STOP:
		player("Stop");
		break;
	default:
		break;
	}
}

void media_init(void) {
	m.surface = shell_surface_new(C8_SHELL_V1_ROLE_OSD);
	shell_surface_hide(m.surface);
	m.w = c8ui_widget_new(&osd_impl, NULL);
	m.w->fill = true;
	m.w->expand = true;
	c8ui_widget_set_scheme(m.w, C8UI_SCHEME_DARK);
	c8ui_root_set_child(shell_surface_root(m.surface), m.w);
}
