/*
 * A Files window: places down the side, the folder as tiles or details,
 * commands in the app bar. A window has tabs (a strip over the folder
 * once there are two), and a tab shows one folder or two side by side
 * (split view), each a pane with its own header, history and selection;
 * the commands act on the pane used last. Pickers are the same window
 * with one pane and a band at the bottom (a name box when saving, the
 * filter, Open/Save, Cancel), opened over the app that asked.
 */
#define _GNU_SOURCE
#include <fnmatch.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include "files.h"
#include "stealth.h"

#define SIDE_WIDTH 280
#define TILE_W 150
#define TILE_H 160
#define ROW_H 40
#define PLACE_H 44
/* Narrow (a quarter of the screen): smaller tiles so three fit, and
 * details as two-line rows without the column headers */
#define NARROW_TILE_W 136
#define NARROW_TILE_H 150
#define NARROW_ROW_H 56
#define NARROW_PAD 16
#define SPLIT_PAD 24 // two panes side by side: less air round each
#define TAB_H 40
#define TAB_MAX_W 240
#define TAB_MIN_W 72
#define BUTTON_MIDDLE 0x112

enum {
	COL_NAME,
	COL_MODIFIED,
	COL_TYPE,
	COL_SIZE,
};

struct browser;
struct tab;

/* One folder shown: a tab has one, or two when split */
struct pane {
	struct browser *b;
	struct tab *tab;
	struct folder *folder;
	GPtrArray *history; // GFile: where Back goes
	char *search; // folded; NULL: everything
	/* After the next reload: select these names (keeping the selection),
	 * and maybe rename the one */
	GPtrArray *keep; // char *
	char *rename_next;
	bool restoring; // selecting keep: not a change of the user's

	struct c8ui_widget *main, *places_button, *back, *title, *crumbs;
	struct c8ui_widget *info, *columns, *list, *scroll, *empty;

	GFile *mount_tried; // the folder was not mounted: mounting it once
	bool mounting;
};

struct tab {
	struct browser *b;
	struct c8ui_widget *box; // in the window's stack: holds the pane(s)
	struct c8ui_widget *split; // NULL with one pane
	struct pane *pane[2];
	int active; // the pane the commands are for
};

struct browser {
	struct c8ui_window *win;
	struct c8ui_root *root;
	enum browser_mode mode;
	GPtrArray *tabs; // struct tab, in the strip's order
	int tab; // the one shown

	struct c8ui_widget *page, *places, *places_scroll;
	struct c8ui_widget *side, *right, *places_back;
	struct c8ui_widget *strip, *stack; // the tabs, and what they show
	int strip_hover; // the tab under the pointer, or -1
	bool strip_close; // on its close cross
	/* Narrow: one thing at a time, the folder or (places_open) the places */
	bool narrow, places_open;
	struct c8ui_widget *ops;
	struct c8ui_widget *bar;
	struct {
		struct c8ui_widget *open, *open_with, *props, *connect;
		struct c8ui_widget *copy, *cut, *rename, *trash, *restore,
			*erase, *pin, *paste, *new_folder, *select_all, *empty_trash,
			*details, *hidden, *new_tab, *split, *pin_folder;
		struct c8ui_widget *extract, *compress, *extract_all;
	} cmd;
	guint places_watch;

	/* Typed over the list: the start of a name to go to */
	GString *typed; // folded
	gint64 typed_at;

	/* A drag over the window: what it would land on, and what it holds */
	struct pane *drop_pane; // whose item drop_item is
	int drop_item, drop_place; // highlighted, or -1
	GList *drop_files; // GFile, read once per drag
	bool drop_read;
	char *drop_fs; // the filesystem the first of them is on
	bool drop_fs_read;
	GFile *fs_dir; // the last target's filesystem, asked once
	char *fs_id;

	/* Pickers */
	struct {
		bool multiple, folders, answered;
		GPtrArray *filters; // struct pick_filter
		int filter;
		struct c8ui_widget *name, *combo, *accept, *count, *cancel;
		struct c8ui_widget *band; // holds them in one row, or stacked
		pick_fn done;
		void *data;
	} pick;
};

static GList *browsers; // newest first

static void update(struct pane *p);
static void update_selection(struct pane *p);
static void browser_rename(struct pane *p);
static void show_folder(struct pane *p, GFile *dir, bool remember);
static void arrange(struct browser *b);
static void tabs_changed(struct browser *b);
static void stealth_changed(void *data);

/* Panes */

static struct tab *cur_tab(struct browser *b) {
	return b->tabs->pdata[b->tab];
}

/* The pane the commands, keys and places act on */
static struct pane *cur(struct browser *b) {
	struct tab *t = cur_tab(b);
	return t->pane[t->active];
}

/* Every pane of the window, shown or not; unref it after */
static GPtrArray *all_panes(struct browser *b) {
	GPtrArray *panes = g_ptr_array_new();
	for (guint i = 0; i < b->tabs->len; i++) {
		struct tab *t = b->tabs->pdata[i];
		for (int j = 0; j < 2; j++) {
			if (t->pane[j]) {
				g_ptr_array_add(panes, t->pane[j]);
			}
		}
	}
	return panes;
}

static bool is_inside(struct c8ui_widget *w, struct c8ui_widget *of) {
	for (; w; w = w->parent) {
		if (w == of) {
			return true;
		}
	}
	return false;
}

/* Filters */

void pick_filter_free(gpointer data) {
	struct pick_filter *f = data;
	g_free(f->name);
	g_ptr_array_unref(f->globs);
	g_ptr_array_unref(f->mimes);
	free(f);
}

static bool pick_filter_matches(const struct pick_filter *f, struct entry *e) {
	for (guint i = 0; i < f->globs->len; i++) {
		/* Shell patterns, sets too: GTK apps and Firefox send
		 * "*.[jJ][pP][gG]", which GPatternSpec reads letter by letter and
		 * so never matched. Case-blind besides: "*.JPG" is a JPEG too. */
		if (fnmatch(f->globs->pdata[i], e->name, FNM_CASEFOLD) == 0) {
			return true;
		}
	}
	for (guint i = 0; e->mime && i < f->mimes->len; i++) {
		const char *m = f->mimes->pdata[i];
		size_t n = strlen(m);
		if (n >= 2 && strcmp(m + n - 2, "/*") == 0) {
			if (strncmp(e->mime, m, n - 1) == 0) {
				return true; // "image/*"
			}
		} else if (g_content_type_is_a(e->mime, m)) {
			return true;
		}
	}
	return false;
}

static bool shown_filter(struct entry *e, void *data) {
	struct pane *p = data;
	struct browser *b = p->b;
	if (p->search) {
		char *folded = g_utf8_casefold(e->name, -1);
		bool hit = strstr(folded, p->search) != NULL;
		g_free(folded);
		if (!hit) {
			return false;
		}
	}
	if (e->dir || b->mode == MODE_BROWSE) {
		return true;
	}
	if (b->pick.folders) {
		return false;
	}
	if (b->pick.filters && b->pick.filter >= 0 &&
			b->pick.filter < (int)b->pick.filters->len) {
		return pick_filter_matches(b->pick.filters->pdata[b->pick.filter], e);
	}
	return true;
}

/* Selection */

static GList *selected_files(struct pane *p) {
	GList *files = NULL;
	struct folder *f = p->folder;
	for (int i = (int)f->shown->len - 1; i >= 0; i--) {
		if (c8ui_list_is_selected(p->list, i)) {
			struct entry *e = f->shown->pdata[i];
			files = g_list_prepend(files, g_object_ref(e->file));
		}
	}
	return files;
}

static struct entry *selected_entry(struct pane *p) {
	int i = c8ui_list_get_selected(p->list);
	return i >= 0 && i < (int)p->folder->shown->len ?
		p->folder->shown->pdata[i] : NULL;
}

static void keep_selection(struct pane *p) {
	g_ptr_array_set_size(p->keep, 0);
	for (guint i = 0; i < p->folder->shown->len; i++) {
		if (c8ui_list_is_selected(p->list, i)) {
			struct entry *e = p->folder->shown->pdata[i];
			g_ptr_array_add(p->keep, g_file_get_basename(e->file));
		}
	}
}

static bool in_trash(struct pane *p) {
	return g_file_has_uri_scheme(p->folder->dir, "trash");
}

/* Inside an archive: looked at, never changed */
static bool in_archive(struct pane *p) {
	return g_file_has_uri_scheme(p->folder->dir, "archive");
}

/* Every selected one is an archive to extract */
static bool selected_archives(struct pane *p) {
	struct folder *f = p->folder;
	bool any = false;
	for (guint i = 0; i < f->shown->len; i++) {
		if (!c8ui_list_is_selected(p->list, i)) {
			continue;
		}
		struct entry *e = f->shown->pdata[i];
		if (e->dir || !arc_is(e->mime)) {
			return false;
		}
		any = true;
	}
	return any;
}

/* The type the selected files share, if they are files of one type */
static const char *selected_type(struct pane *p) {
	const char *mime = NULL;
	struct folder *f = p->folder;
	for (guint i = 0; i < f->shown->len; i++) {
		if (!c8ui_list_is_selected(p->list, i)) {
			continue;
		}
		struct entry *e = f->shown->pdata[i];
		if (e->dir || e->mime == NULL ||
				(mime && strcmp(mime, e->mime) != 0)) {
			return NULL;
		}
		mime = e->mime;
	}
	return mime;
}

/* Drawing items */

static void draw_tile(struct pane *p, cairo_t *cr,
		const struct c8ui_list_item *item, struct entry *e) {
	cairo_surface_t *thumb = entry_thumbnail(e);
	if (thumb == NULL) {
		c8ui_list_draw_text(p->list, cr, item, entry_icon(e),
			c8_stealth_show(e->name), NULL);
		return;
	}
	/* The picture where the icon goes, the name under it as for icons */
	const char *family = c8ui_widget_font(p->list);
	double tw, th;
	c8ui_text_size(family, c8ui_text_font(C8UI_TEXT_BODY), "Ag", 0, 0, &tw,
		&th);
	const struct c8ui_rect *r = &item->rect;
	double pad = 8;
	double size = r->height - th - 3 * pad;
	if (size > r->width - 2 * pad) {
		size = r->width - 2 * pad;
	}
	double w = cairo_image_surface_get_width(thumb);
	double h = cairo_image_surface_get_height(thumb);
	double s = size / (w > h ? w : h);
	double x = r->x + (r->width - w * s) / 2;
	double y = r->y + pad + (size - h * s) / 2;
	/* At this size once, then copied: a folder of photos scrolls */
	c8ui_draw_surface(cr, thumb, x, y, w * s, h * s);
	c8ui_list_draw_text(p->list, cr, item, NULL, c8_stealth_show(e->name),
		NULL);
}

/* Narrow: the name, and under it when and how big, across the row */
static void draw_narrow_row(struct pane *p, cairo_t *cr,
		const struct c8ui_list_item *item, struct entry *e) {
	const struct c8ui_rect *r = &item->rect;
	double icon = 32, pad = 8;
	/* After the row's check box */
	double left = r->x + C8UI_LIST_CHECK_WIDTH;
	struct c8ui_icon *i = entry_icon(e);
	if (i) {
		c8ui_icon_draw_fit(cr, i, left + icon / 2, r->y + r->height / 2,
			icon);
	}
	const char *family = c8ui_widget_font(p->list);
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY);
	struct c8ui_font small = c8ui_text_font(C8UI_TEXT_CAPTION);
	double tw, th, sw, sh;
	c8ui_text_size(family, font, "Ag", 0, 0, &tw, &th);
	c8ui_text_size(family, small, "Ag", 0, 0, &sw, &sh);
	double tx = left + icon + 12;
	double room = r->x + r->width - pad - tx;
	room = room > 1 ? room : 1;
	double y = r->y + (r->height - th - sh - 2) / 2;
	c8ui_set_source(cr, item->fg, 1);
	c8ui_text_draw(cr, family, font, c8_stealth_show(e->name), tx, y, room,
		1);
	const char *when = entry_when(e);
	char *line = e->dir ? g_strdup(when) :
		g_strdup_printf("%s · %s", when, entry_size(e));
	c8ui_set_source(cr, item->fg, item->secondary);
	c8ui_text_draw(cr, family, small, line, tx, y + th + 2, room, 1);
	g_free(line);
}

static void draw_row(struct pane *p, cairo_t *cr,
		const struct c8ui_list_item *item, struct entry *e) {
	if (p->b->narrow) {
		draw_narrow_row(p, cr, item, e);
		return;
	}
	double x, width;
	c8ui_columns_get(p->columns, COL_NAME, &x, &width);
	const struct c8ui_rect *r = &item->rect;
	double icon = 24, pad = 8;
	/* The name starts after the row's check box */
	double left = r->x + x + C8UI_LIST_CHECK_WIDTH;
	struct c8ui_icon *i = entry_icon(e);
	if (i) {
		c8ui_icon_draw_fit(cr, i, left + icon / 2, r->y + r->height / 2,
			icon);
	}
	const char *family = c8ui_widget_font(p->list);
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY);
	double tw, th;
	c8ui_text_size(family, font, "Ag", 0, 0, &tw, &th);
	double tx = left + icon + 10;
	double room = r->x + x + width - pad - tx;
	c8ui_set_source(cr, item->fg, 1);
	c8ui_text_draw(cr, family, font, c8_stealth_show(e->name), tx,
		r->y + (r->height - th) / 2,
		room > 1 ? room : 1, 1);

	c8ui_columns_draw_cell(p->columns, cr, item, COL_MODIFIED, entry_when(e),
		true);
	c8ui_columns_draw_cell(p->columns, cr, item, COL_TYPE, e->type, true);
	if (!e->dir) {
		c8ui_columns_draw_cell(p->columns, cr, item, COL_SIZE, entry_size(e),
			true);
	}
}

/* What a drop would land on */
static void draw_drop_outline(cairo_t *cr, const struct c8ui_rect *r) {
	c8ui_set_source(cr, c8ui_app_theme(files_app())->accent, 1);
	cairo_set_line_width(cr, 2);
	cairo_rectangle(cr, r->x + 1, r->y + 1, r->width - 2, r->height - 2);
	cairo_stroke(cr);
}

static void draw_item(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	struct pane *p = data;
	if (item->index >= (int)p->folder->shown->len) {
		return;
	}
	struct entry *e = p->folder->shown->pdata[item->index];
	if (prefs.details) {
		draw_row(p, cr, item, e);
	} else {
		draw_tile(p, cr, item, e);
	}
	if (p == p->b->drop_pane && item->index == p->b->drop_item) {
		draw_drop_outline(cr, &item->rect);
	}
}

/* Shows prefs; called whenever they change */
static void pane_apply_prefs(struct pane *p) {
	struct browser *b = p->b;
	bool details = prefs.details;
	p->columns->hidden = !details || b->narrow;
	if (details) {
		c8ui_list_set_mode(p->list, C8UI_LIST_ROWS, 0,
			b->narrow ? NARROW_ROW_H : ROW_H);
	} else if (b->narrow) {
		c8ui_list_set_mode(p->list, C8UI_LIST_GRID, NARROW_TILE_W,
			NARROW_TILE_H);
	} else {
		c8ui_list_set_mode(p->list, C8UI_LIST_GRID, TILE_W, TILE_H);
	}
	c8ui_columns_set_sort(p->columns, (int)prefs.sort, prefs.descending);
	struct folder *f = p->folder;
	if (f && (f->show_hidden != prefs.show_hidden || f->sort != prefs.sort ||
			f->descending != prefs.descending)) {
		f->show_hidden = prefs.show_hidden;
		f->sort = prefs.sort;
		f->descending = prefs.descending;
		folder_update_view(f);
	}
	c8ui_list_redraw(p->list); // thumbnails on or off
}

static void apply_prefs(struct browser *b) {
	GPtrArray *panes = all_panes(b);
	for (guint i = 0; i < panes->len; i++) {
		pane_apply_prefs(panes->pdata[i]);
	}
	g_ptr_array_unref(panes);
	c8ui_appbar_command_set_toggle(b->cmd.details, prefs.details);
	c8ui_appbar_command_set_toggle(b->cmd.hidden, prefs.show_hidden);
	c8ui_widget_queue_layout(b->page);
}

void browsers_apply_prefs(void) {
	for (GList *l = browsers; l; l = l->next) {
		apply_prefs(l->data);
	}
}

/* Places */

static void draw_place(struct c8ui_widget *list, cairo_t *cr,
		const struct c8ui_list_item *item, void *data) {
	GPtrArray *places = places_get();
	if (item->index >= (int)places->len) {
		return;
	}
	struct place *p = places->pdata[item->index];
	const struct c8ui_rect *r = &item->rect;
	const char *family = c8ui_widget_font(list);
	if (p->kind == PLACE_HEADING) {
		struct c8ui_font font = c8ui_text_font(C8UI_TEXT_CAPTION);
		double tw, th;
		c8ui_text_size(family, font, p->name, 0, 0, &tw, &th);
		c8ui_set_source(cr, item->fg, item->secondary);
		c8ui_text_draw(cr, family, font, c8_stealth_show(p->name), r->x + 24,
			r->y + r->height - th - 6, r->width - 48, 1);
		return;
	}
	struct c8ui_icon *icon = p->icon ? icon_named(p->icon) : NULL;
	double x = r->x + 24;
	if (icon) {
		c8ui_icon_draw_fit(cr, icon, x + 12, r->y + r->height / 2, 24);
	}
	struct browser *b = data;
	if (item->index == b->drop_place) {
		draw_drop_outline(cr, r);
	}
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY);
	double tw, th;
	c8ui_text_size(family, font, "Ag", 0, 0, &tw, &th);
	c8ui_set_source(cr, item->fg, 1);
	c8ui_text_draw(cr, family, font, c8_stealth_show(p->name), x + 36,
		r->y + (r->height - th) / 2, r->width - x - 36 - 16 + r->x, 1);
}

static void select_place(struct browser *b) {
	c8ui_list_set_count(b->places, places_get()->len);
	/* In an archive: the place the archive is in */
	GFile *dir = cur(b)->folder->dir, *archive = arc_file(dir);
	c8ui_list_select(b->places, places_find(archive ? archive : dir));
	g_clear_object(&archive);
}

static void places_changed(void *data) {
	struct browser *b = data;
	select_place(b);
	/* Pin this folder comes and goes with them */
	update(cur(b));
}

struct mount_wait {
	struct pane *p; // checked against the open ones
	GVolume *volume;
};

static bool alive(struct browser *b) {
	return g_list_find(browsers, b) != NULL;
}

/* A pane goes with its tab or its window, whatever was asked for it */
static bool pane_alive(struct pane *p) {
	bool found = false;
	for (GList *l = browsers; l && !found; l = l->next) {
		GPtrArray *panes = all_panes(l->data);
		found = g_ptr_array_find(panes, p, NULL);
		g_ptr_array_unref(panes);
	}
	return found;
}

static void info(struct pane *p, enum c8ui_severity severity,
		const char *title, const char *message) {
	c8ui_infobar_set(p->info, severity, title, message);
	p->info->hidden = false;
	c8ui_widget_queue_layout(p->main);
}

static void mounted(GObject *source, GAsyncResult *result, gpointer data) {
	struct mount_wait *w = data;
	GError *error = NULL;
	bool ok = g_volume_mount_finish(G_VOLUME(source), result, &error);
	if (pane_alive(w->p)) {
		if (ok) {
			GMount *m = g_volume_get_mount(w->volume);
			if (m) {
				GFile *root = g_mount_get_root(m);
				show_folder(w->p, root, true);
				g_object_unref(root);
				g_object_unref(m);
			}
		} else if (!g_error_matches(error, G_IO_ERROR,
				G_IO_ERROR_FAILED_HANDLED)) {
			info(w->p, C8UI_SEVERITY_ERROR, "Couldn't open the drive",
				error->message);
		}
	}
	g_clear_error(&error);
	g_object_unref(w->volume);
	free(w);
}

static void show_places(struct browser *b, bool open);
static void reveal_in(struct pane *p, GFile *file);
static struct tab *tab_new(struct browser *b, GFile *dir, int at);
static void tab_show(struct browser *b, int index);

static void open_place(struct c8ui_widget *list, int index, void *data) {
	struct browser *b = data;
	GPtrArray *places = places_get();
	if (index < 0 || index >= (int)places->len) {
		return;
	}
	struct place *p = places->pdata[index];
	if (p->kind == PLACE_HEADING) {
		select_place(b);
		return;
	}
	if (b->places_open) {
		show_places(b, false); // narrow: back to the folder
	}
	if (p->is_file) {
		if (b->mode == MODE_BROWSE) {
			char *uri = g_file_get_uri(p->file);
			c8ui_window_open_uri(b->win, uri);
			g_free(uri);
		} else {
			/* A picker: there it is, to choose */
			reveal_in(cur(b), p->file);
		}
		select_place(b);
	} else if (p->file) {
		show_folder(cur(b), p->file, true);
	} else if (p->volume) {
		struct mount_wait *w = calloc(1, sizeof(*w));
		w->p = cur(b);
		w->volume = g_object_ref(p->volume);
		GMountOperation *op = g_mount_operation_new();
		g_volume_mount(p->volume, G_MOUNT_MOUNT_NONE, op, NULL, mounted, w);
		g_object_unref(op);
	}
}

static void ejected(GObject *source, GAsyncResult *result, gpointer data) {
	GError *error = NULL;
	bool ok = G_IS_MOUNT(source) ?
		(g_mount_can_eject(G_MOUNT(source)) ?
			g_mount_eject_with_operation_finish(G_MOUNT(source), result,
				&error) :
			g_mount_unmount_with_operation_finish(G_MOUNT(source), result,
				&error)) :
		g_volume_eject_with_operation_finish(G_VOLUME(source), result, &error);
	if (!ok) {
		fprintf(stderr, "c8-files: eject: %s\n", error->message);
		g_error_free(error);
	}
}

static void eject(struct place *p) {
	if (p->mount && g_mount_can_eject(p->mount)) {
		g_mount_eject_with_operation(p->mount, G_MOUNT_UNMOUNT_NONE, NULL,
			NULL, ejected, NULL);
	} else if (p->mount) {
		g_mount_unmount_with_operation(p->mount, G_MOUNT_UNMOUNT_NONE, NULL,
			NULL, ejected, NULL);
	} else if (p->volume) {
		g_volume_eject_with_operation(p->volume, G_MOUNT_UNMOUNT_NONE, NULL,
			NULL, ejected, NULL);
	}
}

enum place_action {
	PLACE_OPEN,
	PLACE_NEW_TAB,
	PLACE_NEW_WINDOW,
	PLACE_SHOW, // a pinned file, in its folder
	PLACE_UNPIN,
	PLACE_EJECT,
};

struct place_menu {
	struct browser *b;
	GFile *file; // the place's, to know it is still that one
	int index;
	enum place_action actions[6];
};

static void place_chosen(int choice, void *data) {
	struct place_menu *m = data;
	GPtrArray *places = places_get();
	struct place *p = m->index < (int)places->len ?
		places->pdata[m->index] : NULL;
	/* The places may have changed under the menu */
	bool same = p && (p->file == NULL) == (m->file == NULL) &&
		(p->file == NULL || g_file_equal(p->file, m->file));
	if (choice >= 0 && alive(m->b) && same) {
		struct browser *b = m->b;
		switch (m->actions[choice]) {
		case PLACE_OPEN:
			open_place(b->places, m->index, b);
			break;
		case PLACE_NEW_TAB:
			tab_new(b, p->file, b->tab + 1);
			tab_show(b, b->tab + 1);
			break;
		case PLACE_NEW_WINDOW:
			browser_present(browser_new(p->file));
			break;
		case PLACE_SHOW:
			reveal_in(cur(b), p->file);
			break;
		case PLACE_UNPIN:
			places_unpin(p->file); // p goes with the list
			break;
		case PLACE_EJECT:
			eject(p);
			break;
		}
	}
	if (alive(m->b)) {
		select_place(m->b);
	}
	g_clear_object(&m->file);
	free(m);
}

static void place_context(struct c8ui_widget *list, int index, double x,
		double y, void *data) {
	struct browser *b = data;
	GPtrArray *places = places_get();
	if (index < 0 || index >= (int)places->len) {
		return;
	}
	struct place *p = places->pdata[index];
	if (p->kind == PLACE_HEADING) {
		return;
	}
	struct place_menu *m = calloc(1, sizeof(*m));
	m->b = b;
	m->index = index;
	m->file = p->file ? g_object_ref(p->file) : NULL;
	const char *items[6];
	int count = 0;
	bool browse = b->mode == MODE_BROWSE;
#define ITEM(label, action) \
	(items[count] = (label), m->actions[count++] = (action))
	ITEM("Open", PLACE_OPEN);
	if (p->is_file) {
		ITEM("Show in its folder", PLACE_SHOW);
	} else if (browse && p->file) {
		ITEM("Open in new tab", PLACE_NEW_TAB);
		ITEM("Open in new window", PLACE_NEW_WINDOW);
	}
	if (p->pinned) {
		ITEM("Unpin", PLACE_UNPIN);
	}
	if (p->can_eject) {
		ITEM("Eject", PLACE_EJECT);
	}
#undef ITEM
	c8ui_menu_show(b->root, x, y, false, items, count, place_chosen, m);
}

/* The folder */

/* p is the one in use now: its tab's commands, title and place follow */
static void activate(struct pane *p) {
	struct browser *b = p->b;
	struct tab *t = p->tab;
	int index = t->pane[1] == p ? 1 : 0;
	if (t->active == index) {
		return;
	}
	t->active = index;
	if (t == cur_tab(b)) {
		tabs_changed(b);
	}
}

static void crumb_clicked(struct c8ui_widget *link, void *data) {
	struct pane *p = data;
	GFile *dir = link->user_data;
	activate(p);
	if (dir && !g_file_equal(dir, p->folder->dir)) {
		GFile *go = g_object_ref(dir); // the link goes with the crumbs
		show_folder(p, go, true);
		g_object_unref(go);
	}
}

static void crumb_gone(struct c8ui_widget *w, void *data) {
	g_clear_object((GFile **)&w->user_data);
}

/* Place › folder › folder, each a link back up */
static void build_crumbs(struct pane *pane) {
	c8ui_widget_clear(pane->crumbs);
	GFile *dir = pane->folder->dir;
	/* In an archive the way up goes on from its top to the folder the
	 * archive is in */
	GFile *outer = arc_file(dir);
	int pi = places_find(outer ? outer : dir);
	struct place *p = pi >= 0 ? places_get()->pdata[pi] : NULL;
	GList *chain = NULL;
	for (GFile *f = g_object_ref(dir); f;) {
		chain = g_list_prepend(chain, f);
		if (p && g_file_equal(f, p->file)) {
			break;
		}
		GFile *parent = g_file_get_parent(f);
		if (parent == NULL && outer) {
			parent = g_file_get_parent(outer);
			g_clear_object(&outer);
		}
		f = parent;
	}
	g_clear_object(&outer);
	/* Narrow or split: only the last two, after a … that goes to the one
	 * before */
	int len = g_list_length(chain), at = 0;
	bool tight = pane->b->narrow || pane->tab->split;
	int first = tight && len > 2 ? len - 2 : 0;
	for (GList *l = chain; l; l = l->next, at++) {
		GFile *f = l->data;
		if (at < first - 1) {
			continue;
		}
		if (at == first - 1) {
			struct c8ui_widget *link = c8ui_link_new("…", crumb_clicked, pane);
			link->user_data = g_object_ref(f);
			link->on_destroy = crumb_gone;
			c8ui_widget_add(pane->crumbs, link);
			continue;
		}
		/* Outside any place the chain starts at / : say so plainly */
		char *name = p && g_file_equal(f, p->file) ? g_strdup(p->name) :
			l == chain ? g_file_get_parse_name(f) : folder_title_real(f);
		char *real = name;
		name = c8_stealth_text(real);
		g_free(real);
		if (at > 0) {
			struct c8ui_widget *sep = c8ui_label_new("›", C8UI_TEXT_BODY);
			c8ui_label_set_color(sep, C8UI_COLOR_SECONDARY);
			c8ui_widget_add(pane->crumbs, sep);
		}
		if (l->next) {
			struct c8ui_widget *link = c8ui_link_new(name, crumb_clicked, pane);
			link->user_data = g_object_ref(f);
			link->on_destroy = crumb_gone;
			c8ui_widget_add(pane->crumbs, link);
		} else {
			struct c8ui_widget *here = c8ui_label_new(name, C8UI_TEXT_BODY);
			c8ui_label_set_color(here, C8UI_COLOR_SECONDARY);
			c8ui_widget_add(pane->crumbs, here);
		}
		g_free(name);
	}
	g_list_free_full(chain, g_object_unref);
}

static void folder_changed(struct folder *f, void *data) {
	struct pane *p = data;
	p->restoring = true;
	c8ui_list_set_count(p->list, f->shown->len);
	c8ui_list_select_all(p->list, false);
	int first = -1;
	if (p->keep->len > 0) {
		/* By name, as folder_find does, but looking each one up in turn
		 * is slow when a few thousand are selected */
		GHashTable *names = g_hash_table_new_full(g_str_hash, g_str_equal,
			g_free, NULL);
		for (guint i = f->shown->len; i-- > 0;) { // the first one wins
			struct entry *e = f->shown->pdata[i];
			g_hash_table_replace(names, g_strdup(e->name),
				GUINT_TO_POINTER(i));
			char *base = g_file_get_basename(e->file);
			if (base) {
				g_hash_table_replace(names, base, GUINT_TO_POINTER(i));
			}
		}
		for (guint i = 0; i < p->keep->len; i++) {
			gpointer at;
			if (g_hash_table_lookup_extended(names, p->keep->pdata[i], NULL,
					&at)) {
				int index = GPOINTER_TO_UINT(at);
				c8ui_list_set_selected(p->list, index, true);
				first = first < 0 ? index : first;
			}
		}
		g_hash_table_destroy(names);
	}
	if (first >= 0) {
		c8ui_list_reveal(p->list, first);
	}
	p->restoring = false;
	if (p->rename_next) {
		int index;
		if (folder_find(f, p->rename_next, &index)) {
			g_clear_pointer(&p->rename_next, g_free);
			c8ui_list_select(p->list, index);
			c8ui_list_reveal(p->list, index);
			c8ui_appbar_hide(p->b->bar);
			browser_rename(p);
		}
	}
	update(p);
}

static void folder_redraw(struct folder *f, void *data) {
	struct pane *p = data;
	c8ui_list_redraw(p->list);
}

/* An archive is mounted to be looked into: let it go when the last pane
 * showing it has left (but: the pane leaving now) */
static void archive_left(GFile *was, struct pane *but) {
	GFile *archive = arc_file(was);
	if (archive == NULL) {
		return;
	}
	bool used = false;
	for (GList *l = browsers; l && !used; l = l->next) {
		GPtrArray *panes = all_panes(l->data);
		for (guint i = 0; i < panes->len && !used; i++) {
			struct pane *p = panes->pdata[i];
			GFile *theirs = p != but && p->folder ?
				arc_file(p->folder->dir) : NULL;
			used = theirs && g_file_equal(theirs, archive);
			g_clear_object(&theirs);
		}
		g_ptr_array_unref(panes);
	}
	if (!used) {
		GMount *mount = g_file_find_enclosing_mount(was, NULL, NULL);
		if (mount) {
			g_mount_unmount_with_operation(mount, G_MOUNT_UNMOUNT_NONE, NULL,
				NULL, NULL, NULL);
			g_object_unref(mount);
		}
	}
	g_object_unref(archive);
}

static void show_folder(struct pane *p, GFile *dir, bool remember) {
	g_clear_object(&p->mount_tried); // somewhere else: may try again
	if (p->folder && g_file_equal(dir, p->folder->dir)) {
		return;
	}
	if (p->folder) {
		GFile *in = arc_file(p->folder->dir), *to = arc_file(dir);
		if (in && !(to && g_file_equal(in, to))) {
			archive_left(p->folder->dir, p);
		}
		g_clear_object(&in);
		g_clear_object(&to);
		if (remember) {
			g_ptr_array_add(p->history, g_object_ref(p->folder->dir));
		}
		/* Coming back up selects the folder we were in */
		g_ptr_array_set_size(p->keep, 0);
		GFile *parent = g_file_get_parent(p->folder->dir);
		if (parent && g_file_equal(parent, dir)) {
			g_ptr_array_add(p->keep, g_file_get_basename(p->folder->dir));
		}
		g_clear_object(&parent);
		folder_free(p->folder);
	}
	g_clear_pointer(&p->search, g_free);
	p->folder = folder_new(dir, folder_changed, folder_redraw, p);
	p->folder->show_hidden = prefs.show_hidden;
	p->folder->sort = prefs.sort;
	p->folder->descending = prefs.descending;
	p->folder->filter = shown_filter;
	p->folder->filter_data = p;
	c8ui_list_set_count(p->list, 0);
	c8ui_scroll_to(p->scroll, 0);
	char *title = folder_title(dir);
	c8ui_label_set_text(p->title, title);
	g_free(title);
	build_crumbs(p);
	p->back->hidden = p->history->len == 0;
	p->info->hidden = true;
	tabs_changed(p->b); // the tab's name; the window's and the place too
}

static void browser_go(struct pane *p, GFile *dir) {
	show_folder(p, dir, true);
}

GFile *browser_folder(struct browser *b) {
	return cur(b)->folder->dir;
}

static void reveal_in(struct pane *p, GFile *file) {
	GFile *parent = g_file_get_parent(file);
	if (parent == NULL) {
		show_folder(p, file, true);
		return;
	}
	bool there = g_file_equal(parent, p->folder->dir);
	show_folder(p, parent, true);
	g_ptr_array_set_size(p->keep, 0);
	g_ptr_array_add(p->keep, g_file_get_basename(file));
	g_object_unref(parent);
	if (there) {
		folder_changed(p->folder, p); // already read: select it now
	}
}

void browser_reveal(struct browser *b, GFile *file) {
	reveal_in(cur(b), file);
}

void browser_select_too(struct browser *b, GFile *file) {
	struct pane *p = cur(b);
	g_ptr_array_add(p->keep, g_file_get_basename(file));
}

static void go_back(struct c8ui_widget *w, void *data) {
	struct pane *p = data;
	activate(p);
	if (p->history->len == 0) {
		return;
	}
	GFile *dir = g_object_ref(p->history->pdata[p->history->len - 1]);
	g_ptr_array_remove_index(p->history, p->history->len - 1);
	show_folder(p, dir, false);
	g_object_unref(dir);
}

static void go_up(struct pane *p) {
	GFile *parent = g_file_get_parent(p->folder->dir);
	if (parent) {
		show_folder(p, parent, true);
		g_object_unref(parent);
		return;
	}
	/* Out of an archive's top: its folder, the archive selected */
	GFile *archive = arc_file(p->folder->dir);
	if (archive) {
		reveal_in(p, archive);
		g_object_unref(archive);
	}
}

void browser_search(struct browser *b, const char *query) {
	struct pane *p = cur(b);
	g_clear_pointer(&p->search, g_free);
	if (query && query[0]) {
		p->search = g_utf8_casefold(query, -1);
	}
	folder_update_view(p->folder);
}

/* What the app bar and band show for the selection */

static void update_selection(struct pane *p) {
	struct browser *b = p->b;
	if (p != cur(b)) {
		return; // the bar is the other pane's
	}
	int n = c8ui_list_selected_count(p->list);
	struct entry *one = n == 1 ? selected_entry(p) : NULL;
	bool trash = in_trash(p);
	bool packed = in_archive(p);
	bool browse = b->mode == MODE_BROWSE;
	/* Where files are plain files: a new one can be made beside them */
	bool plain = browse && !trash && g_file_is_native(p->folder->dir);
	b->cmd.open->hidden = !(browse && one && !one->dir);
	b->cmd.open_with->hidden = !(browse && n > 0 && !trash &&
		selected_type(p) != NULL);
	b->cmd.extract->hidden = !(plain && n > 0 && selected_archives(p));
	b->cmd.compress->hidden = !(plain && n > 0);
	b->cmd.pin->hidden = !(browse && n > 0 && !trash && !packed);
	b->cmd.props->hidden = !(browse && n > 0);
	b->cmd.copy->hidden = !(browse && n > 0 && !trash);
	b->cmd.cut->hidden = !(browse && n > 0 && !trash && !packed);
	b->cmd.rename->hidden = !(browse && one && !trash && !packed);
	b->cmd.trash->hidden = !(browse && n > 0 && !trash && !packed);
	b->cmd.restore->hidden = !(browse && n > 0 && trash);
	b->cmd.erase->hidden = !(browse && n > 0 && trash);
	if (b->mode == MODE_OPEN) {
		bool ok = b->pick.folders ? (n == 0 || (one && one->dir)) :
			n > 0;
		/* Folders open by going in, unless folders are what's picked */
		for (int i = 0; ok && !b->pick.folders && i < (int)p->folder->shown->len;
				i++) {
			struct entry *e = p->folder->shown->pdata[i];
			if (e->dir && c8ui_list_is_selected(p->list, i)) {
				ok = false;
			}
		}
		b->pick.accept->disabled = !ok;
		char text[64] = "";
		if (n > 1) {
			snprintf(text, sizeof(text), "%d selected", n);
		}
		c8ui_label_set_text(b->pick.count, text);
	} else if (b->mode == MODE_SAVE && one && !one->dir) {
		c8ui_entry_set(b->pick.name, one->name);
	}
	c8ui_widget_queue_layout(b->bar);
	c8ui_widget_queue_draw(b->page);
}

static bool in_network(struct pane *p) {
	return g_file_has_uri_scheme(p->folder->dir, "network");
}

static void folder_mounted(bool ok, const char *error, void *data) {
	struct pane *p = data;
	if (!pane_alive(p)) {
		return;
	}
	p->mounting = false;
	if (ok) {
		folder_reload(p->folder);
	} else {
		bool packed = in_archive(p);
		c8ui_label_set_text(p->empty, packed ? "Not opened." :
			"Not connected.");
		info(p, C8UI_SEVERITY_ERROR, packed ? "Couldn't open the archive" :
			"Couldn't connect", error ? error : packed ?
			"It can't be looked into. Extracting it may still work." :
			"Signing in was cancelled.");
	}
}

static void update(struct pane *p) {
	struct browser *b = p->b;
	struct folder *f = p->folder;
	bool trash = in_trash(p);
	bool network = in_network(p);
	bool packed = in_archive(p);
	bool browse = b->mode == MODE_BROWSE;
	if (p == cur(b)) {
		b->cmd.paste->hidden = !(browse && !trash && !network && !packed &&
			clipboard_has());
		b->cmd.new_folder->hidden = trash || network || packed;
		b->cmd.extract_all->hidden = !(browse && packed);
		b->cmd.empty_trash->hidden = !(browse && trash && f->all->len > 0);
		b->cmd.connect->hidden = !network;
		/* Not what the list on the left has already */
		int place = places_find(f->dir);
		struct place *at = place >= 0 ? places_get()->pdata[place] : NULL;
		b->cmd.pin_folder->hidden = !browse || trash || network || packed ||
			(at && g_file_equal(at->file, f->dir));
	}
	p->empty->hidden = f->loading || f->shown->len > 0;
	c8ui_label_set_text(p->empty, f->not_mounted ?
		(p->mounting ? (packed ? "Opening…" : "Connecting…") :
		packed ? "Not opened." : "Not connected.") :
		packed && !p->search ? "This archive is empty." :
		p->search ? "Nothing here matches." :
		trash ? "The Trash is empty." :
		network ? "Nothing was found nearby. Connect to a server from the "
		"app bar." : "This folder is empty.");
	if (f->not_mounted && !f->loading) {
		/* A server not connected to yet: connect, then read it again */
		if (p->mount_tried == NULL || !g_file_equal(p->mount_tried, f->dir)) {
			g_set_object(&p->mount_tried, f->dir);
			p->mounting = true;
			c8ui_label_set_text(p->empty, packed ? "Opening…" :
				"Connecting…");
			mount_location(b->root, f->dir, folder_mounted, p);
		}
	} else if (f->error && !f->loading) {
		info(p, C8UI_SEVERITY_ERROR, "Couldn't read this folder", f->error);
	}
	update_selection(p);
}

static void selection_changed(struct c8ui_widget *list, void *data) {
	struct pane *p = data;
	if (p->restoring) {
		return;
	}
	activate(p);
	keep_selection(p);
	update_selection(p);
}

/* Picker answers */

static gboolean close_later(gpointer data) {
	struct browser *b = data;
	if (!alive(b)) {
		return G_SOURCE_REMOVE; // closed by the user meanwhile
	}
	/* The hold makes the last window going quit the app, as closing it
	 * by its title bar does (unless something else holds it) */
	struct c8ui_app *app = files_app();
	c8ui_app_hold(app);
	c8ui_window_destroy(b->win);
	c8ui_app_release(app);
	return G_SOURCE_REMOVE;
}

static void answer(struct browser *b, char **uris) {
	if (b->pick.answered) {
		return;
	}
	b->pick.answered = true;
	b->pick.done(b, uris, b->pick.data);
	/* Not from inside the click that answered */
	g_idle_add(close_later, b);
}

static void accept_open(struct browser *b) {
	struct pane *p = cur(b);
	GPtrArray *uris = g_ptr_array_new_with_free_func(g_free);
	GList *files = selected_files(p);
	for (GList *l = files; l; l = l->next) {
		g_ptr_array_add(uris, g_file_get_uri(l->data));
	}
	g_list_free_full(files, g_object_unref);
	if (uris->len == 0 && b->pick.folders) {
		g_ptr_array_add(uris, g_file_get_uri(p->folder->dir));
	}
	g_ptr_array_add(uris, NULL);
	if (uris->len > 1) {
		answer(b, (char **)uris->pdata);
	}
	g_ptr_array_unref(uris);
}

struct replace_ask {
	struct browser *b;
	char *uri;
};

static void replace_answered(int choice, void *data) {
	struct replace_ask *r = data;
	if (choice == 0 && alive(r->b)) {
		char *uris[] = { r->uri, NULL };
		answer(r->b, uris);
	}
	g_free(r->uri);
	free(r);
}

static void accept_save(struct browser *b) {
	struct pane *p = cur(b);
	const char *name = c8ui_entry_get(b->pick.name);
	if (name == NULL || name[0] == '\0' || strchr(name, '/')) {
		c8ui_widget_grab_focus(b->pick.name);
		return;
	}
	GFile *file = g_file_get_child_for_display_name(p->folder->dir, name,
		NULL);
	if (file == NULL) {
		return;
	}
	char *uri = g_file_get_uri(file);
	if (g_file_query_exists(file, NULL)) {
		struct replace_ask *r = calloc(1, sizeof(*r));
		r->b = b;
		r->uri = uri;
		char *message = g_strdup_printf("There's already a file called %s "
			"here. Replace it?", c8_stealth_show(name));
		const char *buttons[] = { "Replace", "Cancel" };
		c8ui_dialog_show(b->root, "Replace the file?", message, buttons, 2,
			replace_answered, r);
		g_free(message);
	} else {
		char *uris[] = { uri, NULL };
		answer(b, uris);
		g_free(uri);
	}
	g_object_unref(file);
}

static void accept_clicked(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	if (b->mode == MODE_SAVE) {
		accept_save(b);
	} else {
		accept_open(b);
	}
}

static void cancel_clicked(struct c8ui_widget *w, void *data) {
	answer(data, NULL);
}

static void filter_chosen(struct c8ui_widget *combo, void *data) {
	struct browser *b = data;
	b->pick.filter = c8ui_combo_get(combo);
	folder_update_view(cur(b)->folder);
}

static void name_entered(struct c8ui_widget *entry, void *data) {
	accept_save(data);
}

/* Opening */

static void open_item(struct c8ui_widget *list, int index, void *data) {
	struct pane *p = data;
	struct browser *b = p->b;
	activate(p);
	if (index < 0 || index >= (int)p->folder->shown->len) {
		return;
	}
	struct entry *e = p->folder->shown->pdata[index];
	if (e->dir) {
		/* e goes with the folder */
		GFile *dir = g_object_ref(e->target ? e->target : e->file);
		show_folder(p, dir, true);
		g_object_unref(dir);
	} else if (b->mode == MODE_OPEN) {
		accept_open(b);
	} else if (b->mode == MODE_SAVE) {
		c8ui_entry_set(b->pick.name, e->name);
		accept_save(b);
	} else if (in_trash(p)) {
		return;
	} else if (arc_can_browse(e->mime)) {
		/* An archive opens like a folder */
		GFile *root = arc_root(e->file);
		show_folder(p, root, true);
		g_object_unref(root);
	} else {
		char *uri = g_file_get_uri(e->file);
		c8ui_window_open_uri(b->win, uri);
		g_free(uri);
	}
}

static void item_context(struct c8ui_widget *list, int index, double x,
		double y, void *data) {
	struct pane *p = data;
	activate(p);
	/* Off the items the selection stays, to act on from the bar */
	if (index >= 0 && !c8ui_list_is_selected(list, index)) {
		c8ui_list_select(list, index);
	}
	keep_selection(p);
	update(p);
	c8ui_appbar_show(p->b->bar);
}

/* Commands */

static void cmd_open(struct c8ui_widget *w, void *data) {
	struct pane *p = cur(data);
	open_item(p->list, c8ui_list_get_selected(p->list), p);
}

/* Where a flyout about the selection goes: over its first item */
static struct c8ui_rect selection_anchor(struct pane *p) {
	int index = c8ui_list_get_selected(p->list);
	c8ui_appbar_hide(p->b->bar);
	c8ui_list_reveal(p->list, index);
	return c8ui_list_get_item_rect(p->list, index);
}

static void cmd_open_with(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	struct pane *p = cur(b);
	const char *mime = selected_type(p);
	if (mime == NULL) {
		return;
	}
	GList *files = selected_files(p);
	GPtrArray *uris = g_ptr_array_new_with_free_func(g_free);
	for (GList *l = files; l; l = l->next) {
		g_ptr_array_add(uris, g_file_get_uri(l->data));
	}
	g_ptr_array_add(uris, NULL);
	struct c8ui_rect anchor = selection_anchor(p);
	open_with_show(b->win, b->root, &anchor, (char **)uris->pdata, mime);
	g_ptr_array_unref(uris);
	g_list_free_full(files, g_object_unref);
}

static void cmd_props(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	struct pane *p = cur(b);
	GList *files = selected_files(p);
	struct c8ui_rect anchor = selection_anchor(p);
	props_show(b->root, &anchor, files);
	g_list_free_full(files, g_object_unref);
}

static void put_on_clipboard(struct browser *b, bool cut) {
	struct pane *p = cur(b);
	GList *files = selected_files(p);
	GPtrArray *uris = g_ptr_array_new_with_free_func(g_free);
	for (GList *l = files; l; l = l->next) {
		g_ptr_array_add(uris, g_file_get_uri(l->data));
	}
	g_ptr_array_add(uris, NULL);
	if (uris->len > 1) {
		clipboard_set(b->win, (char **)uris->pdata, cut);
	}
	g_ptr_array_unref(uris);
	g_list_free_full(files, g_object_unref);
}

void browsers_clipboard_changed(struct c8ui_app *app, void *data) {
	for (GList *l = browsers; l; l = l->next) {
		update(cur(l->data));
	}
}

static void cmd_copy(struct c8ui_widget *w, void *data) {
	put_on_clipboard(data, false);
}

static void cmd_cut(struct c8ui_widget *w, void *data) {
	put_on_clipboard(data, true);
}

static void cmd_paste(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	struct pane *p = cur(b);
	clipboard_paste(b->win, p->folder->dir);
}

static void cmd_trash(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	struct pane *p = cur(b);
	if (in_archive(p)) {
		return;
	}
	GList *files = selected_files(p);
	if (files) {
		ops_trash(b->win, files);
	}
	g_list_free_full(files, g_object_unref);
}

static void cmd_erase(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	struct pane *p = cur(b);
	if (in_archive(p)) {
		return;
	}
	GList *files = selected_files(p);
	if (files) {
		ops_delete(b->win, files);
	}
	g_list_free_full(files, g_object_unref);
}

static void cmd_restore(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	struct pane *p = cur(b);
	GList *files = selected_files(p);
	if (files) {
		ops_restore(b->win, files);
	}
	g_list_free_full(files, g_object_unref);
}

static void cmd_empty_trash(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	ops_empty_trash(b->win);
}

struct made_wait {
	struct pane *p;
};

static void folder_made(GFile *made, void *data) {
	struct made_wait *m = data;
	if (made && pane_alive(m->p)) {
		struct pane *p = m->p;
		g_free(p->rename_next);
		p->rename_next = g_file_get_basename(made);
		/* It may be in already: the monitor can be quicker than us */
		folder_changed(p->folder, p);
	}
	free(m);
}

static void cmd_new_folder(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	struct pane *p = cur(b);
	struct made_wait *m = calloc(1, sizeof(*m));
	m->p = p;
	ops_new_folder(b->win, p->folder->dir, folder_made, m);
}

static void cmd_select_all(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	struct pane *p = cur(b);
	c8ui_list_select_all(p->list, true);
	keep_selection(p);
	update_selection(p);
}

static void cmd_details(struct c8ui_widget *w, void *data) {
	prefs.details = c8ui_appbar_command_get_toggle(w);
	prefs_changed();
}

static void set_hidden(bool show) {
	prefs.show_hidden = show;
	prefs_changed();
}

static void cmd_hidden(struct c8ui_widget *w, void *data) {
	set_hidden(c8ui_appbar_command_get_toggle(w));
}

/* Renaming: a box in a flyout over the item */

struct rename {
	struct pane *p;
	GFile *file;
	struct c8ui_widget *entry, *flyout;
	char *old;
};

static void rename_done(void *data) {
	struct rename *r = data;
	const char *name = c8ui_entry_get(r->entry);
	if (pane_alive(r->p) && name && name[0] && strcmp(name, r->old) != 0) {
		g_ptr_array_set_size(r->p->keep, 0);
		g_ptr_array_add(r->p->keep, g_strdup(name));
		ops_rename(r->p->b->win, r->file, name);
	}
	g_object_unref(r->file);
	g_free(r->old);
	free(r);
}

static void rename_enter(struct c8ui_widget *entry, void *data) {
	struct rename *r = data;
	c8ui_flyout_close(r->flyout); // rename_done runs
}

static void browser_rename(struct pane *p) {
	struct entry *e = selected_entry(p);
	if (e == NULL || in_trash(p) || in_archive(p)) {
		return;
	}
	int index = c8ui_list_get_selected(p->list);
	struct rename *r = calloc(1, sizeof(*r));
	r->p = p;
	r->file = g_object_ref(e->file);
	r->old = g_strdup(e->name);
	struct c8ui_widget *box = c8ui_box_new(C8UI_VERTICAL, 12);
	box->fixed_width = 320;
	r->entry = c8ui_entry_new("Name", e->name, rename_enter, r);
	r->entry->fill = true;
	c8ui_widget_add(box, r->entry);
	/* Under the item */
	c8ui_list_reveal(p->list, index);
	struct c8ui_rect anchor = c8ui_list_get_item_rect(p->list, index);
	r->flyout = c8ui_flyout_show(p->b->root, &anchor, box, rename_done, r);
	c8ui_widget_grab_focus(r->entry);
}

static void cmd_rename(struct c8ui_widget *w, void *data) {
	browser_rename(cur(data));
}

/* Archives */

/* What an extract or a compress made: selected, if its folder still shows */
static void archive_made(GFile *made, void *data) {
	struct made_wait *m = data;
	if (made && pane_alive(m->p)) {
		struct pane *p = m->p;
		GFile *parent = g_file_get_parent(made);
		if (parent && g_file_equal(parent, p->folder->dir)) {
			g_ptr_array_set_size(p->keep, 0);
			g_ptr_array_add(p->keep, g_file_get_basename(made));
			/* It may be in already: the monitor can be quicker than us */
			folder_changed(p->folder, p);
		}
		g_clear_object(&parent);
	}
	free(m);
}

static void cmd_extract(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	struct pane *p = cur(b);
	c8ui_appbar_hide(b->bar);
	if (!selected_archives(p) || !g_file_is_native(p->folder->dir)) {
		return;
	}
	GList *files = selected_files(p);
	struct made_wait *m = calloc(1, sizeof(*m));
	m->p = p;
	ops_extract(b->win, files, p->folder->dir, archive_made, m);
	g_list_free_full(files, g_object_unref);
}

/* From inside one: all of it, beside the archive, and back out to see */
static void cmd_extract_all(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	struct pane *p = cur(b);
	c8ui_appbar_hide(b->bar);
	GFile *archive = arc_file(p->folder->dir);
	GFile *into = archive ? g_file_get_parent(archive) : NULL;
	if (into && g_file_is_native(into)) {
		GList *files = g_list_prepend(NULL, archive);
		show_folder(p, into, true);
		struct made_wait *m = calloc(1, sizeof(*m));
		m->p = p;
		ops_extract(b->win, files, into, archive_made, m);
		g_list_free(files);
	} else if (archive) {
		info(p, C8UI_SEVERITY_ERROR, "Couldn't extract it",
			"Copy the archive to a folder on this PC first.");
	}
	g_clear_object(&into);
	g_clear_object(&archive);
}

struct compress {
	struct browser *b;
	struct pane *p;
	GList *files;
	struct c8ui_widget *dialog, *entry, *format;
};

static enum arc_format compress_format; // as last chosen

static void compress_answered(int choice, void *data) {
	struct compress *c = data;
	/* Read only on Compress (a press or Enter): the boxes are still there */
	char *name = choice == 0 ?
		g_strstrip(g_strdup(c8ui_entry_get(c->entry))) : NULL;
	if (name && pane_alive(c->p)) {
		struct pane *p = c->p;
		compress_format = c8ui_combo_get(c->format);
		const char *ext = arc_format_ext(compress_format);
		/* Typed with its ending: not twice */
		if (g_str_has_suffix(name, ext)) {
			name[strlen(name) - strlen(ext)] = '\0';
		}
		if (name[0] == '\0' || strchr(name, '/')) {
			info(p, C8UI_SEVERITY_ERROR, "Couldn't make the archive",
				name[0] ? "A name can't have a / in it." : "It needs a name.");
		} else {
			char *full = g_strconcat(name, ext, NULL);
			GFile *dest = g_file_get_child(p->folder->dir, full);
			struct made_wait *m = calloc(1, sizeof(*m));
			m->p = p;
			ops_compress(c->b->win, c->files, dest, compress_format,
				archive_made, m);
			g_object_unref(dest);
			g_free(full);
		}
	}
	g_free(name);
	g_list_free_full(c->files, g_object_unref);
	free(c);
}

static void compress_enter(struct c8ui_widget *entry, void *data) {
	struct compress *c = data;
	c8ui_dialog_choose(c->dialog, 0);
}

static void cmd_compress(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	struct pane *p = cur(b);
	c8ui_appbar_hide(b->bar);
	int n = c8ui_list_selected_count(p->list);
	if (n == 0 || in_trash(p) || !g_file_is_native(p->folder->dir)) {
		return;
	}
	struct compress *c = calloc(1, sizeof(*c));
	c->b = b;
	c->p = p;
	c->files = selected_files(p);
	/* One thing: its name. Several: their folder's */
	struct entry *one = n == 1 ? selected_entry(p) : NULL;
	char *name = one ? (one->dir ? g_strdup(one->name) : arc_stem(one->name)) :
		g_file_get_basename(p->folder->dir);
	char *message = one ? g_strdup_printf("%s goes into a new archive in "
		"this folder.", c8_stealth_show(one->name)) : g_strdup_printf("The %d selected items "
		"go into a new archive in this folder.", n);
	static const char *const buttons[] = { "Compress", "Cancel" };
	c->dialog = c8ui_dialog_show(b->root, "Compress", message, buttons, 2,
		compress_answered, c);
	g_free(message);
	c->entry = c8ui_entry_new("Name", name, compress_enter, c);
	c8ui_dialog_add(c->dialog, c->entry);
	const char *formats[ARC_FORMATS];
	for (int i = 0; i < ARC_FORMATS; i++) {
		formats[i] = arc_format_name(i);
	}
	c->format = c8ui_combo_new("Kind", formats, ARC_FORMATS, compress_format,
		NULL, NULL);
	c->format->fill = true;
	c8ui_dialog_add(c->dialog, c->format);
	c8ui_widget_grab_focus(c->entry);
	g_free(name);
}

/* Keys */

static void tab_close(struct browser *b, int index);
static void tab_step(struct browser *b, int by);
static void set_split(struct browser *b, bool split);
static void other_pane(struct browser *b);
static void pin_selection(struct browser *b);

/* The pane the keyboard is in is the one in use */
static void follow_focus(struct browser *b) {
	struct c8ui_widget *focus = c8ui_root_focus(b->root);
	struct tab *t = cur_tab(b);
	for (int i = 0; focus && i < 2; i++) {
		if (t->pane[i] && is_inside(focus, t->pane[i]->main)) {
			activate(t->pane[i]);
		}
	}
}

/* Letters typed over the list go to the first item whose name starts
 * with them; typed within TYPE_MS they add up ("re" then "p": "rep"),
 * and one letter again goes to the next item starting with it */
#define TYPE_MS 1000

static bool name_starts(const struct entry *e, const char *folded) {
	char *name = g_utf8_casefold(e->name, -1);
	bool starts = g_str_has_prefix(name, folded);
	g_free(name);
	return starts;
}

static bool type_ahead(struct pane *p, const struct c8ui_event *ev) {
	struct browser *b = p->b;
	struct c8ui_widget *focus = c8ui_root_focus(b->root);
	if (ev->text == NULL || p->folder == NULL || (ev->mods & (C8UI_MOD_CTRL | C8UI_MOD_ALT)) ||
			(focus && !is_inside(focus, p->main))) {
		return false;
	}
	gint64 now = g_get_monotonic_time();
	if (b->typed == NULL) {
		b->typed = g_string_new(NULL);
	}
	if (now - b->typed_at > TYPE_MS * 1000) {
		g_string_truncate(b->typed, 0);
	}
	gunichar c = g_utf8_get_char(ev->text);
	if (!g_unichar_isprint(c) || (g_unichar_isspace(c) && b->typed->len == 0)) {
		return false;
	}
	char *folded = g_utf8_casefold(ev->text, -1);
	GPtrArray *shown = p->folder->shown;
	int count = shown->len, from = 0;
	bool again = strcmp(b->typed->str, folded) == 0;
	if (again) {
		/* The same letter once more: the next one after the selection */
		from = c8ui_list_get_selected(p->list) + 1;
	} else {
		g_string_append(b->typed, folded);
	}
	g_free(folded);
	b->typed_at = now;
	for (int i = 0; i < count; i++) {
		int index = (from + i) % count;
		if (name_starts(shown->pdata[index], b->typed->str)) {
			c8ui_list_select(p->list, index);
			c8ui_list_reveal(p->list, index);
			c8ui_widget_grab_focus(p->list);
			update(p);
			break;
		}
	}
	return true;
}

static bool key(const struct c8ui_event *ev, void *data) {
	struct browser *b = data;
	follow_focus(b);
	struct pane *p = cur(b);
	uint32_t mods = ev->mods & (C8UI_MOD_CTRL | C8UI_MOD_SHIFT | C8UI_MOD_ALT);
	bool browse = b->mode == MODE_BROWSE;
	switch (ev->base_sym) {
	case XKB_KEY_BackSpace:
		if (mods == 0) {
			go_back(NULL, p);
			return true;
		}
		break;
	case XKB_KEY_F3:
		if (browse && mods == 0) {
			set_split(b, cur_tab(b)->split == NULL);
			return true;
		}
		break;
	case XKB_KEY_F6:
		if (browse && mods == 0 && cur_tab(b)->split) {
			other_pane(b);
			return true;
		}
		break;
	case XKB_KEY_Tab:
	case XKB_KEY_ISO_Left_Tab:
		if (browse && (mods & C8UI_MOD_CTRL) && !(mods & C8UI_MOD_ALT)) {
			tab_step(b, mods & C8UI_MOD_SHIFT ? -1 : 1);
			return true;
		}
		break;
	case XKB_KEY_Page_Up:
	case XKB_KEY_Page_Down:
		if (browse && mods == C8UI_MOD_CTRL) {
			tab_step(b, ev->base_sym == XKB_KEY_Page_Up ? -1 : 1);
			return true;
		}
		break;
	case XKB_KEY_Up:
		if (mods == C8UI_MOD_ALT) {
			go_up(p);
			return true;
		}
		break;
	case XKB_KEY_F5:
		folder_reload(p->folder);
		return true;
	case XKB_KEY_F2:
		if (browse) {
			browser_rename(p);
			return true;
		}
		break;
	case XKB_KEY_Delete:
		if (!browse) {
			break;
		}
		if (mods == C8UI_MOD_SHIFT || in_trash(p)) {
			cmd_erase(NULL, b);
		} else if (mods == 0) {
			cmd_trash(NULL, b);
		}
		return true;
	case XKB_KEY_Escape:
		if (b->places_open) {
			show_places(b, false);
			return true;
		}
		if (!browse) {
			answer(b, NULL);
			return true;
		}
		break;
	case XKB_KEY_Return:
	case XKB_KEY_KP_Enter:
		/* What the list didn't open: the picker's button */
		if (!browse && mods == 0 && !b->pick.accept->disabled) {
			accept_clicked(NULL, b);
			return true;
		}
		if (browse && mods == C8UI_MOD_ALT &&
				c8ui_list_selected_count(p->list) > 0) {
			cmd_props(NULL, b);
			return true;
		}
		break;
	case XKB_KEY_Menu:
		update(p);
		c8ui_appbar_toggle(b->bar);
		return true;
	}
	if (mods == C8UI_MOD_CTRL) {
		switch (ev->base_sym) {
		case XKB_KEY_c:
			if (browse) {
				put_on_clipboard(b, false);
			}
			return true;
		case XKB_KEY_x:
			if (browse) {
				put_on_clipboard(b, true);
			}
			return true;
		case XKB_KEY_v:
			if (browse && clipboard_has()) {
				cmd_paste(NULL, b);
			}
			return true;
		case XKB_KEY_a:
			cmd_select_all(NULL, b);
			return true;
		case XKB_KEY_h:
			set_hidden(!prefs.show_hidden);
			return true;
		case XKB_KEY_n:
			if (browse) {
				browser_present(browser_new(p->folder->dir));
			}
			return true;
		case XKB_KEY_t:
			if (browse) {
				tab_new(b, p->folder->dir, b->tab + 1);
				tab_show(b, b->tab + 1);
			}
			return true;
		case XKB_KEY_d:
			if (browse) {
				pin_selection(b);
			}
			return true;
		case XKB_KEY_w:
			if (browse && b->tabs->len > 1) {
				tab_close(b, b->tab);
			} else if (browse) {
				g_idle_add(close_later, b);
			}
			return true;
		}
	}
	if (mods == (C8UI_MOD_CTRL | C8UI_MOD_SHIFT) && ev->base_sym == XKB_KEY_n &&
			!b->cmd.new_folder->hidden) {
		cmd_new_folder(NULL, b);
		return true;
	}
	return type_ahead(p, ev);
}

/* Connect to a server: an address typed, mounted, then shown */

struct connect {
	struct browser *b;
	struct c8ui_widget *dialog, *entry, *keep;
};

struct connecting {
	struct pane *p;
	GFile *location;
	char *uri;
	bool keep;
};

/* What people type: \\server\share as Windows has it, or a bare
 * server/share, are Windows shares */
static char *server_uri(const char *text) {
	char *t = g_strstrip(g_strdup(text));
	char *uri;
	if (g_str_has_prefix(t, "\\\\")) {
		g_strdelimit(t, "\\", '/');
		uri = g_strconcat("smb:", t, NULL);
	} else if (g_str_has_prefix(t, "https://") || g_str_has_prefix(t,
			"http://")) {
		/* A web address is a WebDAV folder here (Nextcloud and the
		 * like), not one page to download */
		uri = g_strconcat(t[4] == 's' ? "davs" : "dav", t + (t[4] == 's' ?
			5 : 4), NULL);
	} else if (strstr(t, "://") || t[0] == '/') {
		uri = g_strdup(t);
	} else {
		uri = g_strconcat("smb://", t, NULL);
	}
	g_free(t);
	return uri;
}

static void connected(bool ok, const char *error, void *data) {
	struct connecting *c = data;
	if (pane_alive(c->p)) {
		if (ok) {
			if (c->keep) {
				places_add_bookmark(c->uri);
			}
			browser_go(c->p, c->location);
		} else if (error) {
			info(c->p, C8UI_SEVERITY_ERROR, "Couldn't connect", error);
		}
	}
	g_object_unref(c->location);
	g_free(c->uri);
	free(c);
}

static void connect_answered(int choice, void *data) {
	struct connect *c = data;
	/* Read only on Connect (a press or Enter): the boxes are still there */
	const char *text = choice == 0 ? c8ui_entry_get(c->entry) : NULL;
	if (text && text[0] && alive(c->b)) {
		struct connecting *g = calloc(1, sizeof(*g));
		g->p = cur(c->b);
		g->uri = server_uri(text);
		g->location = g_file_new_for_commandline_arg(g->uri);
		g->keep = c8ui_checkbox_get(c->keep);
		mount_location(c->b->root, g->location, connected, g);
	}
	free(c);
}

static void connect_enter(struct c8ui_widget *entry, void *data) {
	struct connect *c = data;
	c8ui_dialog_choose(c->dialog, 0);
}

static void cmd_connect(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	c8ui_appbar_hide(b->bar);
	struct connect *c = calloc(1, sizeof(*c));
	c->b = b;
	static const char *const buttons[] = { "Connect", "Cancel" };
	c->dialog = c8ui_dialog_show(b->root, "Connect to a server",
		"Type the address of a shared folder, like smb://server/share, "
		"sftp://name@server/folder, ftp://server, or a WebDAV one's "
		"web address (https://server/folder).", buttons, 2, connect_answered, c);
	c->entry = c8ui_entry_new("Address", "", connect_enter, c);
	c8ui_entry_set_placeholder(c->entry, "smb://server/share");
	c8ui_dialog_add(c->dialog, c->entry);
	c->keep = c8ui_checkbox_new("Add it to the list on the left", true, NULL,
		NULL);
	c8ui_dialog_add(c->dialog, c->keep);
	c8ui_widget_grab_focus(c->entry);
}

/* Drag and drop: the selection out to anywhere, files in from anywhere */

#define DRAG_ICON 72
#define URI_LIST "text/uri-list"

struct drag_picture {
	struct entry *entry; // the one pressed
	int count;
};

static void draw_drag_icon(cairo_t *cr, void *data) {
	struct drag_picture *d = data;
	double s = DRAG_ICON;
	cairo_surface_t *thumb = entry_thumbnail(d->entry);
	struct c8ui_icon *icon = entry_icon(d->entry);
	if (thumb) {
		double w = cairo_image_surface_get_width(thumb);
		double h = cairo_image_surface_get_height(thumb);
		double k = (s - 8) / (w > h ? w : h);
		cairo_save(cr);
		cairo_translate(cr, (s - w * k) / 2, (s - h * k) / 2);
		cairo_scale(cr, k, k);
		cairo_set_source_surface(cr, thumb, 0, 0);
		cairo_paint_with_alpha(cr, 0.85);
		cairo_restore(cr);
	} else if (icon) {
		c8ui_icon_draw_fit(cr, icon, s / 2, s / 2, s - 8);
	}
	if (d->count > 1) {
		/* How many: a badge in the accent colour */
		char text[16];
		snprintf(text, sizeof(text), "%d", d->count);
		struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY_STRONG);
		double tw, th;
		c8ui_text_size(NULL, font, text, 0, 0, &tw, &th);
		double bw = tw + 12 > 24 ? tw + 12 : 24;
		c8ui_set_source(cr, c8ui_app_theme(files_app())->accent, 1);
		cairo_rectangle(cr, s - bw, 0, bw, 24);
		cairo_fill(cr);
		cairo_set_source_rgb(cr, 1, 1, 1);
		c8ui_text_draw(cr, NULL, font, text, s - bw + (bw - tw) / 2,
			(24 - th) / 2, tw + 1, 1);
	}
}

static void list_drag(struct c8ui_widget *list, int index, void *data) {
	struct pane *p = data;
	struct browser *b = p->b;
	activate(p);
	if (index < 0 || index >= (int)p->folder->shown->len) {
		return;
	}
	GList *files = selected_files(p);
	GString *uris = g_string_new(NULL);
	GString *paths = g_string_new(NULL);
	int count = 0;
	for (GList *l = files; l; l = l->next, count++) {
		char *uri = g_file_get_uri(l->data);
		char *path = g_file_get_path(l->data);
		g_string_append_printf(uris, "%s\r\n", uri);
		g_string_append_printf(paths, "%s%s", count ? "\n" : "",
			path ? path : uri);
		g_free(uri);
		g_free(path);
	}
	g_list_free_full(files, g_object_unref);
	const struct c8ui_clip_item items[] = {
		{ URI_LIST, uris->str, uris->len },
		{ "text/plain", paths->str, paths->len },
	};
	struct drag_picture picture = {
		.entry = p->folder->shown->pdata[index],
		.count = count,
	};
	const struct c8ui_drag_options o = {
		.items = items,
		.count = count ? G_N_ELEMENTS(items) : 0,
		/* Out of the Trash is putting back: a move */
		.actions = in_trash(p) ? C8UI_DND_MOVE : C8UI_DND_COPY | C8UI_DND_MOVE,
		.icon_width = DRAG_ICON,
		.icon_height = DRAG_ICON,
		.hot_x = DRAG_ICON / 2,
		.hot_y = DRAG_ICON / 2,
		.draw_icon = draw_drag_icon,
		.data = &picture, // drawn before this returns; no done to call
	};
	c8ui_window_start_drag(b->win, &o);
	g_string_free(uris, TRUE);
	g_string_free(paths, TRUE);
}

/* The folder a drop at x, y goes into (a new reference), and what to
 * outline for it: an item of the pane it is over, or a place */
static GFile *drop_target(struct browser *b, double x, double y,
		struct pane **pane, int *item, int *place) {
	*item = *place = -1;
	*pane = NULL;
	struct c8ui_widget *w = c8ui_root_widget_at(b->root, x, y);
	if (is_inside(w, b->places)) {
		int i = c8ui_list_item_at(b->places, x, y);
		GPtrArray *places = places_get();
		struct place *p = i >= 0 && i < (int)places->len ?
			places->pdata[i] : NULL;
		if (p == NULL || p->file == NULL || p->is_file) {
			return NULL;
		}
		*place = i;
		return g_object_ref(p->file);
	}
	struct tab *t = cur_tab(b);
	struct pane *p = NULL;
	for (int i = 0; i < 2; i++) {
		if (t->pane[i] && is_inside(w, t->pane[i]->main)) {
			p = t->pane[i];
		}
	}
	if (p == NULL || (!is_inside(w, p->scroll) && !is_inside(w, p->empty))) {
		return NULL;
	}
	*pane = p;
	int i = is_inside(w, p->list) ? c8ui_list_item_at(p->list, x, y) : -1;
	struct entry *e = i >= 0 && i < (int)p->folder->shown->len ?
		p->folder->shown->pdata[i] : NULL;
	if (e && e->dir) {
		*item = i;
		return g_object_ref(e->file);
	}
	return g_object_ref(p->folder->dir);
}

static void got_drop_files(const char *mime, const char *data, size_t len,
		void *userdata) {
	struct browser *b = userdata;
	if (mime) {
		b->drop_files = files_from_uris(data, false, NULL);
	}
}

static GList *drop_files(struct browser *b) {
	if (!b->drop_read) {
		b->drop_read = true;
		static const char *const types[] = { URI_LIST };
		c8ui_drop_read(b->win, types, 1, got_drop_files, b);
	}
	return b->drop_files;
}

/* Which filesystem dir is on, asked once per target */
static const char *filesystem_of(struct browser *b, GFile *dir) {
	if (b->fs_dir == NULL || !g_file_equal(b->fs_dir, dir)) {
		g_clear_object(&b->fs_dir);
		g_free(b->fs_id);
		b->fs_dir = g_object_ref(dir);
		GFileInfo *info = g_file_query_info(dir,
			G_FILE_ATTRIBUTE_ID_FILESYSTEM, G_FILE_QUERY_INFO_NONE, NULL,
			NULL);
		b->fs_id = info ? g_strdup(g_file_info_get_attribute_string(info,
			G_FILE_ATTRIBUTE_ID_FILESYSTEM)) : NULL;
		g_clear_object(&info);
	}
	return b->fs_id;
}

/* Whether what's dragged (the first of it) is on dir's filesystem. Asked
 * once per drag: this runs for every motion over the window, and on a
 * network folder each query is a round trip. */
static bool same_filesystem(struct browser *b, GFile *file, GFile *dir) {
	const char *there = filesystem_of(b, dir);
	if (!b->drop_fs_read) {
		b->drop_fs_read = true;
		GFileInfo *info = g_file_query_info(file,
			G_FILE_ATTRIBUTE_ID_FILESYSTEM,
			G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, NULL, NULL);
		b->drop_fs = info ? g_strdup(g_file_info_get_attribute_string(info,
			G_FILE_ATTRIBUTE_ID_FILESYSTEM)) : NULL;
		g_clear_object(&info);
	}
	return b->drop_fs && there && strcmp(b->drop_fs, there) == 0;
}

/* What dropping files into dir does: within a drive they move, onto
 * another they are copied, as Windows does; into the Trash they go */
static uint32_t drop_action(struct browser *b, GFile *dir, uint32_t allowed) {
	GList *files = drop_files(b);
	if (dir == NULL || files == NULL) {
		return 0;
	}
	bool all_here = true;
	for (GList *l = files; l; l = l->next) {
		GFile *parent = g_file_get_parent(l->data);
		all_here = all_here && parent && g_file_equal(parent, dir);
		g_clear_object(&parent);
		/* Not a folder into itself */
		if (g_file_equal(l->data, dir) || g_file_has_prefix(dir, l->data)) {
			return 0;
		}
	}
	if (all_here) {
		return 0; // already there
	}
	if (g_file_has_uri_scheme(dir, "archive")) {
		return 0; // read only
	}
	bool trash_in = g_file_has_uri_scheme(dir, "trash");
	bool trash_out = g_file_has_uri_scheme(files->data, "trash");
	uint32_t want;
	if (trash_in) {
		want = trash_out ? 0 : C8UI_DND_MOVE;
	} else if (trash_out || same_filesystem(b, files->data, dir)) {
		want = C8UI_DND_MOVE;
	} else {
		want = C8UI_DND_COPY;
	}
	if (want & allowed) {
		return want;
	}
	/* Copying into the Trash isn't a thing; putting back can't copy */
	return trash_in || trash_out ? 0 : allowed & (C8UI_DND_COPY | C8UI_DND_MOVE);
}

static void set_drop_outline(struct browser *b, struct pane *p, int item,
		int place) {
	p = item >= 0 ? p : NULL;
	if (item != b->drop_item || p != b->drop_pane) {
		struct pane *was = b->drop_pane;
		b->drop_item = item;
		b->drop_pane = p;
		if (was && pane_alive(was)) {
			c8ui_list_redraw(was->list);
		}
		if (p && p != was) {
			c8ui_list_redraw(p->list);
		}
	}
	if (place != b->drop_place) {
		b->drop_place = place;
		c8ui_list_redraw(b->places);
	}
}

static uint32_t drop_motion(struct c8ui_window *win, double x, double y,
		uint32_t allowed, void *data) {
	struct browser *b = data;
	if (!c8ui_drop_offers(win, URI_LIST)) {
		return 0;
	}
	int item, place;
	struct pane *p;
	GFile *dir = drop_target(b, x, y, &p, &item, &place);
	uint32_t action = drop_action(b, dir, allowed);
	g_clear_object(&dir);
	set_drop_outline(b, p, action ? item : -1, action ? place : -1);
	return action;
}

static void drop_leave(struct c8ui_window *win, void *data) {
	struct browser *b = data;
	set_drop_outline(b, NULL, -1, -1);
	g_list_free_full(b->drop_files, g_object_unref);
	b->drop_files = NULL;
	b->drop_read = false;
	g_clear_pointer(&b->drop_fs, g_free);
	b->drop_fs_read = false;
}

static void drop_done(struct c8ui_window *win, double x, double y,
		uint32_t action, void *data) {
	struct browser *b = data;
	int item, place;
	struct pane *p;
	GFile *dir = drop_target(b, x, y, &p, &item, &place);
	GList *files = drop_files(b);
	if (dir && files) {
		if (g_file_has_uri_scheme(dir, "trash")) {
			ops_trash(win, files);
		} else {
			ops_copy(win, files, dir, action == C8UI_DND_MOVE);
		}
	}
	g_clear_object(&dir);
}

static const struct c8ui_drop_impl drop_impl = {
	.motion = drop_motion,
	.leave = drop_leave,
	.drop = drop_done,
};

/* Building the window */

static void columns_changed(struct c8ui_widget *columns, void *data) {
	bool desc;
	int col = c8ui_columns_get_sort(columns, &desc);
	prefs.sort = col == COL_MODIFIED ? SORT_MODIFIED :
		col == COL_TYPE ? SORT_TYPE : col == COL_SIZE ? SORT_SIZE : SORT_NAME;
	prefs.descending = col >= 0 && desc;
	prefs_changed();
}

static void browser_gone(struct c8ui_widget *w, void *data) {
	/* The tabs and their panes went first, as children do */
	struct browser *b = data;
	browsers = g_list_remove(browsers, b);
	if (b->mode != MODE_BROWSE && !b->pick.answered) {
		b->pick.answered = true;
		b->pick.done(b, NULL, b->pick.data); // closed: cancelled
	}
	ops_window_gone(b->win);
	places_unwatch(b->places_watch);
	c8_stealth_unwatch(stealth_changed, b);
	mount_forget_root(b->root);
	g_ptr_array_unref(b->tabs);
	if (b->pick.filters) {
		g_ptr_array_unref(b->pick.filters);
	}
	g_list_free_full(b->drop_files, g_object_unref);
	g_free(b->drop_fs);
	if (b->typed) {
		g_string_free(b->typed, TRUE);
	}
	g_clear_object(&b->fs_dir);
	g_free(b->fs_id);
	free(b);
}

/* Narrow */

/* The picker's band: one row, or stacked when narrow (name, filter, then
 * the buttons at the end) */
static void arrange_band(struct browser *b) {
	struct c8ui_widget *band = b->pick.band;
	if (band == NULL) {
		return;
	}
	struct c8ui_widget *lead = b->pick.name ? b->pick.name : b->pick.count;
	struct c8ui_widget *parts[] = {
		lead, b->pick.combo, b->pick.accept, b->pick.cancel,
	};
	struct c8ui_widget *focus = c8ui_root_focus(b->root);
	for (int i = 0; i < 4; i++) {
		c8ui_widget_unparent(parts[i]);
	}
	c8ui_widget_clear(band);
	bool n = b->narrow;
	lead->expand = !n;
	lead->fill = n;
	b->pick.combo->fixed_width = n ? 0 : 220;
	b->pick.combo->fill = n;
	struct c8ui_widget *row = c8ui_box_new(C8UI_HORIZONTAL, 16);
	row->fill = !n;
	if (n) {
		row->align = C8UI_ALIGN_END;
		c8ui_widget_add(band, lead);
		c8ui_widget_add(band, b->pick.combo);
	} else {
		c8ui_widget_add(row, lead);
		c8ui_widget_add(row, b->pick.combo);
	}
	c8ui_widget_add(row, b->pick.accept);
	c8ui_widget_add(row, b->pick.cancel);
	c8ui_widget_add(band, row);
	for (int i = 0; i < 4; i++) {
		if (parts[i] == focus) {
			c8ui_widget_grab_focus(focus);
		}
	}
}

/* How a pane sits in the window: its margins, its header */
static void pane_arrange(struct pane *p) {
	struct browser *b = p->b;
	bool n = b->narrow;
	bool split = p->tab->split != NULL;
	p->places_button->hidden = !n;
	double pad = n ? NARROW_PAD : split ? SPLIT_PAD : 40;
	c8ui_box_set_padding(p->main, pad, n || split ? 24 : 40, pad,
		b->mode == MODE_BROWSE ? 0 : 24);
	/* Two headers in sight: smaller ones */
	c8ui_label_set_style(p->title, split ? C8UI_TEXT_SUBHEADER :
		C8UI_TEXT_HEADER);
	pane_apply_prefs(p);
	if (p->folder) {
		build_crumbs(p);
	}
}

/* Narrow shows the folders or the places, never both (a split tab's two
 * panes go one over the other there by themselves: c8ui's split) */
static void arrange(struct browser *b) {
	bool n = b->narrow;
	b->side->hidden = n && !b->places_open;
	b->side->fixed_width = n ? 0 : SIDE_WIDTH;
	b->side->expand = n;
	b->right->hidden = n && b->places_open;
	b->places_back->hidden = !n;
	for (guint i = 0; i < b->tabs->len; i++) {
		struct tab *t = b->tabs->pdata[i];
		for (int j = 0; j < 2; j++) {
			if (t->pane[j]) {
				pane_arrange(t->pane[j]);
			}
		}
	}
	apply_prefs(b);
	c8ui_widget_queue_layout(b->page);
}

static void show_places(struct browser *b, bool open) {
	b->places_open = b->narrow && open;
	arrange(b);
	if (b->places_open) {
		c8ui_widget_enter(b->side);
		c8ui_widget_grab_focus(b->places);
	} else if (b->narrow) {
		c8ui_widget_enter(b->right);
		c8ui_widget_grab_focus(cur(b)->list);
	}
}

static void places_clicked(struct c8ui_widget *w, void *data) {
	show_places(data, true);
}

static void places_back_clicked(struct c8ui_widget *w, void *data) {
	show_places(data, false);
}

static void resized(struct c8ui_root *root, double width, double height,
		void *data) {
	struct browser *b = data;
	bool narrow = c8ui_root_is_narrow(root);
	if (narrow == b->narrow) {
		return;
	}
	b->narrow = narrow;
	b->places_open = false;
	arrange(b);
	arrange_band(b);
	if (!narrow && c8ui_root_focus(root) == NULL) {
		c8ui_widget_grab_focus(cur(b)->list);
	}
}

/* Panes and tabs */

static void pane_gone(struct c8ui_widget *w, void *data) {
	struct pane *p = data;
	g_clear_object(&p->mount_tried);
	if (p->folder) {
		archive_left(p->folder->dir, p);
		folder_free(p->folder);
	}
	g_ptr_array_unref(p->history);
	g_ptr_array_unref(p->keep);
	g_free(p->search);
	g_free(p->rename_next);
	free(p);
}

/* A pane showing nothing yet: its header, then the folder */
static struct pane *pane_new(struct tab *t) {
	struct browser *b = t->b;
	struct pane *p = calloc(1, sizeof(*p));
	p->b = b;
	p->tab = t;
	p->history = g_ptr_array_new_with_free_func(g_object_unref);
	p->keep = g_ptr_array_new_with_free_func(g_free);

	struct c8ui_widget *main = p->main = c8ui_box_new(C8UI_VERTICAL, 12);
	main->expand = true;
	main->fill = true;
	main->user_data = p;
	main->on_destroy = pane_gone;
	struct c8ui_widget *head = c8ui_box_new(C8UI_HORIZONTAL, 16);
	p->back = c8ui_back_button_new(go_back, p);
	p->back->align = C8UI_ALIGN_CENTER;
	p->back->hidden = true;
	c8ui_widget_add(head, p->back);
	p->places_button = c8ui_icon_button_new("folder-open", NULL,
		places_clicked, b);
	c8ui_widget_set_tooltip(p->places_button, "Places");
	p->places_button->align = C8UI_ALIGN_CENTER;
	p->places_button->hidden = true;
	c8ui_widget_add(head, p->places_button);
	p->title = c8ui_label_new("", C8UI_TEXT_HEADER);
	c8ui_label_set_max_lines(p->title, 1);
	p->title->expand = true;
	c8ui_widget_add(head, p->title);
	c8ui_widget_add(main, head);
	p->crumbs = c8ui_box_new(C8UI_HORIZONTAL, 8);
	c8ui_box_set_wrap(p->crumbs, true);
	c8ui_widget_add(main, p->crumbs);
	p->info = c8ui_infobar_new(C8UI_SEVERITY_INFO, NULL, NULL);
	c8ui_infobar_set_closable(p->info, true, NULL, NULL);
	p->info->fill = true;
	p->info->hidden = true;
	c8ui_widget_add(main, p->info);

	p->columns = c8ui_columns_new(columns_changed, b);
	c8ui_columns_add(p->columns, "Name", 380);
	c8ui_columns_add(p->columns, "Date modified", 180);
	c8ui_columns_add(p->columns, "Type", 180);
	c8ui_columns_add(p->columns, "Size", 0);
	p->columns->fill = true;
	p->columns->hidden = true;
	c8ui_widget_add(main, p->columns);

	p->empty = c8ui_label_new("", C8UI_TEXT_BODY);
	c8ui_label_set_color(p->empty, C8UI_COLOR_SECONDARY);
	p->empty->hidden = true;
	/* Under the header, above the (empty) list */
	c8ui_widget_add(main, p->empty);

	p->list = c8ui_list_new(C8UI_LIST_GRID, TILE_W, TILE_H, draw_item, p);
	bool many = b->mode == MODE_BROWSE ||
		(b->mode == MODE_OPEN && b->pick.multiple);
	c8ui_list_set_multiple(p->list, many);
	c8ui_list_set_checks(p->list, true); // shown only where many go
	c8ui_list_on_open(p->list, open_item, p);
	c8ui_list_on_drag(p->list, list_drag, p);
	c8ui_list_on_select(p->list, selection_changed, p);
	c8ui_list_on_context(p->list, item_context, p);
	p->list->fill = true;
	p->scroll = c8ui_scroll_new(p->list);
	p->scroll->expand = true;
	p->scroll->fill = true;
	c8ui_widget_add(main, p->scroll);
	pane_arrange(p);
	return p;
}

static void tab_gone(struct c8ui_widget *w, void *data) {
	free(data);
}

/* A tab at dir, the at-th (the strip's order), not shown yet */
static struct tab *tab_new(struct browser *b, GFile *dir, int at) {
	struct tab *t = calloc(1, sizeof(*t));
	t->b = b;
	t->box = c8ui_box_new(C8UI_VERTICAL, 0);
	t->box->fill = true;
	t->box->user_data = t;
	t->box->on_destroy = tab_gone;
	t->pane[0] = pane_new(t);
	c8ui_widget_add(t->box, t->pane[0]->main);
	at = at < 0 || at > (int)b->tabs->len ? (int)b->tabs->len : at;
	g_ptr_array_insert(b->tabs, at, t);
	c8ui_widget_insert(b->stack, at, t->box);
	if (at <= b->tab && b->tabs->len > 1) {
		b->tab++; // the one shown moved along
	}
	c8ui_stack_set(b->stack, b->tab, false);
	GFile *go = g_object_ref(dir); // dir may be a pane's that goes
	show_folder(t->pane[0], go, false);
	g_object_unref(go);
	return t;
}

/* The tab shown, the pane in use or its folder changed: the window's
 * name, the place picked out, the strip and the bar follow */
static void tabs_changed(struct browser *b) {
	if (b->tabs->len == 0 || b->tab >= (int)b->tabs->len) {
		return;
	}
	struct tab *t = cur_tab(b);
	struct pane *p = cur(b);
	if (p == NULL || p->folder == NULL) {
		return; // being built
	}
	if (b->mode == MODE_BROWSE) {
		char *title = folder_title(p->folder->dir);
		c8ui_window_set_title(b->win, title);
		g_free(title);
	}
	/* Split: the pane in use has the dark title */
	for (int i = 0; i < 2; i++) {
		if (t->pane[i]) {
			c8ui_label_set_color(t->pane[i]->title, t->split &&
				i != t->active ? C8UI_COLOR_SECONDARY : C8UI_COLOR_PRIMARY);
		}
	}
	bool strip = b->tabs->len > 1;
	if (b->strip->hidden == strip) {
		b->strip->hidden = !strip;
		c8ui_widget_queue_layout(b->right);
	}
	c8ui_widget_queue_draw(b->strip);
	c8ui_appbar_command_set_toggle(b->cmd.split, t->split != NULL);
	select_place(b);
	update(p);
}

/* Stealth mode turned on or off: what's drawn from names again, titles and
 * crumbs (labels) made again */
static void stealth_changed(void *data) {
	struct browser *b = data;
	for (guint i = 0; i < b->tabs->len; i++) {
		struct tab *t = b->tabs->pdata[i];
		for (int k = 0; k < 2; k++) {
			struct pane *p = t->pane[k];
			if (p == NULL || p->folder == NULL) {
				continue;
			}
			char *title = folder_title(p->folder->dir);
			c8ui_label_set_text(p->title, title);
			g_free(title);
			build_crumbs(p);
			c8ui_list_redraw(p->list);
		}
	}
	c8ui_list_redraw(b->places);
	tabs_changed(b);
}

static void tab_show(struct browser *b, int index) {
	if (index < 0 || index >= (int)b->tabs->len) {
		return;
	}
	b->tab = index;
	c8ui_stack_set(b->stack, index, false);
	tabs_changed(b);
	c8ui_widget_grab_focus(cur(b)->list);
}

static void tab_step(struct browser *b, int by) {
	int n = b->tabs->len;
	tab_show(b, ((b->tab + by) % n + n) % n);
}

static void tab_close(struct browser *b, int index) {
	if (index < 0 || index >= (int)b->tabs->len) {
		return;
	}
	if (b->tabs->len == 1) {
		g_idle_add(close_later, b); // the last one: the window
		return;
	}
	struct tab *t = b->tabs->pdata[index];
	if (b->drop_pane && b->drop_pane->tab == t) {
		b->drop_pane = NULL;
		b->drop_item = -1;
	}
	g_ptr_array_remove_index(b->tabs, index);
	c8ui_widget_destroy(t->box); // its panes with it
	if (index < b->tab || b->tab >= (int)b->tabs->len) {
		b->tab--;
	}
	b->strip_hover = -1;
	tab_show(b, b->tab);
}

/* Split view: the tab's folder twice, side by side, to work between;
 * off keeps the pane in use */
static void set_split(struct browser *b, bool split) {
	struct tab *t = cur_tab(b);
	if (b->mode != MODE_BROWSE || split == (t->split != NULL)) {
		return;
	}
	if (split) {
		struct pane *first = t->pane[0];
		t->pane[1] = pane_new(t);
		c8ui_widget_unparent(first->main);
		t->split = c8ui_split_new(C8UI_HORIZONTAL, first->main,
			t->pane[1]->main, 0);
		/* Halves that stay halves as the window changes (and
		 * stacked, narrow); a drag keeps its proportion */
		c8ui_split_set_share(t->split, 0.5);
		c8ui_split_set_min(t->split, 200, 200);
		t->split->expand = true;
		t->split->fill = true;
		c8ui_widget_add(t->box, t->split);
		show_folder(t->pane[1], first->folder->dir, false);
		t->active = 1;
	} else {
		struct pane *keep = t->pane[t->active];
		struct pane *other = t->pane[!t->active];
		if (b->drop_pane == other) {
			b->drop_pane = NULL;
			b->drop_item = -1;
		}
		c8ui_widget_unparent(keep->main);
		c8ui_widget_destroy(t->split); // the other pane with it
		t->split = NULL;
		t->pane[0] = keep;
		t->pane[1] = NULL;
		t->active = 0;
		c8ui_widget_add(t->box, keep->main);
	}
	for (int i = 0; i < 2; i++) {
		if (t->pane[i]) {
			pane_arrange(t->pane[i]);
		}
	}
	tabs_changed(b);
	c8ui_widget_queue_layout(b->right);
	c8ui_widget_grab_focus(cur(b)->list);
}

static void other_pane(struct browser *b) {
	struct tab *t = cur_tab(b);
	if (t->split) {
		activate(t->pane[!t->active]);
		c8ui_widget_grab_focus(cur(b)->list);
	}
}

static void cmd_new_tab(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	c8ui_appbar_hide(b->bar);
	tab_new(b, cur(b)->folder->dir, b->tab + 1);
	tab_show(b, b->tab + 1);
}

static void cmd_split(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	c8ui_appbar_hide(b->bar);
	set_split(b, c8ui_appbar_command_get_toggle(w));
}

/* Pinning: anything kept in the list on the left */

static void pin_selection(struct browser *b) {
	struct pane *p = cur(b);
	if (in_trash(p)) {
		return;
	}
	bool any = false;
	for (guint i = 0; i < p->folder->shown->len; i++) {
		if (c8ui_list_is_selected(p->list, i)) {
			struct entry *e = p->folder->shown->pdata[i];
			places_pin(e->target ? e->target : e->file, e->dir);
			any = true;
		}
	}
	if (!any && !in_network(p)) {
		places_pin(p->folder->dir, true); // nothing picked: this folder
	}
}

static void cmd_pin(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	c8ui_appbar_hide(b->bar);
	pin_selection(b);
}

static void cmd_pin_folder(struct c8ui_widget *w, void *data) {
	struct browser *b = data;
	c8ui_appbar_hide(b->bar);
	places_pin(cur(b)->folder->dir, true);
}

/* The tab strip: a tab each, the one shown joined to the page under it,
 * a cross to close on the one pointed at, and a + after the last */

static double strip_tab_width(struct browser *b) {
	double width = (b->strip->rect.width - TAB_H) / b->tabs->len;
	return width > TAB_MAX_W ? TAB_MAX_W : width < 1 ? 1 : width;
}

/* The tab at x, y: its index, the count for the +, or -1; close when on
 * its cross */
static int strip_at(struct browser *b, double x, double y, bool *close) {
	const struct c8ui_rect *r = &b->strip->rect;
	*close = false;
	if (!c8ui_rect_contains(r, x, y)) {
		return -1;
	}
	double width = strip_tab_width(b);
	int n = b->tabs->len;
	int i = (int)floor((x - r->x) / width);
	if (i >= n) {
		return x < r->x + n * width + TAB_H ? n : -1;
	}
	*close = width >= TAB_MIN_W && x > r->x + (i + 1) * width - 32;
	return i;
}

static void strip_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	*width = avail;
	*height = TAB_H;
}

static void draw_cross(cairo_t *cr, double cx, double cy, double arm) {
	cairo_set_line_width(cr, 1.5);
	cairo_move_to(cr, cx - arm, cy - arm);
	cairo_line_to(cr, cx + arm, cy + arm);
	cairo_move_to(cr, cx + arm, cy - arm);
	cairo_line_to(cr, cx - arm, cy + arm);
	cairo_stroke(cr);
}

static void strip_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct browser *b = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	const struct c8ui_rect *r = &w->rect;
	const char *family = c8ui_widget_font(w);
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY);
	double tw, th;
	c8ui_text_size(family, font, "Ag", 0, 0, &tw, &th);
	c8ui_set_source(cr, 0xf0f0f0, 1);
	cairo_rectangle(cr, r->x, r->y, r->width, r->height);
	cairo_fill(cr);
	double width = strip_tab_width(b);
	int n = b->tabs->len;
	for (int i = 0; i < n; i++) {
		struct tab *t = b->tabs->pdata[i];
		struct pane *p = t->pane[t->active];
		double x = r->x + i * width;
		bool shown = i == b->tab, hover = i == b->strip_hover;
		if (shown) {
			c8ui_set_source(cr, c.bg, 1);
			cairo_rectangle(cr, x, r->y, width, r->height);
			cairo_fill(cr);
			c8ui_set_source(cr, c.accent, 1);
			cairo_rectangle(cr, x, r->y, width, 3);
			cairo_fill(cr);
		} else if (hover) {
			c8ui_set_source(cr, c.fg, c.fill);
			cairo_rectangle(cr, x, r->y, width, r->height);
			cairo_fill(cr);
		}
		bool cross = (shown || hover) && width >= TAB_MIN_W;
		double room = width - 16 - (cross ? 32 : 12);
		if (p && p->folder && room > 8) {
			char *title = folder_title(p->folder->dir);
			c8ui_set_source(cr, c.fg, shown ? 1 : c.fg_secondary);
			c8ui_text_draw(cr, family, font, title, x + 16,
				r->y + (r->height - th) / 2, room, 1);
			g_free(title);
		}
		if (cross) {
			bool on = hover && b->strip_close;
			if (on) {
				c8ui_set_source(cr, c.fg, c.fill * 2);
				cairo_rectangle(cr, x + width - 30, r->y + 8, 24,
					r->height - 16);
				cairo_fill(cr);
			}
			c8ui_set_source(cr, c.fg, on ? 1 : c.fg_secondary);
			draw_cross(cr, x + width - 18, r->y + r->height / 2, 4.5);
		}
	}
	/* New tab */
	double px = r->x + n * width;
	if (b->strip_hover == n) {
		c8ui_set_source(cr, c.fg, c.fill);
		cairo_rectangle(cr, px, r->y, TAB_H, r->height);
		cairo_fill(cr);
	}
	c8ui_set_source(cr, c.fg, c.fg_secondary);
	cairo_set_line_width(cr, 1.5);
	double cx = px + TAB_H / 2, cy = r->y + r->height / 2;
	cairo_move_to(cr, cx - 6, cy);
	cairo_line_to(cr, cx + 6, cy);
	cairo_move_to(cr, cx, cy - 6);
	cairo_line_to(cr, cx, cy + 6);
	cairo_stroke(cr);
}

static bool strip_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct browser *b = w->data;
	bool close;
	switch (ev->type) {
	case C8UI_EVENT_MOTION:
	case C8UI_EVENT_ENTER: {
		int i = strip_at(b, ev->x, ev->y, &close);
		if (i != b->strip_hover || close != b->strip_close) {
			b->strip_hover = i;
			b->strip_close = close;
			c8ui_widget_queue_draw(w);
		}
		return false;
	}
	case C8UI_EVENT_LEAVE:
		b->strip_hover = -1;
		c8ui_widget_queue_draw(w);
		return false;
	case C8UI_EVENT_PRESS: {
		int i = strip_at(b, ev->x, ev->y, &close);
		int n = b->tabs->len;
		if (i < 0) {
			return false;
		}
		if (i == n) {
			if (ev->button == C8UI_BUTTON_LEFT) {
				tab_new(b, cur(b)->folder->dir, n);
				tab_show(b, n);
			}
		} else if (ev->button == BUTTON_MIDDLE ||
				(ev->button == C8UI_BUTTON_LEFT && close)) {
			tab_close(b, i);
		} else if (ev->button == C8UI_BUTTON_LEFT) {
			tab_show(b, i);
		}
		return true;
	}
	case C8UI_EVENT_SCROLL:
		/* The wheel over the tabs goes through them */
		if (!ev->precise && ev->dy != 0) {
			int to = b->tab + (ev->dy > 0 ? 1 : -1);
			if (to >= 0 && to < (int)b->tabs->len) {
				tab_show(b, to);
			}
			return true;
		}
		return false;
	default:
		return false;
	}
}

static const struct c8ui_widget_impl strip_impl = {
	.name = "files-tabs",
	.measure = strip_measure,
	.draw = strip_draw,
	.event = strip_event,
};

static struct c8ui_widget *command(struct browser *b, const char *icon,
		const char *label, bool right, c8ui_action_fn fn) {
	return c8ui_appbar_add(b->bar, icon, label, right, fn, b);
}

static struct browser *build(enum browser_mode mode, const char *title,
		const char *parent) {
	struct browser *b = calloc(1, sizeof(*b));
	b->mode = mode;
	b->tabs = g_ptr_array_new();
	b->strip_hover = -1;
	b->drop_item = b->drop_place = -1;
	b->win = c8ui_window_new(files_app(), title ? title : "Files",
		mode == MODE_BROWSE ? 1100 : 960, mode == MODE_BROWSE ? 720 : 640);
	if (parent) {
		c8ui_window_set_parent_handle(b->win, parent);
	}
	b->root = c8ui_window_root(b->win);
	c8ui_root_set_key_handler(b->root, key, b);
	places_init();

	b->page = c8ui_box_new(C8UI_HORIZONTAL, 0);
	b->page->fill = true;
	b->page->user_data = b;
	b->page->on_destroy = browser_gone;

	/* Places */
	struct c8ui_widget *side = b->side = c8ui_box_new(C8UI_VERTICAL, 0);
	side->fixed_width = SIDE_WIDTH;
	side->fill = true;
	c8ui_widget_set_background(side, 0xf0f0f0);
	c8ui_box_set_padding(side, 0, 44, 0, 0);
	struct c8ui_widget *app = c8ui_label_new(mode == MODE_BROWSE ? "Files" :
		title ? title : mode == MODE_SAVE ? "Save" : "Open",
		C8UI_TEXT_SUBHEADER);
	struct c8ui_widget *app_box = c8ui_box_new(C8UI_HORIZONTAL, 12);
	c8ui_box_set_padding(app_box, 24, 4, 16, 24);
	b->places_back = c8ui_back_button_new(places_back_clicked, b);
	b->places_back->align = C8UI_ALIGN_CENTER;
	b->places_back->hidden = true;
	c8ui_widget_add(app_box, b->places_back);
	c8ui_label_set_max_lines(app, 2);
	app->expand = true;
	app->align = C8UI_ALIGN_CENTER;
	c8ui_widget_add(app_box, app);
	c8ui_widget_add(side, app_box);
	b->places = c8ui_list_new(C8UI_LIST_ROWS, 0, PLACE_H, draw_place, b);
	c8ui_list_set_click_opens(b->places, true);
	c8ui_list_on_open(b->places, open_place, b);
	c8ui_list_on_context(b->places, place_context, b);
	b->places_scroll = c8ui_scroll_new(b->places);
	b->places_scroll->expand = true;
	b->places_scroll->fill = true;
	c8ui_widget_add(side, b->places_scroll);
	c8ui_widget_add(b->page, side);

	/* The folders: the tabs' strip, the tab shown, what's being done */
	struct c8ui_widget *right = b->right = c8ui_box_new(C8UI_VERTICAL, 0);
	right->expand = true;
	right->fill = true;
	b->strip = c8ui_widget_new(&strip_impl, b);
	b->strip->fill = true;
	b->strip->hidden = true;
	c8ui_widget_add(right, b->strip);
	b->stack = c8ui_stack_new();
	b->stack->expand = true;
	b->stack->fill = true;
	c8ui_widget_add(right, b->stack);
	b->ops = c8ui_box_new(C8UI_VERTICAL, 12);
	b->ops->fill = true;
	b->ops->hidden = true;
	c8ui_widget_set_background(b->ops, 0xf0f0f0);
	c8ui_box_set_padding(b->ops, 24, 14, 24, 14);
	c8ui_widget_add(right, b->ops);
	c8ui_widget_add(b->page, right);

	/* The app bar: what to do with the selection on the left, the rest
	 * on the right */
	b->bar = c8ui_appbar_new(b->root);
	b->cmd.open = command(b, "document-open", "Open", false, cmd_open);
	b->cmd.open_with = command(b, "document-open-with", "Open with", false,
		cmd_open_with);
	b->cmd.extract = command(b, "archive-extract", "Extract", false,
		cmd_extract);
	b->cmd.props = command(b, "document-properties", "Properties", false,
		cmd_props);
	b->cmd.copy = command(b, "edit-copy", "Copy", false, cmd_copy);
	b->cmd.cut = command(b, "edit-cut", "Cut", false, cmd_cut);
	b->cmd.rename = command(b, "edit-rename", "Rename", false, cmd_rename);
	b->cmd.trash = command(b, "edit-delete", "Delete", false, cmd_trash);
	b->cmd.restore = command(b, "edit-undo", "Restore", false, cmd_restore);
	b->cmd.erase = command(b, "edit-delete", "Delete for good", false,
		cmd_erase);
	b->cmd.compress = command(b, "archive-insert", "Compress", false,
		cmd_compress);
	b->cmd.pin = command(b, "view-pin", "Pin", false, cmd_pin);
	b->cmd.paste = command(b, "edit-paste", "Paste", true, cmd_paste);
	b->cmd.new_folder = command(b, "folder-new", "New folder", true,
		cmd_new_folder);
	b->cmd.extract_all = command(b, "archive-extract", "Extract all", true,
		cmd_extract_all);
	b->cmd.connect = command(b, "network-server", "Connect to a server", true,
		cmd_connect);
	b->cmd.empty_trash = command(b, "emptytrash", "Empty Trash", true,
		cmd_empty_trash);
	b->cmd.select_all = command(b, "edit-select-all", "Select all", true,
		cmd_select_all);
	b->cmd.details = command(b, "view-list", "Details", true, cmd_details);
	c8ui_appbar_command_set_toggle(b->cmd.details, false);
	b->cmd.hidden = command(b, "view-reveal", "Hidden items", true,
		cmd_hidden);
	b->cmd.pin_folder = command(b, "view-pin", "Pin this folder", true,
		cmd_pin_folder);
	b->cmd.split = command(b, "view-split-left-right", "Split view", true,
		cmd_split);
	c8ui_appbar_command_set_toggle(b->cmd.split, false);
	b->cmd.new_tab = command(b, "tab-new", "New tab", true, cmd_new_tab);
	if (mode != MODE_BROWSE) {
		b->cmd.select_all->hidden = mode == MODE_SAVE;
		b->cmd.pin->hidden = b->cmd.pin_folder->hidden = true;
		b->cmd.split->hidden = b->cmd.new_tab->hidden = true;
	}

	struct c8ui_widget *outer = b->page;
	if (mode != MODE_BROWSE) {
		/* The band at the bottom: name, filter, answer */
		outer = c8ui_box_new(C8UI_VERTICAL, 0);
		outer->fill = true;
		b->page->expand = true;
		c8ui_widget_add(outer, b->page);
		struct c8ui_widget *band = b->pick.band = c8ui_box_new(C8UI_VERTICAL,
			12);
		band->fill = true;
		c8ui_widget_set_background(band, 0xf0f0f0);
		c8ui_box_set_padding(band, 24, 16, 24, 16);
		if (mode == MODE_SAVE) {
			b->pick.name = c8ui_entry_new(NULL, "", name_entered, b);
			c8ui_entry_set_placeholder(b->pick.name, "File name");
			b->pick.name->align = C8UI_ALIGN_CENTER;
		} else {
			b->pick.count = c8ui_label_new("", C8UI_TEXT_BODY);
			b->pick.count->align = C8UI_ALIGN_CENTER;
		}
		b->pick.combo = c8ui_combo_new(NULL, NULL, 0, 0, filter_chosen, b);
		b->pick.combo->fixed_width = 220;
		b->pick.combo->align = C8UI_ALIGN_CENTER;
		b->pick.combo->hidden = true;
		b->pick.accept = c8ui_button_new(mode == MODE_SAVE ? "Save" : "Open",
			accept_clicked, b);
		c8ui_button_set_primary(b->pick.accept, true);
		b->pick.accept->align = C8UI_ALIGN_CENTER;
		b->pick.cancel = c8ui_button_new("Cancel", cancel_clicked, b);
		b->pick.cancel->align = C8UI_ALIGN_CENTER;
		arrange_band(b);
		c8ui_widget_add(outer, band);
	}
	c8ui_root_set_child(b->root, outer);
	c8ui_root_on_resize(b->root, resized, b);
	if (b->mode == MODE_BROWSE) {
		c8ui_window_set_drop(b->win, &drop_impl, b);
	}
	return b;
}

/* The first tab, and with it the window is whole */
static void open_first(struct browser *b, GFile *dir) {
	GFile *home = dir ? NULL : g_file_new_for_path(g_get_home_dir());
	tab_new(b, dir ? dir : home, 0);
	g_clear_object(&home);
	b->places_watch = places_watch(places_changed, b);
	c8_stealth_watch(stealth_changed, b);
	browsers = g_list_prepend(browsers, b);
	apply_prefs(b);
	tabs_changed(b);
}

struct browser *browser_new(GFile *dir) {
	struct browser *b = build(MODE_BROWSE, NULL, NULL);
	open_first(b, dir);
	c8ui_widget_grab_focus(cur(b)->list);
	return b;
}

struct browser *browser_new_picker(const struct pick_options *o) {
	struct browser *b = build(o->mode, o->title, o->parent);
	b->pick.multiple = o->multiple;
	b->pick.folders = o->folders;
	b->pick.filters = o->filters;
	b->pick.filter = o->filter;
	b->pick.done = o->done;
	b->pick.data = o->data;
	if (o->accept) {
		c8ui_button_set_label(b->pick.accept, o->accept);
	} else if (o->folders) {
		c8ui_button_set_label(b->pick.accept, "Choose this folder");
	}
	if (b->pick.filters && b->pick.filters->len > 0) {
		const char **names = calloc(b->pick.filters->len, sizeof(*names));
		for (guint i = 0; i < b->pick.filters->len; i++) {
			names[i] = ((struct pick_filter *)b->pick.filters->pdata[i])->name;
		}
		if (b->pick.filter < 0 || b->pick.filter >= (int)b->pick.filters->len) {
			b->pick.filter = 0;
		}
		c8ui_combo_set_items(b->pick.combo, names, b->pick.filters->len,
			b->pick.filter);
		b->pick.combo->hidden = b->pick.filters->len < 2;
		free(names);
	}
	open_first(b, o->folder);
	if (o->mode == MODE_SAVE) {
		c8ui_entry_set(b->pick.name, o->name ? o->name : "");
		c8ui_widget_grab_focus(b->pick.name);
	} else {
		c8ui_widget_grab_focus(cur(b)->list);
	}
	return b;
}

void browser_present(struct browser *b) {
	browsers = g_list_remove(browsers, b);
	browsers = g_list_prepend(browsers, b);
	c8ui_window_present(b->win);
}

void browser_close(struct browser *b) {
	/* Going reports a cancel to whoever asked, which may know already */
	g_idle_add(close_later, b);
}

struct c8ui_widget *browser_ops_box(struct c8ui_window *win) {
	for (GList *l = browsers; l; l = l->next) {
		struct browser *b = l->data;
		if (b->win == win) {
			return b->ops;
		}
	}
	return NULL;
}

struct c8ui_window *browser_any_window(void) {
	struct browser *b = browser_last();
	return b ? b->win : NULL;
}

struct browser *browser_last(void) {
	for (GList *l = browsers; l; l = l->next) {
		struct browser *b = l->data;
		if (b->mode == MODE_BROWSE) {
			return b;
		}
	}
	return NULL;
}
