/*
 * c8-photos, Photos: look through your pictures, after Windows 8's
 * Photos app. Opened with pictures (from Files, a browser, a terminal)
 * it shows the first, with the rest of its folder a flip away; opened
 * from Start it shows Pictures as a grid to go through.
 *
 * The app bar has what Photos had: delete, turn, slide show, plus copy,
 * open with, show in folder and the picture's details. The Search charm
 * finds pictures in the folder; the Settings charm has the options.
 */
#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 "background.h"
#include "photos.h"
#include "stealth.h"

enum command {
	CMD_DELETE,
	CMD_COPY,
	CMD_OPEN_WITH,
	CMD_SHOW_FOLDER,
	CMD_DETAILS,
	CMD_ROTATE_LEFT,
	CMD_ROTATE_RIGHT,
	CMD_CROP,
	CMD_SET_AS,
	CMD_SLIDESHOW,
	CMD_BROWSE,
	CMD_OPEN,
	CMD_REFRESH,
	CMD_BY_DATE,
	CMD_BY_FOLDER,
	CMD_COUNT,
};

static struct {
	struct c8ui_app *app;
	struct c8ui_window *win;
	struct c8ui_root *root;
	struct c8ui_widget *stack, *browse, *viewer, *appbar;
	/* Under the viewer while cropping */
	struct c8ui_widget *crop_bar, *crop_ratio, *crop_save, *crop_cancel;
	bool saving;
	struct c8ui_widget *cmd[CMD_COUNT];
	struct c8ui_charms *charms;
	bool viewing;
	/* Turning: one at a time, the turns asked for meanwhile added up */
	char *rotating;
	int turns_pending;
} g;

static void show_viewer(GPtrArray *items, int index);
static void show_browse(void);

/* The app bar: the viewer's commands or the grid's */

static void update_commands(void) {
	if (g.appbar == NULL) {
		return;
	}
	struct ph_entry *e = g.viewing ? viewer_current() : NULL;
	bool pic = e != NULL;
	c8ui_widget_set_hidden(g.cmd[CMD_DELETE], !pic);
	c8ui_widget_set_hidden(g.cmd[CMD_COPY], !pic);
	c8ui_widget_set_hidden(g.cmd[CMD_OPEN_WITH], !pic);
	c8ui_widget_set_hidden(g.cmd[CMD_SHOW_FOLDER], !pic);
	c8ui_widget_set_hidden(g.cmd[CMD_DETAILS], !pic);
	bool turn = pic && ph_can_rotate(e->mime);
	c8ui_widget_set_hidden(g.cmd[CMD_ROTATE_LEFT], !turn);
	c8ui_widget_set_hidden(g.cmd[CMD_ROTATE_RIGHT], !turn);
	struct ph_picture *p = pic ? viewer_picture() : NULL;
	bool ready = p && p->state == PH_READY;
	c8ui_widget_set_hidden(g.cmd[CMD_CROP], !ready || p->animated);
	c8ui_widget_set_hidden(g.cmd[CMD_SET_AS], !ready);
	c8ui_widget_set_hidden(g.cmd[CMD_BROWSE], !g.viewing);
	c8ui_widget_set_hidden(g.cmd[CMD_OPEN], g.viewing);
	c8ui_widget_set_hidden(g.cmd[CMD_REFRESH], g.viewing);
	c8ui_widget_set_hidden(g.cmd[CMD_BY_DATE], g.viewing || browse_by_date());
	c8ui_widget_set_hidden(g.cmd[CMD_BY_FOLDER],
		g.viewing || !browse_by_date());
	GPtrArray *items = g.viewing ? viewer_items() : browse_entries();
	bool any = false;
	for (guint i = 0; items && i < items->len && !any; i++) {
		any = !((struct ph_entry *)items->pdata[i])->folder;
	}
	c8ui_widget_set_disabled(g.cmd[CMD_SLIDESHOW], !any);
}

static void update_title(void) {
	if (g.win == NULL) {
		return;
	}
	struct ph_entry *e = g.viewing ? viewer_current() : NULL;
	if (e) {
		char *t = g_strdup_printf("%s - Photos", c8_stealth_show(e->name));
		c8ui_window_set_title(g.win, t);
		g_free(t);
	} else {
		c8ui_window_set_title(g.win, "Photos");
	}
}

static void viewer_changed(void) {
	update_title();
	update_commands();
}

static void toggle_appbar(void) {
	if (g.appbar && !viewer_in_slideshow()) {
		update_commands();
		c8ui_appbar_toggle(g.appbar);
	}
}

static void message(const char *title, const char *text) {
	c8ui_dialog_message(g.root, title, text);
}

/* Delete */

static void trashed(GObject *src, GAsyncResult *res, gpointer data) {
	char *uri = data;
	GError *err = NULL;
	if (!g_file_trash_finish(G_FILE(src), res, &err)) {
		char *msg = g_strdup_printf("It couldn't be moved to the Trash: %s",
			err->message);
		message("This picture wasn't deleted", msg);
		g_free(msg);
		g_error_free(err);
		g_free(uri);
		return;
	}
	GPtrArray *items = viewer_items();
	if (g.viewing && items) {
		GPtrArray *rest = g_ptr_array_new_with_free_func(
			(GDestroyNotify)ph_entry_unref);
		int at = -1;
		for (guint i = 0; i < items->len; i++) {
			struct ph_entry *e = items->pdata[i];
			if (strcmp(e->uri, uri) == 0) {
				at = i;
			} else {
				g_ptr_array_add(rest, ph_entry_ref(e));
			}
		}
		if (at >= 0) {
			if (rest->len == 0) {
				show_browse();
			} else {
				/* The next one takes its place; after the last, the one
				 * before */
				viewer_set_items(rest, at);
			}
		}
		g_ptr_array_unref(rest);
	}
	g_free(uri);
}

static void delete_answer(int choice, void *data) {
	char *uri = data;
	if (choice == 0) {
		GFile *f = g_file_new_for_uri(uri);
		g_file_trash_async(f, G_PRIORITY_DEFAULT, NULL, trashed,
			g_strdup(uri));
		g_object_unref(f);
	}
	g_free(uri);
}

static void delete_picture(void) {
	struct ph_entry *e = viewer_current();
	if (!g.viewing || e == NULL) {
		return;
	}
	static const char *const buttons[] = { "Delete", "Cancel" };
	char *text = g_strdup_printf("%s goes to the Trash.",
		c8_stealth_show(e->name));
	c8ui_dialog_show(g.root, "Delete this picture?", text, buttons, 2,
		delete_answer, g_strdup(e->uri));
	g_free(text);
}

/* Copy: the file, as Files copies it, and the picture itself for apps
 * that paste pictures (in its own format: PNG and JPEG are what they
 * take) */

static void copy_picture(void) {
	struct ph_entry *e = viewer_current();
	if (!g.viewing || e == NULL) {
		return;
	}
	struct c8ui_clip_item picture;
	int n = 0;
	char *bytes = NULL;
	gsize len = 0;
	if (e->mime && (strcmp(e->mime, "image/png") == 0 ||
			strcmp(e->mime, "image/jpeg") == 0)) {
		GFile *f = g_file_new_for_uri(e->uri);
		if (g_file_load_contents(f, NULL, &bytes, &len, NULL, NULL)) {
			picture = (struct c8ui_clip_item){ e->mime, bytes, len };
			n = 1;
		}
		g_object_unref(f);
	}
	char *uris[] = { e->uri, NULL };
	c8ui_window_set_clipboard_files(g.win, uris, false, &picture, n);
	g_free(bytes);
}

/* Open with */

static GPtrArray *open_apps; // GAppInfo, while the menu is up

static void open_with_chosen(int choice, void *data) {
	struct ph_entry *e = viewer_current();
	if (choice >= 0 && open_apps && choice < (int)open_apps->len && e) {
		const char *uris[] = { e->uri, NULL };
		c8ui_window_launch(g.win, g_app_info_get_id(open_apps->pdata[choice]),
			uris);
	}
	g_clear_pointer(&open_apps, g_ptr_array_unref);
}

static void open_with(struct c8ui_widget *anchor) {
	struct ph_entry *e = viewer_current();
	if (!g.viewing || e == NULL || e->mime == NULL) {
		return;
	}
	char *type = g_content_type_from_mime_type(e->mime);
	GList *apps = g_app_info_get_all_for_type(type ? type : e->mime);
	g_free(type);
	g_clear_pointer(&open_apps, g_ptr_array_unref);
	open_apps = g_ptr_array_new_with_free_func(g_object_unref);
	GPtrArray *labels = g_ptr_array_new();
	for (GList *l = apps; l; l = l->next) {
		GAppInfo *app = l->data;
		const char *id = g_app_info_get_id(app);
		if (id && strcmp(id, APP_ID ".desktop") != 0 &&
				g_app_info_should_show(app)) {
			g_ptr_array_add(open_apps, g_object_ref(app));
			g_ptr_array_add(labels, (char *)g_app_info_get_display_name(app));
		}
	}
	g_list_free_full(apps, g_object_unref);
	if (labels->len == 0) {
		message("No other apps", "No other app on this PC opens pictures "
			"like this one.");
	} else {
		double x = anchor ? anchor->rect.x : c8ui_root_width(g.root) / 2;
		double y = anchor ? anchor->rect.y : c8ui_root_height(g.root) - 100;
		c8ui_menu_show(g.root, x, y, true,
			(const char *const *)labels->pdata, labels->len,
			open_with_chosen, NULL);
	}
	g_ptr_array_unref(labels);
}

/* The folder in the file manager: launched with our token, so it comes
 * forward */
static void show_in_folder(void) {
	struct ph_entry *e = viewer_current();
	char *folder = e ? ph_parent_uri(e->uri) : NULL;
	GAppInfo *fm = g_app_info_get_default_for_type("inode/directory", FALSE);
	if (folder && fm) {
		const char *uris[] = { folder, NULL };
		c8ui_window_launch(g.win, g_app_info_get_id(fm), uris);
	} else if (folder) {
		c8ui_window_open_uri(g.win, folder);
	}
	if (fm) {
		g_object_unref(fm);
	}
	g_free(folder);
}

/* Details: what the file and its camera say */

static void show_details(void) {
	struct ph_entry *e = viewer_current();
	if (!g.viewing || e == NULL) {
		return;
	}
	GPtrArray *pairs = g_ptr_array_new_with_free_func(g_free);
	ph_details(e->uri, pairs);
	struct ph_picture *p = viewer_picture();
	if (p && p->state == PH_READY) {
		g_ptr_array_insert(pairs, 2, g_strdup("Dimensions"));
		g_ptr_array_insert(pairs, 3, g_strdup_printf("%d × %d pixels",
			p->width, p->height));
	}
	GPtrArray *items = viewer_items();
	if (items && items->len > 1) {
		g_ptr_array_add(pairs, g_strdup("In this folder"));
		g_ptr_array_add(pairs, g_strdup_printf("%d of %u",
			viewer_index() + 1, items->len));
	}
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 16);
	box->fill = true;
	for (guint i = 0; i + 1 < pairs->len; i += 2) {
		struct c8ui_widget *pair = c8ui_box_new(C8UI_VERTICAL, 2);
		pair->fill = true;
		struct c8ui_widget *label = c8ui_label_new(pairs->pdata[i],
			C8UI_TEXT_CAPTION);
		c8ui_label_set_color(label, C8UI_COLOR_SECONDARY);
		c8ui_widget_add(pair, label);
		c8ui_widget_add(pair, c8ui_label_new(pairs->pdata[i + 1],
			C8UI_TEXT_BODY));
		c8ui_widget_add(box, pair);
	}
	g_ptr_array_unref(pairs);
	c8ui_settings_flyout_show(g.root, "Details", box, false, NULL, NULL);
}

/* Turning */

static void start_rotate(void);

static void rotated(const char *error, void *data) {
	char *uri = g.rotating;
	g.rotating = NULL;
	if (error) {
		g.turns_pending = 0;
		message("This picture wasn't turned", error);
	} else {
		struct ph_entry *e = viewer_current();
		if (g.viewing && e && strcmp(e->uri, uri) == 0) {
			viewer_reload();
		}
	}
	g_free(uri);
	if (g.turns_pending) {
		start_rotate();
	}
}

static void start_rotate(void) {
	struct ph_entry *e = viewer_current();
	if (e == NULL || g.turns_pending % 4 == 0) {
		g.turns_pending = 0;
		return;
	}
	int turns = g.turns_pending;
	g.turns_pending = 0;
	g.rotating = g_strdup(e->uri);
	ph_rotate(e->uri, turns, rotated, NULL);
}

static void rotate(int turns) {
	struct ph_entry *e = viewer_current();
	if (!g.viewing || e == NULL || !ph_can_rotate(e->mime)) {
		return;
	}
	/* Asked again before the last one is written: done after it, unless
	 * it's another picture by then */
	if (g.rotating && strcmp(g.rotating, e->uri) != 0) {
		return;
	}
	g.turns_pending += turns;
	if (g.rotating == NULL) {
		start_rotate();
	}
}

/* Cropping: a copy is saved beside it, "Name (cropped).ext", in the same
 * kind of file when glycin can write it; the original stays as it was */

struct ratio {
	const char *label;
	int w, h; // 0: any; -1: the picture's own
};

static const struct ratio ratios[] = {
	{ "Any", 0, 0 },
	{ "Original", -1, -1 },
	{ "Square", 1, 1 },
	{ "16:9", 16, 9 },
	{ "4:3", 4, 3 },
	{ "3:2", 3, 2 },
};

static int ratio_chosen;

/* A ratio as width over height, turned to suit a picture standing up */
static double ratio_value(int i) {
	struct ph_picture *p = viewer_picture();
	if (p == NULL || p->state != PH_READY || ratios[i].w == 0) {
		return 0;
	}
	if (ratios[i].w < 0) {
		return (double)p->width / p->height;
	}
	double r = (double)ratios[i].w / ratios[i].h;
	return p->height > p->width ? 1 / r : r;
}

static void crop_bar_update(void) {
	char *label = g_strdup_printf("Aspect ratio: %s",
		ratios[ratio_chosen].label);
	c8ui_button_set_label(g.crop_ratio, label);
	g_free(label);
	c8ui_widget_set_disabled(g.crop_ratio, g.saving);
	c8ui_widget_set_disabled(g.crop_save, g.saving);
	c8ui_widget_set_disabled(g.crop_cancel, g.saving);
}

static void crop_end(void) {
	viewer_crop_end();
	if (g.crop_bar) {
		c8ui_widget_set_hidden(g.crop_bar, true);
	}
	if (g.viewer) {
		c8ui_widget_grab_focus(g.viewer);
	}
}

static void crop_begin(void) {
	if (!g.viewing || g.saving) {
		return;
	}
	ratio_chosen = 0;
	if (!viewer_crop_begin(0)) {
		return;
	}
	if (g.appbar) {
		c8ui_appbar_hide(g.appbar);
	}
	crop_bar_update();
	c8ui_widget_set_hidden(g.crop_bar, false);
	c8ui_widget_grab_focus(g.viewer);
}

static void ratio_picked(int choice, void *data) {
	if (choice >= 0 && choice < (int)G_N_ELEMENTS(ratios)) {
		ratio_chosen = choice;
		viewer_crop_set_ratio(ratio_value(choice));
		crop_bar_update();
	}
	/* Back to the box: Enter saves, not the menu again */
	c8ui_widget_grab_focus(g.viewer);
}

static void ratio_menu(struct c8ui_widget *w, void *data) {
	const char *labels[G_N_ELEMENTS(ratios)];
	for (size_t i = 0; i < G_N_ELEMENTS(ratios); i++) {
		labels[i] = ratios[i].label;
	}
	c8ui_menu_show(g.root, w->rect.x, w->rect.y, true, labels,
		G_N_ELEMENTS(ratios), ratio_picked, NULL);
}

static const char *extension_for(const char *mime) {
	if (strcmp(mime, "image/jpeg") == 0) {
		return "jpg";
	}
	/* GIO knows no extensions by type: the usual ones by hand */
	static const struct { const char *mime, *ext; } known[] = {
		{ "image/png", "png" }, { "image/webp", "webp" },
		{ "image/tiff", "tiff" }, { "image/gif", "gif" },
		{ "image/bmp", "bmp" }, { "image/avif", "avif" },
		{ "image/heif", "heic" }, { "image/jxl", "jxl" },
		{ "image/x-tga", "tga" }, { "image/qoi", "qoi" },
		{ "image/x-exr", "exr" }, { "image/x-portable-pixmap", "ppm" },
	};
	for (size_t i = 0; i < G_N_ELEMENTS(known); i++) {
		if (strcmp(known[i].mime, mime) == 0) {
			return known[i].ext;
		}
	}
	return "png";
}

/* "Name (cropped).ext", or "(cropped 2)" and on when that is taken */
static char *crop_path(const char *path, const char *mime, bool same) {
	char *dir = g_path_get_dirname(path);
	char *base = g_path_get_basename(path);
	char *dot = strrchr(base, '.');
	const char *ext = same && dot && dot != base ? dot + 1 :
		extension_for(mime);
	char *ext_copy = g_strdup(ext);
	if (dot && dot != base) {
		*dot = '\0';
	}
	char *out = NULL;
	for (int n = 1; n < 1000; n++) {
		char *name = n == 1 ?
			g_strdup_printf("%s (cropped).%s", base, ext_copy) :
			g_strdup_printf("%s (cropped %d).%s", base, n, ext_copy);
		out = g_build_filename(dir, name, NULL);
		g_free(name);
		if (!g_file_test(out, G_FILE_TEST_EXISTS)) {
			break;
		}
		g_clear_pointer(&out, g_free);
	}
	g_free(ext_copy);
	g_free(base);
	g_free(dir);
	return out;
}

/* The folder read again with the copy in it: shown, its neighbours
 * a flip away */
static void cropped_listed(GPtrArray *entries, const char *error,
		void *data) {
	char *uri = data;
	for (guint i = 0; entries && g.viewing && i < entries->len; i++) {
		if (strcmp(((struct ph_entry *)entries->pdata[i])->uri, uri) == 0) {
			viewer_set_items(entries, i);
			break;
		}
	}
	g_free(uri);
}

static void crop_saved(const char *error, void *data) {
	char *path = data;
	g.saving = false;
	if (g.win == NULL) {
		g_free(path);
		return;
	}
	if (error) {
		crop_bar_update();
		message("The cropped picture wasn't saved", error);
		g_free(path);
		return;
	}
	crop_end();
	char *uri = g_filename_to_uri(path, NULL, NULL);
	char *parent = ph_parent_uri(uri);
	if (parent) {
		ph_list_folder(parent, false, NULL, cropped_listed, uri);
	} else {
		g_free(uri);
	}
	g_free(parent);
	g_free(path);
}

static void crop_save(void) {
	struct ph_entry *e = viewer_current();
	struct ph_picture *p = viewer_picture();
	int x, y, w, h;
	if (g.saving || e == NULL || p == NULL || p->state != PH_READY ||
			!viewer_crop_get(&x, &y, &w, &h)) {
		return;
	}
	char *path = g_filename_from_uri(e->uri, NULL, NULL);
	if (path == NULL) {
		message("The cropped picture wasn't saved", "Photos saves copies "
			"only of pictures on this PC.");
		return;
	}
	/* The same kind when glycin writes it; else PNG, or JPEG for kinds
	 * cameras and phones make */
	const char *mime = e->mime;
	bool same = mime && ph_can_encode(mime);
	if (!same) {
		mime = e->mime && (strcmp(e->mime, "image/heif") == 0 ||
			strcmp(e->mime, "image/avif") == 0 ||
			strcmp(e->mime, "image/jxl") == 0) ? "image/jpeg" : "image/png";
	}
	char *dest = crop_path(path, mime, same);
	g_free(path);
	if (dest == NULL) {
		return;
	}
	g.saving = true;
	crop_bar_update();
	ph_save(p->surface, x, y, w, h, 0, mime, dest, crop_saved, dest);
}

static void crop_bar_pressed(struct c8ui_widget *w, void *data) {
	if (w == g.crop_save) {
		crop_save();
	} else if (!g.saving) {
		crop_end();
	}
}

/* Set as: the picture as it shows, made into a screen-sized JPEG for
 * Start and the lock screen (background.h) */

#define BACKGROUND_SIDE 3840

static void background_saved(const char *error, void *data) {
	if (error) {
		message("The picture wasn't set", error);
	}
}

static void set_as_chosen(int choice, void *data) {
	struct ph_picture *p = viewer_picture();
	if (choice < 0 || p == NULL || p->state != PH_READY) {
		return;
	}
	for (int which = 0; which < 2; which++) {
		if (choice == which || choice == 2) {
			char *path = c8_background_path(which);
			ph_save(p->surface, 0, 0, p->width, p->height, BACKGROUND_SIDE,
				"image/jpeg", path, background_saved, NULL);
			g_free(path);
		}
	}
}

static void set_as(struct c8ui_widget *anchor) {
	struct ph_picture *p = viewer_picture();
	if (!g.viewing || p == NULL || p->state != PH_READY) {
		return;
	}
	static const char *const items[] = {
		"Start background", "Lock screen", "Both",
	};
	double x = anchor ? anchor->rect.x : c8ui_root_width(g.root) / 2;
	double y = anchor ? anchor->rect.y : c8ui_root_height(g.root) - 100;
	c8ui_menu_show(g.root, x, y, true, items, 3, set_as_chosen, NULL);
}

/* Slide show */

static void slideshow(void) {
	if (g.appbar) {
		c8ui_appbar_hide(g.appbar);
	}
	if (!g.viewing) {
		GPtrArray *pics = browse_pictures();
		if (pics->len == 0) {
			g_ptr_array_unref(pics);
			return;
		}
		int at = 0;
		struct ph_entry *sel = browse_selected();
		for (guint i = 0; sel && i < pics->len; i++) {
			if (pics->pdata[i] == sel) {
				at = i;
			}
		}
		show_viewer(pics, at);
		g_ptr_array_unref(pics);
	}
	viewer_slideshow(true);
}

/* Open a picture through the picker */

static void show_uris(char **uris);

static void opened_files(char **uris, void *data) {
	if (uris && uris[0]) {
		show_uris(uris);
	}
}

static void open_file(void) {
	static const struct c8ui_file_filter filters[] = {
		{ "Pictures", NULL, "image/*" },
		{ "All files", "*", NULL },
	};
	char *folder = browse_folder() ? g_filename_from_uri(browse_folder(),
		NULL, NULL) : NULL;
	c8ui_file_open(g.win, &(struct c8ui_file_options){
		.title = "Open pictures",
		.multiple = true,
		.filters = filters,
		.filter_count = 2,
		.folder_path = folder,
	}, opened_files, NULL);
	g_free(folder);
}

static void command(struct c8ui_widget *w, void *data) {
	switch ((enum command)GPOINTER_TO_INT(data)) {
	case CMD_DELETE:
		delete_picture();
		break;
	case CMD_COPY:
		copy_picture();
		break;
	case CMD_OPEN_WITH:
		open_with(w);
		break;
	case CMD_SHOW_FOLDER:
		show_in_folder();
		break;
	case CMD_DETAILS:
		show_details();
		break;
	case CMD_ROTATE_LEFT:
		rotate(-1);
		break;
	case CMD_ROTATE_RIGHT:
		rotate(1);
		break;
	case CMD_CROP:
		crop_begin();
		break;
	case CMD_SET_AS:
		set_as(w);
		break;
	case CMD_SLIDESHOW:
		slideshow();
		break;
	case CMD_BROWSE:
		show_browse();
		break;
	case CMD_OPEN:
		open_file();
		break;
	case CMD_REFRESH:
		browse_refresh();
		break;
	case CMD_BY_DATE:
	case CMD_BY_FOLDER:
		prefs.by_date = GPOINTER_TO_INT(data) == CMD_BY_DATE;
		prefs_save();
		if (g.appbar) {
			c8ui_appbar_hide(g.appbar);
		}
		browse_set_by_date(prefs.by_date);
		if (browse_list()) {
			c8ui_widget_grab_focus(browse_list());
		}
		break;
	case CMD_COUNT:
		break;
	}
}

/* Pages */

static void show_viewer(GPtrArray *items, int index) {
	crop_end();
	g.viewing = true;
	viewer_show(items, index);
	c8ui_stack_set(g.stack, 1, false);
	c8ui_widget_grab_focus(g.viewer);
	update_title();
	update_commands();
}

/* Back to the grid, at the folder of the picture shown */
static void show_browse(void) {
	struct ph_entry *e = g.viewing ? viewer_current() : NULL;
	crop_end();
	viewer_slideshow(false);
	if (e) {
		browse_select(e->uri);
	} else if (browse_folder() == NULL) {
		char *top = ph_pictures_uri();
		browse_set_folder(top, NULL);
		g_free(top);
	}
	bool was = g.viewing;
	g.viewing = false;
	if (g.appbar) {
		c8ui_appbar_hide(g.appbar);
	}
	c8ui_stack_set(g.stack, 0, was);
	if (browse_list()) {
		c8ui_widget_grab_focus(browse_list());
	}
	viewer_show(NULL, -1); // let the decoded pictures go
	update_title();
	update_commands();
}

static void browse_open(GPtrArray *pictures, int index) {
	show_viewer(pictures, index);
}

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

/* While cropping: Enter saves, Escape stops; the rest waits */
static bool crop_keys(const struct c8ui_event *ev) {
	switch (ev->sym) {
	case XKB_KEY_Escape:
		if (!g.saving) {
			crop_end();
		}
		return true;
	case XKB_KEY_Return:
	case XKB_KEY_KP_Enter:
		/* A focused button's own Enter came first */
		crop_save();
		return true;
	case XKB_KEY_Tab:
	case XKB_KEY_ISO_Left_Tab:
		return false;
	}
	viewer_crop_key(ev);
	return true;
}

static bool keys(const struct c8ui_event *ev, void *data) {
	bool ctrl = ev->mods & C8UI_MOD_CTRL, alt = ev->mods & C8UI_MOD_ALT;
	if (g.viewing && viewer_cropping()) {
		return crop_keys(ev);
	}
	switch (ev->sym) {
	case XKB_KEY_Escape:
		if (viewer_in_slideshow()) {
			viewer_slideshow(false);
			return true;
		}
		if (g.viewing) {
			show_browse();
			return true;
		}
		return false;
	case XKB_KEY_Left:
		if (alt) {
			if (g.viewing) {
				show_browse();
			} else {
				browse_up();
			}
			return true;
		}
		return false;
	case XKB_KEY_Up:
		if (alt && !g.viewing) {
			browse_up();
			return true;
		}
		return false;
	case XKB_KEY_BackSpace:
		if (!g.viewing) {
			browse_up();
			return true;
		}
		return false;
	case XKB_KEY_Delete:
	case XKB_KEY_KP_Delete:
		delete_picture();
		return true;
	case XKB_KEY_F5:
		slideshow();
		return true;
	case XKB_KEY_Return:
	case XKB_KEY_KP_Enter:
		if (alt) {
			show_details();
			return true;
		}
		return false;
	case XKB_KEY_Menu:
		toggle_appbar();
		return true;
	}
	if (ctrl) {
		switch (ev->base_sym) {
		case XKB_KEY_c:
			copy_picture();
			return true;
		case XKB_KEY_o:
			open_file();
			return true;
		case XKB_KEY_r:
		case XKB_KEY_period:
			rotate((ev->mods & C8UI_MOD_SHIFT) ? -1 : 1);
			return true;
		case XKB_KEY_comma:
			rotate(-1);
			return true;
		case XKB_KEY_e:
			crop_begin();
			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));
}

static void window_gone(struct c8ui_widget *w, void *data) {
	g.win = NULL;
	g.root = NULL;
	g.stack = g.browse = g.viewer = g.appbar = NULL;
	g.crop_bar = g.crop_ratio = g.crop_save = g.crop_cancel = NULL;
	memset(g.cmd, 0, sizeof(g.cmd));
	g.viewing = false;
}

static void make_window(void) {
	g.win = c8ui_window_new(g.app, "Photos", 1100, 720);
	c8ui_window_set_background(g.win, 0x1d1d1d, 1);
	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_picture = browse_open,
		.changed = browse_changed,
		.context = toggle_appbar,
	};
	g.browse = browse_new(&bh);
	c8ui_widget_add(g.stack, g.browse);
	browse_set_by_date(prefs.by_date);
	static const struct viewer_hooks vh = {
		.changed = viewer_changed,
		.context = toggle_appbar,
		.back = show_browse,
	};
	viewer_set_hooks(&vh);
	g.viewer = viewer_new();
	/* The viewer, with the crop bar under it while cropping */
	struct c8ui_widget *page = c8ui_box_new(C8UI_VERTICAL, 0);
	page->fill = true;
	page->expand = true;
	c8ui_widget_add(page, g.viewer);
	g.crop_bar = c8ui_box_new(C8UI_HORIZONTAL, 10);
	g.crop_bar->fill = true;
	g.crop_bar->hidden = true;
	c8ui_widget_set_background(g.crop_bar, 0x000000);
	c8ui_box_set_padding(g.crop_bar, 40, 16, 40, 20);
	c8ui_box_set_narrow_padding(g.crop_bar, 20, 12, 20, 16);
	g.crop_ratio = c8ui_button_new("Aspect ratio", ratio_menu, NULL);
	c8ui_widget_add(g.crop_bar, g.crop_ratio);
	struct c8ui_widget *gap = c8ui_box_new(C8UI_HORIZONTAL, 0);
	gap->expand = true;
	c8ui_widget_add(g.crop_bar, gap);
	g.crop_save = c8ui_button_new("Save a copy", crop_bar_pressed, NULL);
	c8ui_button_set_primary(g.crop_save, true);
	c8ui_widget_add(g.crop_bar, g.crop_save);
	g.crop_cancel = c8ui_button_new("Cancel", crop_bar_pressed, NULL);
	c8ui_widget_add(g.crop_bar, g.crop_cancel);
	c8ui_widget_add(page, g.crop_bar);
	c8ui_widget_add(g.stack, page);
	c8ui_root_set_child(g.root, g.stack);
	c8ui_root_set_key_handler(g.root, keys, NULL);
	c8ui_root_on_resize(g.root, resized, NULL);
	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_DELETE, "edit-delete", "Delete", false },
		{ CMD_COPY, "edit-copy", "Copy", false },
		{ CMD_OPEN_WITH, "document-open-with", "Open with", false },
		{ CMD_SHOW_FOLDER, "folder-open", "Show in folder", false },
		{ CMD_DETAILS, "document-properties", "Details", false },
		{ CMD_OPEN, "document-open", "Open", false },
		{ CMD_ROTATE_LEFT, "object-rotate-left", "Rotate left", true },
		{ CMD_ROTATE_RIGHT, "object-rotate-right", "Rotate right", true },
		{ CMD_CROP, "transform-crop", "Crop", true },
		{ CMD_SET_AS, "preferences-desktop-wallpaper", "Set as", true },
		{ CMD_SLIDESHOW, "view-presentation", "Slide show", true },
		{ CMD_REFRESH, "view-refresh", "Refresh", true },
		{ CMD_BY_DATE, "view-calendar", "By date", true },
		{ CMD_BY_FOLDER, "folder-open", "Folders", true },
		{ CMD_BROWSE, "view-grid", "All pictures", 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));
	}
	update_commands();
}

/* Charms */

static GPtrArray *searched(void) {
	return g.viewing ? viewer_items() : browse_entries();
}

static void search(struct c8ui_search *s, const char *query, void *data) {
	GPtrArray *items = searched();
	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 ph_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" : "image-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 = searched();
	for (guint i = 0; items && i < items->len; i++) {
		struct ph_entry *e = items->pdata[i];
		if (strcmp(e->uri, id) != 0) {
			continue;
		}
		if (g.viewing) {
			viewer_go(i);
		} else if (e->folder) {
			browse_set_by_date(false);
			browse_set_folder(e->uri, NULL);
		} else {
			GPtrArray *pics = ph_pictures_of(items);
			for (guint j = 0; j < pics->len; j++) {
				if (pics->pdata[j] == e) {
					show_viewer(pics, j);
				}
			}
			g_ptr_array_unref(pics);
		}
		break;
	}
	c8ui_window_present(g.win);
}

static const char *const wheel_items[] = {
	"Goes to the next picture", "Zooms",
};
static const int seconds[] = { 3, 5, 10, 20, 60 };
static const char *const seconds_items[] = {
	"3 seconds", "5 seconds", "10 seconds", "20 seconds", "A minute",
};

static void wheel_changed(struct c8ui_setting *s, void *data) {
	prefs.wheel = c8ui_setting_get_int(s) == 1 ? PH_WHEEL_ZOOM :
		PH_WHEEL_FLIP;
	prefs_save();
}

static void seconds_changed(struct c8ui_setting *s, void *data) {
	int i = c8ui_setting_get_int(s);
	if (i >= 0 && i < (int)G_N_ELEMENTS(seconds)) {
		prefs.slide_seconds = seconds[i];
		prefs_save();
	}
}

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

static void options(struct c8ui_settings_page *page, void *data) {
	struct c8ui_setting *s = c8ui_page_choice(page, "wheel",
		"The mouse wheel", wheel_items, 2,
		prefs.wheel == PH_WHEEL_ZOOM ? 1 : 0, wheel_changed, NULL);
	c8ui_setting_set_description(s, "Ctrl and the wheel always zoom");
	int sel = 1;
	for (size_t i = 0; i < G_N_ELEMENTS(seconds); i++) {
		if (seconds[i] == prefs.slide_seconds) {
			sel = i;
		}
	}
	c8ui_page_heading(page, "Slide show");
	c8ui_page_choice(page, "seconds", "Show each picture for",
		seconds_items, G_N_ELEMENTS(seconds_items), sel, seconds_changed,
		NULL);
	c8ui_page_toggle(page, "shuffle", "Shuffle", prefs.shuffle,
		shuffle_changed, NULL);
}

/* The app */

static void stealth_changed(void *data) {
	update_title();
	browse_stealth_changed();
}

static void startup(struct c8ui_app *app, void *data) {
	g.app = app;
	c8_stealth_watch(stealth_changed, NULL);
	prefs_load();
	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 picture opened is shown at once; its folder comes after */
static void siblings(GPtrArray *entries, const char *error, void *data) {
	char *uri = data;
	GPtrArray *items = viewer_items();
	struct ph_entry *e = viewer_current();
	if (entries && g.viewing && items && items->len == 1 && e &&
			strcmp(e->uri, uri) == 0) {
		for (guint i = 0; i < entries->len; i++) {
			if (strcmp(((struct ph_entry *)entries->pdata[i])->uri,
					uri) == 0) {
				viewer_set_items(entries, i);
				break;
			}
		}
	}
	g_free(uri);
}

static void show_uris(char **uris) {
	GPtrArray *items = g_ptr_array_new_with_free_func(
		(GDestroyNotify)ph_entry_unref);
	for (int i = 0; uris[i]; i++) {
		struct ph_entry *e = ph_entry_for(uris[i]);
		if (e->folder) {
			/* A folder: its grid */
			if (items->len == 0 && uris[i + 1] == NULL) {
				browse_set_by_date(false);
				browse_set_folder(e->uri, NULL);
				if (g.viewing) {
					g.viewing = false;
					viewer_show(NULL, -1);
					c8ui_stack_set(g.stack, 0, false);
				}
			}
			ph_entry_unref(e);
			continue;
		}
		g_ptr_array_add(items, e);
	}
	if (items->len > 0) {
		if (browse_folder() == NULL) {
			/* Back from the viewer goes to its folder */
			char *top = ph_pictures_uri();
			browse_set_folder(top, NULL);
			g_free(top);
		}
		show_viewer(items, 0);
		if (items->len == 1) {
			struct ph_entry *e = items->pdata[0];
			char *parent = ph_parent_uri(e->uri);
			if (parent) {
				ph_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 || browse_folder() == NULL) {
		char *top = ph_pictures_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) {
	c8ui_charms_destroy(g.charms);
}

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);
}
