/*
 * c8-video, Video: plays your videos, after Windows 8's Video app.
 * Opened with videos (from Files, a browser, a terminal) it plays the
 * first, the rest of its folder after it; opened from Start it shows
 * Videos as a grid to pick from.
 *
 * libmpv does the playing (player.c). 3D videos (the eyes' pictures side
 * by side or one over the other) show as 2D or for coloured glasses,
 * and all-round ones (360, 180) can be looked round in with a drag:
 * the app bar's 3D command says what a video is when it couldn't tell.
 *
 * The app bar also has the subtitles, the sound tracks and the speed;
 * the Search charm finds videos in the folder, the Settings charm has
 * the options.
 */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include <c8ui/c8ui-charms.h>
#include <c8ui/c8ui-files.h>
#include "video.h"

enum command {
	CMD_OPEN,
	CMD_PICTURE,
	CMD_SUBTITLES,
	CMD_SOUND,
	CMD_SPEED,
	CMD_CHAPTERS,
	CMD_PLAYLIST,
	CMD_REPEAT,
	CMD_REFRESH,
	CMD_BROWSE,
	CMD_COUNT,
};

static struct {
	struct c8ui_app *app;
	struct c8ui_window *win;
	struct c8ui_root *root;
	struct c8ui_widget *stack, *browse, *stage, *appbar, *flyout;
	struct c8ui_widget *cmd[CMD_COUNT];
	struct c8ui_widget *layout, *swap, *shape, *show; // the 3D flyout's
	struct c8ui_charms *charms;
	char *startup_error;
	bool playing; // the player's page is up
	GPtrArray *items; // what plays: struct vd_entry
	int index;
	bool view_said; // you set this video's 3D by hand
	bool was_ended;
	GArray *menu_tracks; // the menu up is of these
	char *playing_name; // what the player has open, for the tile
	struct c8ui_widget *plist; // the play list flyout's list, while up
	struct c8ui_widget *chapters; // the chapters flyout's list, while up
} g;

static void show_browse(void);

static struct vd_entry *current(void) {
	if (!g.playing || g.items == NULL || g.index < 0 ||
			g.index >= (int)g.items->len) {
		return NULL;
	}
	return g.items->pdata[g.index];
}

static void update_title(void) {
	if (g.win == NULL) {
		return;
	}
	struct vd_entry *e = current();
	if (e) {
		char *t = g_strdup_printf("%s - Video", e->name);
		c8ui_window_set_title(g.win, t);
		g_free(t);
	} else {
		c8ui_window_set_title(g.win, "Video");
	}
}

static void update_commands(void) {
	if (g.appbar == NULL) {
		return;
	}
	bool open = g.playing && vd.active;
	c8ui_widget_set_hidden(g.cmd[CMD_PICTURE], !open);
	c8ui_widget_set_hidden(g.cmd[CMD_SUBTITLES], !open);
	c8ui_widget_set_hidden(g.cmd[CMD_SOUND], !open);
	c8ui_widget_set_hidden(g.cmd[CMD_SPEED], !open);
	c8ui_widget_set_hidden(g.cmd[CMD_CHAPTERS], !open ||
		vd.chapters->len < 2);
	c8ui_widget_set_hidden(g.cmd[CMD_PLAYLIST], !g.playing);
	c8ui_widget_set_hidden(g.cmd[CMD_REPEAT], !g.playing);
	c8ui_widget_set_hidden(g.cmd[CMD_BROWSE], !g.playing);
	c8ui_widget_set_hidden(g.cmd[CMD_REFRESH], g.playing);
	c8ui_appbar_command_set_toggle(g.cmd[CMD_REPEAT], prefs.repeat);
}

static void toggle_appbar(void) {
	if (g.appbar) {
		update_commands();
		c8ui_appbar_toggle(g.appbar);
		if (g.playing) {
			stage_wake();
		}
	}
}

static bool busy(void) {
	return (g.appbar && c8ui_appbar_is_shown(g.appbar)) || g.flyout;
}

/* What a video's picture is: guessed when it opens, and again when mpv
 * has read what the file says, unless you said */
static void guess_view(void) {
	struct vd_entry *e = current();
	if (e == NULL || g.view_said) {
		return;
	}
	struct vd_view v, now = *player_view();
	views_guess(e->uri, vd.stereo, &v);
	v.yaw = now.yaw;
	v.pitch = now.pitch;
	v.fov = now.fov;
	player_set_view(&v);
}

static void play_index(int index) {
	if (g.items == NULL || index < 0 || index >= (int)g.items->len) {
		return;
	}
	g.index = index;
	g.view_said = false;
	g.was_ended = false;
	struct vd_entry *e = g.items->pdata[index];
	/* The one before is let go first, as it was shown (the tile) */
	player_load(e->uri);
	g_free(g.playing_name);
	g.playing_name = g_strdup(e->name);
	g_clear_pointer(&vd.stereo, g_free);
	struct vd_view v;
	views_guess(e->uri, NULL, &v);
	player_set_view(&v);
	stage_set_skip(g.items->len > 1);
	if (g.plist) {
		c8ui_list_redraw(g.plist);
	}
	stage_wake();
	update_title();
	update_commands();
}

static void go_next(void) {
	if (g.playing && g.items && g.index + 1 < (int)g.items->len) {
		play_index(g.index + 1);
	}
}

static void go_previous(void) {
	/* Back to the start first, as players do; again for the one before */
	if (g.playing && vd.position > 5) {
		player_seek(0);
	} else if (g.playing && g.index > 0) {
		play_index(g.index - 1);
	}
}

/* A copy of our own: the play list can be changed */
static void set_items(GPtrArray *items, int index) {
	GPtrArray *mine = g_ptr_array_new_full(items->len,
		(GDestroyNotify)vd_entry_unref);
	for (guint i = 0; i < items->len; i++) {
		g_ptr_array_add(mine, vd_entry_ref(items->pdata[i]));
	}
	if (g.items) {
		g_ptr_array_unref(g.items);
	}
	g.items = mine;
	g.index = index;
}

static void show_player(GPtrArray *items, int index) {
	set_items(items, index);
	if (!g.playing) {
		g.playing = true;
		c8ui_stack_set(g.stack, 1, false);
	}
	stage_focus();
	play_index(index);
}

static void show_browse(void) {
	if (g.win == NULL) {
		return;
	}
	if (c8ui_window_is_fullscreen(g.win)) {
		c8ui_window_set_fullscreen(g.win, false);
	}
	struct vd_entry *e = current();
	char *uri = e ? g_strdup(e->uri) : NULL;
	player_stop();
	g.playing = false;
	c8ui_stack_set(g.stack, 0, false);
	if (uri && g_str_has_prefix(uri, "file:")) {
		browse_select(uri);
	} else if (browse_folder() == NULL) {
		char *top = vd_videos_uri();
		browse_set_folder(top, NULL);
		g_free(top);
	}
	g_free(uri);
	if (browse_list()) {
		c8ui_widget_grab_focus(browse_list());
	}
	update_title();
	update_commands();
	mpris_update(NULL, false);
}

/* The player says what changed */
static void player_changed(unsigned changes) {
	if (g.win == NULL) {
		return;
	}
	if (changes & VD_CH_PICTURE) {
		guess_view();
	}
	if (changes & VD_CH_VOLUME) {
		prefs.volume = vd.volume;
	}
	if (changes & VD_CH_CHAPTERS) {
		update_commands();
		if (g.chapters) {
			c8ui_list_set_count(g.chapters, vd.chapters->len);
			c8ui_list_redraw(g.chapters);
		}
	}
	stage_update(changes);
	if (changes & VD_CH_STATE) {
		if (vd.ended && !g.was_ended && vd.loaded) {
			if (prefs.repeat) {
				player_set_paused(false);
			} else if (g.items && g.index + 1 < (int)g.items->len) {
				go_next();
			}
		}
		g.was_ended = vd.ended;
		update_commands();
	}
	struct vd_entry *e = current();
	mpris_update(e && vd.active ? e->uri : NULL,
		g.items && g.items->len > 1);
}

/* Open */

static void show_uris(char **uris);

static void picked(char **uris, void *data) {
	if (uris && uris[0] && g.win) {
		show_uris(uris);
	}
}

static void open_file(void) {
	static const struct c8ui_file_filter filters[] = {
		{ "Videos", NULL, "video/*" },
		{ "All files", "*", NULL },
	};
	c8ui_file_open(g.win, &(struct c8ui_file_options){
		.title = "Open videos",
		.multiple = true,
		.filters = filters,
		.filter_count = 2,
	}, picked, NULL);
}

static void subtitles_picked(char **uris, void *data) {
	if (uris && uris[0] && current()) {
		player_add_subtitles(uris[0]);
	}
}

static void add_subtitles(void) {
	static const struct c8ui_file_filter filters[] = {
		{ "Subtitles", "*.srt;*.ass;*.ssa;*.vtt;*.sub;*.idx;*.sup", NULL },
		{ "All files", "*", NULL },
	};
	struct vd_entry *e = current();
	char *parent = e ? vd_parent_uri(e->uri) : NULL;
	char *folder = parent ? g_filename_from_uri(parent, NULL, NULL) : NULL;
	c8ui_file_open(g.win, &(struct c8ui_file_options){
		.title = "Add subtitles",
		.filters = filters,
		.filter_count = 2,
		.folder_path = folder,
	}, subtitles_picked, NULL);
	g_free(folder);
	g_free(parent);
}

/* Menus over the app bar's place: tracks and speed */

#define ID_ADD 100000

static void menu_place(struct c8ui_widget *command, double *x, double *y) {
	*x = command ? command->rect.x : 40;
	*y = c8ui_root_height(g.root) - 20;
}

static void tracks_done(void) {
	player_tracks_free(g.menu_tracks);
	g.menu_tracks = NULL;
	stage_hold(false);
}

static void subtitles_chosen(int id, void *data) {
	if (id == ID_ADD) {
		add_subtitles();
	} else if (id >= 0) {
		player_set_track('s', id);
	}
	tracks_done();
}

static void sound_chosen(int id, void *data) {
	if (id >= 0) {
		player_set_track('a', id);
	}
	tracks_done();
}

static void tracks_menu(char type) {
	if (g.menu_tracks) {
		return;
	}
	g.menu_tracks = player_tracks(type);
	GArray *items = g_array_new(FALSE, TRUE, sizeof(struct c8ui_menu_item));
	bool any = false;
	for (guint i = 0; i < g.menu_tracks->len; i++) {
		struct vd_track *t = &g_array_index(g.menu_tracks, struct vd_track, i);
		struct c8ui_menu_item item = { .label = t->label, .id = t->id,
			.kind = C8UI_MENU_RADIO, .checked = t->selected };
		any = any || t->selected;
		g_array_append_val(items, item);
	}
	if (type == 's') {
		struct c8ui_menu_item off = { .label = "No subtitles", .id = 0,
			.kind = C8UI_MENU_RADIO, .checked = !any };
		g_array_prepend_val(items, off);
		struct c8ui_menu_item line = { .kind = C8UI_MENU_SEPARATOR };
		g_array_append_val(items, line);
		struct c8ui_menu_item add = { .label = "Add a subtitles file",
			.id = ID_ADD };
		g_array_append_val(items, add);
	} else if (items->len == 0) {
		struct c8ui_menu_item none = { .label = "This video has no sound",
			.id = -2, .disabled = true };
		g_array_append_val(items, none);
	}
	double x, y;
	menu_place(g.cmd[type == 's' ? CMD_SUBTITLES : CMD_SOUND], &x, &y);
	stage_hold(true);
	c8ui_menu_show_items(g.root, x, y, true,
		(struct c8ui_menu_item *)items->data, items->len,
		type == 's' ? subtitles_chosen : sound_chosen, NULL);
	g_array_unref(items);
}

static const double speeds[] = { 0.5, 0.75, 1, 1.25, 1.5, 2 };
static const char *const speed_names[] = {
	"Half speed", "Three quarters", "Normal", "A quarter faster",
	"Half as fast again", "Twice as fast",
};

static void speed_chosen(int id, void *data) {
	if (id >= 0 && id < (int)G_N_ELEMENTS(speeds)) {
		player_set_speed(speeds[id]);
	}
	stage_hold(false);
}

static void speed_menu(void) {
	struct c8ui_menu_item items[G_N_ELEMENTS(speeds)];
	for (size_t i = 0; i < G_N_ELEMENTS(speeds); i++) {
		items[i] = (struct c8ui_menu_item){ .label = speed_names[i], .id = i,
			.kind = C8UI_MENU_RADIO,
			.checked = fabs(vd.speed - speeds[i]) < 0.01 };
	}
	double x, y;
	menu_place(g.cmd[CMD_SPEED], &x, &y);
	stage_hold(true);
	c8ui_menu_show_items(g.root, x, y, true, items, G_N_ELEMENTS(items),
		speed_chosen, NULL);
}

/* Flyouts of a list over the app bar's place: the play list, chapters */

static struct c8ui_widget *list_flyout(const char *title,
		struct c8ui_widget *list, int count, struct c8ui_widget *below,
		c8ui_flyout_fn closed) {
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 12);
	c8ui_box_set_padding(box, 24, 20, 24, 20);
	box->fixed_width = fmin(420, c8ui_root_width(g.root) - 24);
	c8ui_widget_add(box, c8ui_label_new(title, C8UI_TEXT_SUBHEADER));
	list->fill = true;
	struct c8ui_widget *scroll = c8ui_scroll_new(list);
	scroll->fill = true;
	double room = c8ui_root_height(g.root) - 260 - (below ? 90 : 0);
	scroll->fixed_height = fmax(120, fmin(room, count * 60.0));
	c8ui_widget_add(box, scroll);
	if (below) {
		c8ui_widget_add(box, below);
	}
	double w = c8ui_root_width(g.root), h = c8ui_root_height(g.root);
	struct c8ui_rect anchor = { w / 2 - 1, h - 110, 2, 2 };
	stage_hold(true);
	g.flyout = c8ui_flyout_show(g.root, &anchor, box, closed, NULL);
	return box;
}

static char *clock_text(double seconds) {
	int t = (int)seconds;
	return t >= 3600 ? g_strdup_printf("%d:%02d:%02d", t / 3600,
		t / 60 % 60, t % 60) : g_strdup_printf("%d:%02d", t / 60, t % 60);
}

/* Chapters */

static void chapter_draw(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	if (item->index >= (int)vd.chapters->len) {
		return;
	}
	struct vd_chapter *c = &g_array_index(vd.chapters, struct vd_chapter,
		item->index);
	char *at = clock_text(c->time);
	char *line = item->index == vd.chapter ?
		g_strdup_printf("%s · Playing", at) : g_strdup(at);
	c8ui_list_draw_text(list, cr, item, NULL, c->title, line);
	g_free(line);
	g_free(at);
}

static void chapter_open(struct c8ui_widget *list, int index, void *data) {
	player_set_chapter(index);
	if (g.flyout) {
		c8ui_flyout_close(g.flyout);
	}
}

static void chapters_closed(void *data) {
	g.flyout = NULL;
	g.chapters = NULL;
	stage_hold(false);
	/* Not the transport: Enter there would pause */
	stage_focus();
}

static void chapters_flyout(void) {
	if (g.flyout || current() == NULL || vd.chapters->len == 0) {
		return;
	}
	g.chapters = c8ui_list_new(C8UI_LIST_ROWS, 0, 56, chapter_draw, NULL);
	c8ui_list_set_click_opens(g.chapters, true);
	c8ui_list_on_open(g.chapters, chapter_open, NULL);
	c8ui_list_set_count(g.chapters, vd.chapters->len);
	list_flyout("Chapters", g.chapters, vd.chapters->len, NULL,
		chapters_closed);
	int at = MAX(vd.chapter, 0);
	c8ui_list_select(g.chapters, at);
	c8ui_list_reveal(g.chapters, at);
	c8ui_widget_grab_focus(g.chapters);
}

static void chapter_by(int by) {
	if (vd.chapters->len == 0) {
		return;
	}
	if (by < 0 && vd.chapter >= 0 && vd.position -
			g_array_index(vd.chapters, struct vd_chapter, vd.chapter).time > 5) {
		/* Back to the start of this one first, as with videos */
		by = 0;
	}
	int to = vd.chapter + by;
	if (to >= (int)vd.chapters->len) {
		return;
	}
	player_set_chapter(MAX(to, 0));
}

/* The play list: what plays, in order, to change */

enum plist_action {
	PL_PLAY,
	PL_UP,
	PL_DOWN,
	PL_REMOVE,
	PL_ADD,
};

static void plist_draw(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	if (g.items == NULL || item->index >= (int)g.items->len) {
		return;
	}
	struct vd_entry *e = g.items->pdata[item->index];
	c8ui_list_draw_text(list, cr, item, NULL, e->name,
		item->index == g.index ? "Playing" : NULL);
}

static void plist_refresh(int select) {
	if (g.plist == NULL) {
		return;
	}
	c8ui_list_set_count(g.plist, g.items ? g.items->len : 0);
	c8ui_list_redraw(g.plist);
	if (select >= 0) {
		c8ui_list_select(g.plist, select);
		c8ui_list_reveal(g.plist, select);
	}
	stage_set_skip(g.items && g.items->len > 1);
	update_commands();
}

static void plist_move(int from, int by) {
	int to = from + by;
	if (g.items == NULL || from < 0 || to < 0 || to >= (int)g.items->len) {
		return;
	}
	gpointer e = g.items->pdata[from];
	g.items->pdata[from] = g.items->pdata[to];
	g.items->pdata[to] = e;
	if (g.index == from) {
		g.index = to;
	} else if (g.index == to) {
		g.index = from;
	}
	plist_refresh(to);
}

static void plist_remove(int at) {
	if (g.items == NULL || at < 0 || at >= (int)g.items->len) {
		return;
	}
	g_ptr_array_remove_index(g.items, at);
	if (g.items->len == 0) {
		/* Nothing left to play */
		if (g.flyout) {
			c8ui_flyout_close(g.flyout);
		}
		show_browse();
		return;
	}
	if (at < g.index) {
		g.index--;
	} else if (at == g.index) {
		/* The one playing went: the next takes its place */
		play_index(MIN(at, (int)g.items->len - 1));
	}
	plist_refresh(MIN(at, (int)g.items->len - 1));
}

static void plist_picked(char **uris, void *data) {
	if (uris == NULL || g.items == NULL || !g.playing) {
		return;
	}
	int first = g.items->len;
	for (int i = 0; uris[i]; i++) {
		struct vd_entry *e = vd_entry_for(uris[i]);
		if (e->folder) {
			vd_entry_unref(e);
		} else {
			g_ptr_array_add(g.items, e);
		}
	}
	if ((int)g.items->len > first) {
		plist_refresh(first);
		mpris_update(current() ? current()->uri : NULL, g.items->len > 1);
	}
}

static void plist_add(void) {
	static const struct c8ui_file_filter filters[] = {
		{ "Videos", NULL, "video/*" },
		{ "All files", "*", NULL },
	};
	struct vd_entry *e = current();
	char *parent = e ? vd_parent_uri(e->uri) : NULL;
	char *folder = parent ? g_filename_from_uri(parent, NULL, NULL) : NULL;
	c8ui_file_open(g.win, &(struct c8ui_file_options){
		.title = "Add to the play list",
		.multiple = true,
		.filters = filters,
		.filter_count = 2,
		.folder_path = folder,
	}, plist_picked, NULL);
	g_free(folder);
	g_free(parent);
}

static void plist_do(enum plist_action action) {
	int at = g.plist ? c8ui_list_get_selected(g.plist) : -1;
	switch (action) {
	case PL_PLAY:
		if (at >= 0) {
			play_index(at);
		}
		break;
	case PL_UP:
		plist_move(at, -1);
		break;
	case PL_DOWN:
		plist_move(at, 1);
		break;
	case PL_REMOVE:
		plist_remove(at);
		break;
	case PL_ADD:
		plist_add();
		break;
	}
}

static void plist_button(struct c8ui_widget *w, void *data) {
	plist_do(GPOINTER_TO_INT(data));
}

static void plist_open(struct c8ui_widget *list, int index, void *data) {
	play_index(index);
}

static void plist_closed(void *data) {
	g.flyout = NULL;
	g.plist = NULL;
	stage_hold(false);
	stage_focus();
}

static void plist_flyout(void) {
	if (g.flyout || g.items == NULL || !g.playing) {
		return;
	}
	g.plist = c8ui_list_new(C8UI_LIST_ROWS, 0, 56, plist_draw, NULL);
	c8ui_list_on_open(g.plist, plist_open, NULL);
	c8ui_list_set_count(g.plist, g.items->len);
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 4);
	static const struct {
		enum plist_action action;
		const char *icon, *label;
	} buttons[] = {
		{ PL_PLAY, "media-playback-start", "Play" },
		{ PL_UP, "go-up", "Up" },
		{ PL_DOWN, "go-down", "Down" },
		{ PL_REMOVE, "list-remove", "Remove" },
		{ PL_ADD, "list-add", "Add" },
	};
	for (size_t i = 0; i < G_N_ELEMENTS(buttons); i++) {
		c8ui_widget_add(row, c8ui_icon_button_new(buttons[i].icon,
			buttons[i].label, plist_button,
			GINT_TO_POINTER(buttons[i].action)));
	}
	list_flyout("Play list", g.plist, g.items->len, row, plist_closed);
	c8ui_list_select(g.plist, g.index);
	c8ui_list_reveal(g.plist, g.index);
	c8ui_widget_grab_focus(g.plist);
}

/* Keys on the play list: Delete, Alt with Up and Down */
static bool plist_keys(const struct c8ui_event *ev) {
	if (g.plist == NULL) {
		return false;
	}
	bool alt = ev->mods & C8UI_MOD_ALT;
	if (ev->sym == XKB_KEY_Delete) {
		plist_do(PL_REMOVE);
	} else if (alt && ev->sym == XKB_KEY_Up) {
		plist_do(PL_UP);
	} else if (alt && ev->sym == XKB_KEY_Down) {
		plist_do(PL_DOWN);
	} else if (ev->sym == XKB_KEY_Insert) {
		plist_do(PL_ADD);
	} else {
		return false;
	}
	return true;
}

/* The 3D flyout: what this video is, and how to show it */

static void view_changed(struct c8ui_widget *w, void *data) {
	struct vd_entry *e = current();
	if (e == NULL || g.layout == NULL) {
		return;
	}
	struct vd_view v = *player_view();
	v.layout = c8ui_combo_get(g.layout);
	v.swap = c8ui_checkbox_get(g.swap);
	v.shape = c8ui_combo_get(g.shape);
	v.show = c8ui_combo_get(g.show);
	if (v.shape == VD_FLAT) {
		v.yaw = v.pitch = 0;
		v.fov = VD_FOV_DEFAULT;
	}
	g.view_said = true;
	player_set_view(&v);
	views_remember(e->uri, &v);
	c8ui_widget_set_disabled(g.swap, v.layout == VD_MONO);
	c8ui_widget_set_disabled(g.show, v.layout == VD_MONO);
}

static void flyout_closed(void *data) {
	g.flyout = NULL;
	g.layout = g.swap = g.shape = g.show = NULL;
	stage_hold(false);
}

static void picture_flyout(void) {
	if (g.flyout || current() == NULL) {
		return;
	}
	const struct vd_view *v = player_view();
	static const char *const layouts[] = {
		"Not 3D", "3D, side by side", "3D, one over the other",
		"3D, made for red and cyan glasses",
	};
	static const char *const shapes[] = {
		"A flat picture", "All round you (360°)", "In front of you (180°)",
		"In front of you, fisheye (180°)",
	};
	static const char *const shows[] = {
		"In 2D", "For red and cyan glasses", "For green and magenta glasses",
		"For amber and blue glasses", "Both pictures, as they are",
	};
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 16);
	c8ui_box_set_padding(box, 24, 20, 24, 24);
	box->fixed_width = fmin(360, c8ui_root_width(g.root) - 24);
	c8ui_widget_add(box, c8ui_label_new("3D and all round",
		C8UI_TEXT_SUBHEADER));
	g.layout = c8ui_combo_new("This video is", layouts,
		G_N_ELEMENTS(layouts), v->layout, view_changed, NULL);
	g.layout->fill = true;
	c8ui_widget_add(box, g.layout);
	g.swap = c8ui_checkbox_new("The right eye's picture comes first",
		v->swap, view_changed, NULL);
	c8ui_widget_add(box, g.swap);
	g.show = c8ui_combo_new("Show 3D", shows, G_N_ELEMENTS(shows), v->show,
		view_changed, NULL);
	g.show->fill = true;
	c8ui_widget_add(box, g.show);
	g.shape = c8ui_combo_new("Its picture is", shapes, G_N_ELEMENTS(shapes),
		v->shape, view_changed, NULL);
	g.shape->fill = true;
	c8ui_widget_add(box, g.shape);
	struct c8ui_widget *hint = c8ui_label_new("Drag an all-round video to "
		"look round in it. Ctrl and the wheel bring it nearer or further.",
		C8UI_TEXT_CAPTION);
	c8ui_label_set_color(hint, C8UI_COLOR_SECONDARY);
	hint->fill = true;
	c8ui_widget_add(box, hint);
	c8ui_widget_set_disabled(g.swap, v->layout == VD_MONO);
	c8ui_widget_set_disabled(g.show, v->layout == VD_MONO);
	double w = c8ui_root_width(g.root), h = c8ui_root_height(g.root);
	struct c8ui_rect anchor = { w / 2 - 1, h - 110, 2, 2 };
	stage_hold(true);
	g.flyout = c8ui_flyout_show(g.root, &anchor, box, flyout_closed, NULL);
}

static void set_fullscreen(bool on) {
	if (g.win) {
		c8ui_window_set_fullscreen(g.win, on);
	}
}

static void fullscreen_changed(struct c8ui_window *win, void *data) {
	stage_set_fullscreen(c8ui_window_is_fullscreen(win));
}

static void command(struct c8ui_widget *w, void *data) {
	switch ((enum command)GPOINTER_TO_INT(data)) {
	case CMD_OPEN:
		open_file();
		break;
	case CMD_PICTURE:
		picture_flyout();
		break;
	case CMD_SUBTITLES:
		tracks_menu('s');
		break;
	case CMD_SOUND:
		tracks_menu('a');
		break;
	case CMD_SPEED:
		speed_menu();
		break;
	case CMD_CHAPTERS:
		chapters_flyout();
		break;
	case CMD_PLAYLIST:
		plist_flyout();
		break;
	case CMD_REPEAT:
		prefs.repeat = !prefs.repeat;
		prefs_save();
		break;
	case CMD_REFRESH:
		browse_refresh();
		break;
	case CMD_BROWSE:
		show_browse();
		break;
	default:
		break;
	}
}

/* The grid */

static void browse_open(GPtrArray *videos, int index) {
	show_player(videos, index);
}

static void browse_changed(void) {
	update_commands();
}

/* Keys no widget took */

static void nudge_speed(int by) {
	int at = 2;
	for (size_t i = 0; i < G_N_ELEMENTS(speeds); i++) {
		if (fabs(vd.speed - speeds[i]) < 0.01) {
			at = i;
		}
	}
	at = CLAMP(at + by, 0, (int)G_N_ELEMENTS(speeds) - 1);
	player_set_speed(speeds[at]);
}

static void next_subtitles(void) {
	GArray *tracks = player_tracks('s');
	int next = tracks->len > 0 ?
		g_array_index(tracks, struct vd_track, 0).id : 0;
	for (guint i = 0; i < tracks->len; i++) {
		if (g_array_index(tracks, struct vd_track, i).selected) {
			next = i + 1 < tracks->len ?
				g_array_index(tracks, struct vd_track, i + 1).id : 0;
		}
	}
	player_set_track('s', next);
	player_tracks_free(tracks);
}

static bool player_keys(const struct c8ui_event *ev) {
	bool ctrl = ev->mods & C8UI_MOD_CTRL;
	bool shift = ev->mods & C8UI_MOD_SHIFT;
	switch (ev->sym) {
	case XKB_KEY_Escape:
		if (c8ui_window_is_fullscreen(g.win)) {
			set_fullscreen(false);
		} else {
			show_browse();
		}
		return true;
	case XKB_KEY_BackSpace:
		show_browse();
		return true;
	case XKB_KEY_space:
		player_set_paused(!(vd.paused || vd.ended));
		break;
	case XKB_KEY_Left:
	case XKB_KEY_Right: {
		double by = ctrl ? 60 : shift ? 1 : 5;
		player_seek_by(ev->sym == XKB_KEY_Left ? -by : by);
		break;
	}
	case XKB_KEY_Up:
		player_set_volume(vd.volume + 0.05);
		break;
	case XKB_KEY_Down:
		player_set_volume(vd.volume - 0.05);
		break;
	case XKB_KEY_Home:
		player_seek(0);
		break;
	case XKB_KEY_Page_Down:
		if (shift) {
			chapter_by(1);
		} else {
			go_next();
		}
		break;
	case XKB_KEY_Page_Up:
		if (shift) {
			chapter_by(-1);
		} else {
			go_previous();
		}
		break;
	case XKB_KEY_F11:
		set_fullscreen(!c8ui_window_is_fullscreen(g.win));
		break;
	case XKB_KEY_comma:
		player_step(true);
		break;
	case XKB_KEY_period:
		player_step(false);
		break;
	case XKB_KEY_bracketleft:
		nudge_speed(-1);
		break;
	case XKB_KEY_bracketright:
		nudge_speed(1);
		break;
	default:
		if (ctrl || (ev->mods & C8UI_MOD_ALT)) {
			return false;
		}
		switch (ev->base_sym) {
		case XKB_KEY_k:
			player_set_paused(!(vd.paused || vd.ended));
			break;
		case XKB_KEY_f:
			set_fullscreen(!c8ui_window_is_fullscreen(g.win));
			break;
		case XKB_KEY_m:
			player_set_muted(!vd.muted);
			break;
		case XKB_KEY_n:
			go_next();
			break;
		case XKB_KEY_p:
			go_previous();
			break;
		case XKB_KEY_s:
			next_subtitles();
			break;
		case XKB_KEY_3:
			picture_flyout();
			break;
		case XKB_KEY_l:
			plist_flyout();
			break;
		case XKB_KEY_c:
			chapters_flyout();
			break;
		case XKB_KEY_r: {
			/* Look ahead again */
			struct vd_view v = *player_view();
			v.yaw = v.pitch = 0;
			v.fov = VD_FOV_DEFAULT;
			player_set_view(&v);
			break;
		}
		default:
			return false;
		}
	}
	stage_wake();
	return true;
}

static bool keys(const struct c8ui_event *ev, void *data) {
	bool ctrl = ev->mods & C8UI_MOD_CTRL;
	if (ev->sym == XKB_KEY_Menu) {
		toggle_appbar();
		return true;
	}
	if (ctrl && ev->base_sym == XKB_KEY_o) {
		open_file();
		return true;
	}
	if (plist_keys(ev)) {
		return true;
	}
	if (g.playing) {
		return player_keys(ev);
	}
	switch (ev->sym) {
	case XKB_KEY_BackSpace:
		browse_up();
		return true;
	case XKB_KEY_Up:
		if (ev->mods & C8UI_MOD_ALT) {
			browse_up();
			return true;
		}
		return false;
	case XKB_KEY_F5:
		browse_refresh();
		return true;
	}
	return false;
}

static void resized(struct c8ui_root *root, double width, double height,
		void *data) {
	browse_set_narrow(c8ui_root_is_narrow(root));
	player_resize();
}

static void window_gone(struct c8ui_widget *w, void *data) {
	player_detach();
	prefs_save();
	g.win = NULL;
	g.root = NULL;
	g.stack = g.browse = g.stage = g.appbar = g.flyout = NULL;
	g.plist = g.chapters = NULL;
	g.layout = g.swap = g.shape = g.show = NULL;
	memset(g.cmd, 0, sizeof(g.cmd));
	g.playing = false;
	mpris_update(NULL, false);
}

static void make_window(void) {
	g.win = c8ui_window_new(g.app, "Video", 1100, 720);
	/* Clear: the video is on a surface under this one. The grid's page
	 * paints its own dark. */
	c8ui_window_set_background(g.win, 0x000000, 0);
	g.root = c8ui_window_root(g.win);
	g.stack = c8ui_stack_new();
	g.stack->fill = true;
	g.stack->on_destroy = window_gone;
	c8ui_widget_set_scheme(g.stack, C8UI_SCHEME_DARK);
	static const struct browse_hooks bh = {
		.open_video = browse_open,
		.changed = browse_changed,
		.context = toggle_appbar,
	};
	g.browse = browse_new(&bh);
	g.browse->has_background = true;
	g.browse->background = 0x1d1d1d;
	c8ui_widget_add(g.stack, g.browse);
	static const struct stage_hooks sh = {
		.back = show_browse,
		.context = toggle_appbar,
		.fullscreen = set_fullscreen,
		.previous = go_previous,
		.next = go_next,
		.busy = busy,
	};
	g.stage = stage_new(&sh);
	c8ui_widget_add(g.stack, g.stage);
	c8ui_root_set_child(g.root, g.stack);
	stage_attach(g.win);
	c8ui_root_set_key_handler(g.root, keys, NULL);
	c8ui_root_on_resize(g.root, resized, NULL);
	c8ui_window_on_fullscreen(g.win, fullscreen_changed, NULL);
	player_attach(g.win);
	resized(g.root, c8ui_root_width(g.root), c8ui_root_height(g.root), NULL);

	g.appbar = c8ui_appbar_new(g.root);
	static const struct {
		enum command cmd;
		const char *icon, *label;
		bool right;
	} cmds[] = {
		{ CMD_OPEN, "document-open", "Open", false },
		{ CMD_PICTURE, "view-3d", "3D", false },
		{ CMD_SUBTITLES, "media-view-subtitles", "Subtitles", false },
		{ CMD_SOUND, "media-track-audio", "Sound", false },
		{ CMD_SPEED, "media-playback-speed", "Speed", false },
		{ CMD_CHAPTERS, "media-chapters", "Chapters", false },
		{ CMD_PLAYLIST, "view-media-playlist", "Play list", true },
		{ CMD_REPEAT, "media-playlist-repeat", "Repeat", true },
		{ CMD_REFRESH, "view-refresh", "Refresh", true },
		{ CMD_BROWSE, "view-grid", "All videos", true },
	};
	for (size_t i = 0; i < G_N_ELEMENTS(cmds); i++) {
		g.cmd[cmds[i].cmd] = c8ui_appbar_add(g.appbar, cmds[i].icon,
			cmds[i].label, cmds[i].right, command,
			GINT_TO_POINTER(cmds[i].cmd));
	}
	c8ui_appbar_command_set_toggle(g.cmd[CMD_REPEAT], prefs.repeat);
	update_commands();
	if (g.startup_error) {
		c8ui_dialog_message(g.root, "Videos can't be played",
			g.startup_error);
	}
}

/* Charms */

static void search(struct c8ui_search *s, const char *query, void *data) {
	GPtrArray *items = g.playing ? g.items : browse_entries();
	if (items == NULL || query[0] == '\0') {
		return;
	}
	char *q = g_utf8_casefold(query, -1);
	int found = 0;
	for (guint i = 0; i < items->len && found < 50; i++) {
		struct vd_entry *e = items->pdata[i];
		char *name = g_utf8_casefold(e->name, -1);
		if (strstr(name, q)) {
			c8ui_search_add(s, e->uri, e->name, e->folder ? "Folder" : NULL,
				e->folder ? "folder" : "video-x-generic");
			found++;
		}
		g_free(name);
	}
	g_free(q);
}

static void result(const char *id, const char *query, void *data) {
	if (g.win == NULL) {
		return;
	}
	GPtrArray *items = g.playing ? g.items : browse_entries();
	for (guint i = 0; items && i < items->len; i++) {
		struct vd_entry *e = items->pdata[i];
		if (strcmp(e->uri, id) != 0) {
			continue;
		}
		if (g.playing) {
			play_index(i);
		} else if (e->folder) {
			browse_set_folder(e->uri, NULL);
		} else {
			GPtrArray *videos = vd_videos_of(items);
			for (guint j = 0; j < videos->len; j++) {
				if (videos->pdata[j] == e) {
					show_player(videos, j);
				}
			}
			g_ptr_array_unref(videos);
		}
		break;
	}
	c8ui_window_present(g.win);
}

static const char *const show_items[] = {
	"In 2D", "For red and cyan glasses", "For green and magenta glasses",
	"For amber and blue glasses", "Both pictures, as they are",
};

static void resume_changed(struct c8ui_setting *s, void *data) {
	prefs.resume = c8ui_setting_get_bool(s);
	prefs_save();
}

static void show_changed(struct c8ui_setting *s, void *data) {
	int i = c8ui_setting_get_int(s);
	if (i >= 0 && i < VD_SHOW_COUNT) {
		prefs.show = i;
		prefs_save();
	}
}

static void hwdec_changed(struct c8ui_setting *s, void *data) {
	prefs.hwdec = c8ui_setting_get_bool(s);
	prefs_save();
}

static void tile_changed(struct c8ui_setting *s, void *data) {
	prefs.tile = c8ui_setting_get_bool(s);
	prefs_save();
	if (!prefs.tile) {
		tile_clear();
	}
}

static void options(struct c8ui_settings_page *page, void *data) {
	c8ui_page_toggle(page, "resume", "Carry on where I left off",
		prefs.resume, resume_changed, NULL);
	struct c8ui_setting *s = c8ui_page_choice(page, "show", "Show 3D videos",
		show_items, G_N_ELEMENTS(show_items), prefs.show, show_changed, NULL);
	c8ui_setting_set_description(s, "Until you say otherwise for a video, "
		"with 3D on the app bar");
	s = c8ui_page_toggle(page, "hwdec", "Decode on the graphics card",
		prefs.hwdec, hwdec_changed, NULL);
	c8ui_setting_set_description(s, "Easier on the battery. Applies the "
		"next time Video starts");
	s = c8ui_page_toggle(page, "tile", "Show what I watched last on the tile",
		prefs.tile, tile_changed, NULL);
	c8ui_setting_set_description(s, "Its picture where you left it, on "
		"Start");
}

/* MPRIS */

static void mpris_play(void) {
	if (g.playing) {
		player_set_paused(false);
	}
}

static void mpris_pause(void) {
	if (g.playing) {
		player_set_paused(true);
	}
}

static void mpris_toggle(void) {
	if (g.playing) {
		player_set_paused(!(vd.paused || vd.ended));
	}
}

static void mpris_stopped(void) {
	if (g.playing) {
		show_browse();
	}
}

static void mpris_raise(void) {
	if (g.win) {
		c8ui_window_present(g.win);
	}
}

/* The app */

/* A video is let go: the tile shows where it was left */
static void player_leaving(void) {
	tile_left(g.playing_name, vd.position, vd.duration);
}

static void startup(struct c8ui_app *app, void *data) {
	g.app = app;
	prefs_load();
	if (!player_init(app, &g.startup_error)) {
		g_warning("video: %s", g.startup_error);
	}
	player_on_change(player_changed);
	player_on_leave(player_leaving);
	static const struct mpris_hooks mh = {
		.play = mpris_play,
		.pause = mpris_pause,
		.toggle = mpris_toggle,
		.stop = mpris_stopped,
		.next = go_next,
		.previous = go_previous,
		.raise = mpris_raise,
	};
	mpris_start(&mh);
	g.charms = c8ui_charms_new(app);
	if (g.charms) {
		c8ui_charms_on_search(g.charms, search, result, NULL, NULL);
		c8ui_charms_add_page(g.charms, "options", "Options", options, NULL);
	}
}

/* The one video opened plays at once; the others of its folder come
 * after, for next and previous */
static void siblings(GPtrArray *entries, const char *error, void *data) {
	char *uri = data;
	struct vd_entry *e = current();
	if (entries && g.items && g.items->len == 1 && e &&
			strcmp(e->uri, uri) == 0) {
		for (guint i = 0; i < entries->len; i++) {
			if (strcmp(((struct vd_entry *)entries->pdata[i])->uri,
					uri) == 0) {
				set_items(entries, i);
				stage_set_skip(entries->len > 1);
				break;
			}
		}
	}
	g_free(uri);
}

static void show_uris(char **uris) {
	GPtrArray *items = g_ptr_array_new_with_free_func(
		(GDestroyNotify)vd_entry_unref);
	for (int i = 0; uris[i]; i++) {
		struct vd_entry *e = vd_entry_for(uris[i]);
		if (e->folder) {
			/* A folder: its grid */
			if (items->len == 0 && uris[i + 1] == NULL) {
				if (g.playing) {
					show_browse();
				}
				browse_set_folder(e->uri, NULL);
			}
			vd_entry_unref(e);
			continue;
		}
		g_ptr_array_add(items, e);
	}
	if (items->len > 0) {
		show_player(items, 0);
		struct vd_entry *e = items->pdata[0];
		if (items->len == 1 && g_str_has_prefix(e->uri, "file:")) {
			char *parent = vd_parent_uri(e->uri);
			if (parent) {
				vd_list_folder(parent, false, NULL, siblings,
					g_strdup(e->uri));
			}
			g_free(parent);
		}
	}
	g_ptr_array_unref(items);
}

static void open(struct c8ui_app *app, char **uris, void *data) {
	bool fresh = g.win == NULL;
	if (fresh) {
		make_window();
	}
	if (uris[0]) {
		show_uris(uris);
	} else if (fresh || (!g.playing && browse_folder() == NULL)) {
		char *top = vd_videos_uri();
		browse_set_folder(top, NULL);
		g_free(top);
		if (browse_list()) {
			c8ui_widget_grab_focus(browse_list());
		}
	}
	c8ui_window_present(g.win);
}

static void shutdown(struct c8ui_app *app, void *data) {
	prefs_save();
	mpris_stop();
	c8ui_charms_destroy(g.charms);
	player_shutdown();
	tile_flush();
	g_free(g.playing_name);
	if (g.items) {
		g_ptr_array_unref(g.items);
	}
	g_free(g.startup_error);
}

int main(int argc, char **argv) {
	static const struct c8ui_app_info info = {
		.id = APP_ID,
		.startup = startup,
		.open = open,
		.shutdown = shutdown,
	};
	return c8ui_app_main(&info, argc, argv);
}
