/*
 * File operations. Copying, moving, deleting and restoring run on a
 * worker thread each; the window that started one shows it in a band
 * under the folder (ops_box in view.c): what is being done to how many
 * and where to, a bar, the file in hand, how much is done, how fast and
 * how long is left, and a Cancel link. When that window closes the
 * newest other one takes it over. A clash with a file
 * already there is asked on the main thread while the worker waits. The
 * app stays up until every operation is done, windows or not.
 */
#define _GNU_SOURCE
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "ops.h"
#include "stealth.h"

#define TICK_MS 200 // progress shown this often
#define SHOW_AFTER_MS 600 // quick ones never show a row

/* Defined in view.c: where a window shows its operations, and a window
 * to show one whose own has gone (NULL: none open) */
struct c8ui_widget *browser_ops_box(struct c8ui_window *win);
struct c8ui_window *browser_any_window(void);

enum op_kind {
	OP_COPY,
	OP_MOVE,
	OP_TRASH,
	OP_DELETE,
	OP_RESTORE,
	OP_EXTRACT,
	OP_COMPRESS,
};

enum clash {
	CLASH_ASK,
	CLASH_REPLACE,
	CLASH_SKIP,
	CLASH_BOTH, // keep both: the new one gets another name
};

struct op {
	enum op_kind kind;
	GList *files; // GFile
	GFile *into; // copy, move and extract; compress: the archive
	enum arc_format format; // compress
	struct c8ui_window *win; // NULL once it closed
	GCancellable *cancel;
	/* Progress, from the worker; done and current under lock */
	gint64 total, done; // bytes (or items for delete and trash)
	gint64 items, items_done; // files, folders apart (copy and move)
	gint64 started;
	/* How fast, from one tick to the next, smoothed (main thread) */
	gint64 seen_done, seen_at;
	double speed; // bytes a second; 0 until known
	GMutex lock;
	char *current; // the name being done
	/* A clash: the worker waits for the answer */
	GCond answered;
	enum clash clash_all; // after "do this for all"
	enum clash answer;
	bool asking;
	char *clash_name;
	/* A password: the same wait, the answer in secret */
	char *secret_name, *secret;
	bool secret_again;
	struct c8ui_widget *secret_dialog, *secret_entry;
	/* What it made, for whoever started it (extract and compress) */
	GFile *made;
	made_fn made_cb;
	void *made_data;
	/* What went wrong */
	GPtrArray *failed; // char *: "name: why"
	GPtrArray *untrashable; // GFile: no trash where they are
	/* UI */
	struct c8ui_widget *row, *label, *bar, *detail;
	guint tick;
	char *verb; // "Copying"
	char *what; // "12 items", or the one's name
	char *where; // "to Pictures"
};

static GList *ops;
static GList *quick; // struct made: renames and new folders under way

static void run(struct op *op);

/* Little things */

/* A name like name in dir that isn't taken: "a (2).txt" */
GFile *files_unique_child(GFile *dir, const char *name) {
	GFile *f = g_file_get_child(dir, name);
	if (!g_file_query_exists(f, NULL)) {
		return f;
	}
	g_object_unref(f);
	/* "photo.jpg" → "photo (2).jpg"; folders and ".bashrc" have none */
	const char *dot = strrchr(name, '.');
	if (dot == name) {
		dot = NULL;
	}
	char *stem = dot ? g_strndup(name, dot - name) : g_strdup(name);
	for (int i = 2;; i++) {
		char *try = g_strdup_printf("%s (%d)%s", stem, i, dot ? dot : "");
		f = g_file_get_child(dir, try);
		g_free(try);
		if (!g_file_query_exists(f, NULL)) {
			break;
		}
		g_object_unref(f);
	}
	g_free(stem);
	return f;
}

static char *display_name(GFile *file) {
	GFileInfo *info = g_file_query_info(file,
		G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME, G_FILE_QUERY_INFO_NONE, NULL,
		NULL);
	char *name = info ? g_strdup(g_file_info_get_display_name(info)) : NULL;
	if (info) {
		g_object_unref(info);
	}
	return name ? name : g_file_get_basename(file);
}

static void fail(struct op *op, GFile *file, const GError *error) {
	char *name = display_name(file);
	g_mutex_lock(&op->lock);
	g_ptr_array_add(op->failed, g_strdup_printf("%s: %s", name,
		error->message));
	g_mutex_unlock(&op->lock);
	g_free(name);
}

static void set_done(struct op *op, gint64 done) {
	g_mutex_lock(&op->lock);
	op->done = done;
	g_mutex_unlock(&op->lock);
}

static gint64 get_done(struct op *op) {
	g_mutex_lock(&op->lock);
	gint64 done = op->done;
	g_mutex_unlock(&op->lock);
	return done;
}

static void items_did(struct op *op, gint64 n) {
	g_mutex_lock(&op->lock);
	op->items_done += n;
	g_mutex_unlock(&op->lock);
}

static void set_current(struct op *op, GFile *file) {
	char *name = g_file_get_basename(file);
	g_mutex_lock(&op->lock);
	g_free(op->current);
	op->current = name;
	g_mutex_unlock(&op->lock);
}

/* Clashes, asked on the main thread */

static void give_answer(struct op *op, enum clash answer) {
	g_mutex_lock(&op->lock);
	if (op->asking) {
		op->answer = answer;
		op->asking = false;
		g_cond_signal(&op->answered);
	}
	g_mutex_unlock(&op->lock);
}

static void clash_chosen(int choice, void *data) {
	give_answer(data, choice == 0 ? CLASH_REPLACE :
		choice == 1 ? CLASH_BOTH : CLASH_SKIP);
}

static gboolean ask_clash(gpointer data) {
	struct op *op = data;
	if (op->win == NULL) {
		give_answer(op, CLASH_SKIP); // nobody to ask: leave it be
		return G_SOURCE_REMOVE;
	}
	char *message = g_strdup_printf("There's already something called %s "
		"in the folder. Replace it, keep both (the new one gets another "
		"name), or skip it?", c8_stealth_show(op->clash_name));
	const char *buttons[] = { "Replace", "Keep both", "Skip" };
	c8ui_dialog_show(c8ui_window_root(op->win), "Replace or skip?", message,
		buttons, 3, clash_chosen, op);
	g_free(message);
	return G_SOURCE_REMOVE;
}

/* From the worker: what to do with dest, which exists */
static enum clash clash(struct op *op, GFile *dest) {
	if (op->clash_all != CLASH_ASK) {
		return op->clash_all;
	}
	g_mutex_lock(&op->lock);
	g_free(op->clash_name);
	op->clash_name = display_name(dest);
	op->asking = true;
	g_idle_add(ask_clash, op);
	while (op->asking) {
		g_cond_wait(&op->answered, &op->lock);
	}
	enum clash answer = op->answer;
	g_mutex_unlock(&op->lock);
	/* The same for the rest of this operation: asking for each of a
	 * thousand photos helps nobody */
	op->clash_all = answer;
	return answer;
}

/* A password, asked the same way */

static void secret_answered(int choice, void *data) {
	struct op *op = data;
	/* Read only on OK: the box is still there then */
	char *typed = choice == 0 && op->secret_entry ?
		g_strdup(c8ui_entry_get(op->secret_entry)) : NULL;
	op->secret_dialog = op->secret_entry = NULL;
	g_mutex_lock(&op->lock);
	if (op->asking) {
		op->secret = typed;
		typed = NULL;
		op->asking = false;
		g_cond_signal(&op->answered);
	}
	g_mutex_unlock(&op->lock);
	g_free(typed);
}

static void secret_enter(struct c8ui_widget *entry, void *data) {
	struct op *op = data;
	if (op->secret_dialog) {
		c8ui_dialog_choose(op->secret_dialog, 0);
	}
}

static gboolean ask_secret(gpointer data) {
	struct op *op = data;
	if (op->win == NULL) {
		give_answer(op, CLASH_SKIP); // nobody to ask: no password
		return G_SOURCE_REMOVE;
	}
	char *message = g_strdup_printf(op->secret_again ?
		"That password didn't open %s. Try again." :
		"%s is protected with a password.", op->secret_name);
	static const char *const buttons[] = { "OK", "Cancel" };
	op->secret_dialog = c8ui_dialog_show(c8ui_window_root(op->win),
		"Password needed", message, buttons, 2,
		secret_answered, op);
	g_free(message);
	op->secret_entry = c8ui_entry_new("Password", "", secret_enter, op);
	c8ui_entry_set_password(op->secret_entry, true);
	c8ui_dialog_add(op->secret_dialog, op->secret_entry);
	c8ui_widget_grab_focus(op->secret_entry);
	return G_SOURCE_REMOVE;
}

char *op_ask_password(struct op *op, const char *name, bool again) {
	if (g_cancellable_is_cancelled(op->cancel)) {
		return NULL;
	}
	g_mutex_lock(&op->lock);
	g_free(op->secret_name);
	op->secret_name = g_strdup(name);
	op->secret_again = again;
	g_clear_pointer(&op->secret, g_free);
	op->asking = true;
	g_idle_add(ask_secret, op);
	while (op->asking) {
		g_cond_wait(&op->answered, &op->lock);
	}
	char *secret = op->secret;
	op->secret = NULL;
	g_mutex_unlock(&op->lock);
	return secret;
}

/* For archive.c's workers */

GCancellable *op_cancellable(struct op *op) {
	return op->cancel;
}

bool op_cancelled(struct op *op) {
	return g_cancellable_is_cancelled(op->cancel);
}

void op_set_total(struct op *op, gint64 total) {
	g_mutex_lock(&op->lock);
	op->total = total;
	g_mutex_unlock(&op->lock);
}

void op_set_done(struct op *op, gint64 done) {
	set_done(op, done);
}

gint64 op_get_done(struct op *op) {
	return get_done(op);
}

void op_set_current(struct op *op, const char *name) {
	g_mutex_lock(&op->lock);
	g_free(op->current);
	op->current = g_strdup(name);
	g_mutex_unlock(&op->lock);
}

void op_fail(struct op *op, const char *name, const char *why) {
	g_mutex_lock(&op->lock);
	g_ptr_array_add(op->failed, g_strdup_printf("%s: %s", name,
		why ? why : "It didn't work"));
	g_mutex_unlock(&op->lock);
}

void op_item_done(struct op *op) {
	items_did(op, 1);
}

void op_made(struct op *op, GFile *file) {
	g_set_object(&op->made, file); // read when the worker is done
}

/* Copying */

static gint64 measure(struct op *op, GFile *file) {
	GFileInfo *info = g_file_query_info(file, G_FILE_ATTRIBUTE_STANDARD_TYPE
		"," G_FILE_ATTRIBUTE_STANDARD_SIZE, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
		op->cancel, NULL);
	if (info == NULL) {
		return 0;
	}
	gint64 size = g_file_info_get_size(info);
	bool dir = g_file_info_get_file_type(info) == G_FILE_TYPE_DIRECTORY;
	g_object_unref(info);
	if (!dir) {
		op->items++;
		return size > 0 ? size : 1;
	}
	gint64 total = 1;
	GFileEnumerator *en = g_file_enumerate_children(file,
		G_FILE_ATTRIBUTE_STANDARD_NAME, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
		op->cancel, NULL);
	GFileInfo *child;
	while (en && (child = g_file_enumerator_next_file(en, op->cancel, NULL))) {
		GFile *f = g_file_enumerator_get_child(en, child);
		total += measure(op, f);
		g_object_unref(f);
		g_object_unref(child);
	}
	g_clear_object(&en);
	return total;
}

gint64 op_measure(struct op *op, GFile *file) {
	return measure(op, file);
}

struct progress {
	struct op *op;
	gint64 base;
};

static void copied_some(goffset current, goffset total, gpointer data) {
	struct progress *p = data;
	set_done(p->op, p->base + current);
}

static bool remove_tree(struct op *op, GFile *file, GError **error);

static bool copy_tree(struct op *op, GFile *src, GFile *dest, bool move) {
	GError *error = NULL;
	GFileInfo *info = g_file_query_info(src, G_FILE_ATTRIBUTE_STANDARD_TYPE
		"," G_FILE_ATTRIBUTE_STANDARD_SIZE, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
		op->cancel, &error);
	if (info == NULL) {
		fail(op, src, error);
		g_error_free(error);
		return false;
	}
	bool dir = g_file_info_get_file_type(info) == G_FILE_TYPE_DIRECTORY;
	gint64 size = g_file_info_get_size(info);
	g_object_unref(info);
	set_current(op, src);

	if (dir) {
		/* Into a folder of the same name: the two are merged */
		if (!g_file_make_directory(dest, op->cancel, &error) &&
				!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_EXISTS)) {
			fail(op, src, error);
			g_error_free(error);
			return false;
		}
		if (error) {
			/* Something of that name is there. Only a real folder is
			 * merged into: through a link to one the files would land
			 * wherever it points */
			g_clear_error(&error);
			GFileInfo *there = g_file_query_info(dest,
				G_FILE_ATTRIBUTE_STANDARD_TYPE,
				G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, op->cancel, NULL);
			bool folder = there &&
				g_file_info_get_file_type(there) == G_FILE_TYPE_DIRECTORY;
			g_clear_object(&there);
			if (!folder) {
				g_set_error(&error, G_IO_ERROR, G_IO_ERROR_NOT_DIRECTORY,
					"Something that isn't a folder has its name there");
				fail(op, src, error);
				g_error_free(error);
				return false;
			}
		}
		set_done(op, get_done(op) + 1);
		bool ok = true;
		GFileEnumerator *en = g_file_enumerate_children(src,
			G_FILE_ATTRIBUTE_STANDARD_NAME, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
			op->cancel, &error);
		if (en == NULL) {
			fail(op, src, error);
			g_error_free(error);
			return false;
		}
		GFileInfo *child;
		while ((child = g_file_enumerator_next_file(en, op->cancel, NULL))) {
			GFile *from = g_file_enumerator_get_child(en, child);
			GFile *to = g_file_get_child(dest, g_file_info_get_name(child));
			ok = copy_tree(op, from, to, move) && ok;
			g_object_unref(to);
			g_object_unref(from);
			g_object_unref(child);
			if (g_cancellable_is_cancelled(op->cancel)) {
				ok = false;
				break;
			}
		}
		g_object_unref(en);
		if (ok && move && !g_file_delete(src, op->cancel, &error)) {
			fail(op, src, error);
			g_clear_error(&error);
		}
		return ok;
	}

	GFileCopyFlags flags = G_FILE_COPY_NOFOLLOW_SYMLINKS |
		G_FILE_COPY_ALL_METADATA;
	GFile *to = g_object_ref(dest);
	if (g_file_query_exists(to, NULL)) {
		switch (clash(op, to)) {
		case CLASH_REPLACE:
			flags |= G_FILE_COPY_OVERWRITE;
			break;
		case CLASH_BOTH: {
			GFile *parent = g_file_get_parent(to);
			char *name = g_file_get_basename(to);
			g_object_unref(to);
			to = files_unique_child(parent, name);
			g_free(name);
			g_object_unref(parent);
			break;
		}
		case CLASH_SKIP:
		case CLASH_ASK:
			set_done(op, get_done(op) + (size > 0 ? size : 1));
			items_did(op, 1);
			g_object_unref(to);
			return true;
		}
	}
	struct progress p = { op, get_done(op) };
	bool ok = move ?
		g_file_move(src, to, flags, op->cancel, copied_some, &p, &error) :
		g_file_copy(src, to, flags, op->cancel, copied_some, &p, &error);
	if (!ok && !g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
		fail(op, src, error);
	}
	g_clear_error(&error);
	g_object_unref(to);
	set_done(op, p.base + (size > 0 ? size : 1));
	items_did(op, 1);
	return ok;
}

/* bytes and items: what measure made of src, for a move that needs no
 * copying to count as that much done */
static void copy_one(struct op *op, GFile *src, gint64 bytes, gint64 items) {
	char *name = g_file_get_basename(src);
	GFile *dest = g_file_get_child(op->into, name);
	g_free(name);
	GError *error = NULL;
	if (g_file_equal(src, dest)) {
		if (op->kind == OP_MOVE) {
			g_object_unref(dest);
			return; // moved where it is
		}
		/* Pasted into its own folder: a copy beside it */
		char *base = g_file_get_basename(src);
		g_object_unref(dest);
		dest = files_unique_child(op->into, base);
		g_free(base);
	}
	if (g_file_has_prefix(op->into, src)) {
		g_set_error_literal(&error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
			"A folder can't go inside itself");
		fail(op, src, error);
		g_error_free(error);
		g_object_unref(dest);
		return;
	}
	if (op->kind == OP_MOVE) {
		/* On the same drive a move is a rename: try that first */
		set_current(op, src);
		if (g_file_move(src, dest, G_FILE_COPY_NOFOLLOW_SYMLINKS |
				G_FILE_COPY_NO_FALLBACK_FOR_MOVE | G_FILE_COPY_ALL_METADATA,
				op->cancel, NULL, NULL, &error)) {
			set_done(op, get_done(op) + bytes);
			items_did(op, items);
			g_object_unref(dest);
			return;
		}
		/* Across drives, a folder there to merge into, or a clash:
		 * the long way handles them all */
		g_clear_error(&error);
	}
	copy_tree(op, src, dest, op->kind == OP_MOVE);
	g_object_unref(dest);
}

/* Deleting */

/* A folder on this PC is walked by descriptor, never by path again: a
 * path could be swapped for a link to somewhere else between looking
 * and deleting (a folder in /tmp that someone else can write to), and
 * what's there would go instead. */
static bool remove_at(struct op *op, int dirfd, const char *name,
		GError **error) {
	if (unlinkat(dirfd, name, 0) == 0) {
		return true;
	}
	if (errno != EISDIR && errno != EPERM) {
		goto failed;
	}
	int fd = openat(dirfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW |
		O_CLOEXEC);
	if (fd < 0) {
		goto failed;
	}
	DIR *d = fdopendir(fd);
	if (d == NULL) {
		close(fd);
		goto failed;
	}
	bool ok = true;
	struct dirent *e;
	while (ok && (e = readdir(d))) {
		if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0) {
			continue;
		}
		if (g_cancellable_set_error_if_cancelled(op->cancel, error)) {
			ok = false;
			break;
		}
		ok = remove_at(op, fd, e->d_name, error);
	}
	closedir(d);
	if (!ok) {
		return false;
	}
	if (unlinkat(dirfd, name, AT_REMOVEDIR) == 0) {
		return true;
	}
failed:
	g_set_error(error, G_IO_ERROR, g_io_error_from_errno(errno), "%s: %s",
		name, g_strerror(errno));
	return false;
}

static bool remove_tree(struct op *op, GFile *file, GError **error) {
	char *path = g_file_is_native(file) ? g_file_get_path(file) : NULL;
	if (path) {
		char *dir = g_path_get_dirname(path), *name = g_path_get_basename(path);
		int fd = open(dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
		bool ok = false;
		if (fd < 0) {
			g_set_error(error, G_IO_ERROR, g_io_error_from_errno(errno),
				"%s: %s", dir, g_strerror(errno));
		} else {
			ok = remove_at(op, fd, name, error);
			close(fd);
		}
		g_free(dir);
		g_free(name);
		g_free(path);
		return ok;
	}
	if (g_file_delete(file, op->cancel, error)) {
		return true;
	}
	if (!g_error_matches(*error, G_IO_ERROR, G_IO_ERROR_NOT_EMPTY)) {
		return false;
	}
	g_clear_error(error);
	GFileEnumerator *en = g_file_enumerate_children(file,
		G_FILE_ATTRIBUTE_STANDARD_NAME, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
		op->cancel, error);
	if (en == NULL) {
		return false;
	}
	GFileInfo *child;
	bool ok = true;
	while (ok && (child = g_file_enumerator_next_file(en, op->cancel, NULL))) {
		GFile *f = g_file_enumerator_get_child(en, child);
		ok = remove_tree(op, f, error);
		g_object_unref(f);
		g_object_unref(child);
	}
	g_object_unref(en);
	return ok && g_file_delete(file, op->cancel, error);
}

static void restore_one(struct op *op, GFile *file) {
	GError *error = NULL;
	GFileInfo *info = g_file_query_info(file, "trash::orig-path",
		G_FILE_QUERY_INFO_NONE, op->cancel, &error);
	const char *orig = info ? g_file_info_get_attribute_byte_string(info,
		"trash::orig-path") : NULL;
	if (orig == NULL) {
		if (error == NULL) {
			g_set_error_literal(&error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
				"Where it came from isn't known");
		}
		fail(op, file, error);
		g_error_free(error);
		g_clear_object(&info);
		return;
	}
	GFile *dest = g_file_new_for_path(orig);
	GFile *parent = g_file_get_parent(dest);
	if (parent) {
		g_file_make_directory_with_parents(parent, op->cancel, NULL);
		g_object_unref(parent);
	}
	if (g_file_query_exists(dest, NULL)) {
		enum clash c = clash(op, dest);
		if (c == CLASH_BOTH) {
			GFile *p = g_file_get_parent(dest);
			char *name = g_file_get_basename(dest);
			g_object_unref(dest);
			dest = files_unique_child(p, name);
			g_free(name);
			g_object_unref(p);
		} else if (c != CLASH_REPLACE) {
			g_object_unref(dest);
			g_object_unref(info);
			return;
		}
	}
	if (!g_file_move(file, dest, G_FILE_COPY_OVERWRITE |
			G_FILE_COPY_NOFOLLOW_SYMLINKS | G_FILE_COPY_ALL_METADATA,
			op->cancel, NULL, NULL, &error)) {
		fail(op, file, error);
		g_error_free(error);
	}
	g_object_unref(dest);
	g_object_unref(info);
}

/* The worker */

static void work(GTask *task, gpointer source, gpointer data,
		GCancellable *cancel) {
	struct op *op = data;
	guint n = g_list_length(op->files), at = 0;
	if (op->kind == OP_COMPRESS) {
		arc_compress(op, op->files, op->into, op->format);
		g_task_return_boolean(task, TRUE);
		return;
	}
	/* What each of them comes to, counted before the first is touched */
	gint64 *bytes = g_new0(gint64, n + 1), *items = g_new0(gint64, n + 1);
	if (op->kind == OP_COPY || op->kind == OP_MOVE) {
		gint64 total = 0;
		for (GList *l = op->files; l; l = l->next, at++) {
			gint64 before = op->items;
			bytes[at] = measure(op, l->data);
			items[at] = op->items - before;
			total += bytes[at];
		}
		g_mutex_lock(&op->lock);
		op->total = total;
		g_mutex_unlock(&op->lock);
	} else if (op->kind == OP_EXTRACT) {
		/* How far through the archives' own bytes: what's inside isn't
		 * known until it has been read */
		gint64 total = 0;
		for (GList *l = op->files; l; l = l->next, at++) {
			GFileInfo *info = g_file_query_info(l->data,
				G_FILE_ATTRIBUTE_STANDARD_SIZE, G_FILE_QUERY_INFO_NONE,
				op->cancel, NULL);
			bytes[at] = info ? MAX(g_file_info_get_size(info), 1) : 1;
			g_clear_object(&info);
			total += bytes[at];
		}
		op_set_total(op, total);
	} else {
		op->total = n;
	}
	gint64 before = 0;
	at = 0;
	for (GList *l = op->files; l; l = l->next, at++) {
		if (g_cancellable_is_cancelled(op->cancel)) {
			break;
		}
		GFile *file = l->data;
		GError *error = NULL;
		switch (op->kind) {
		case OP_COPY:
		case OP_MOVE:
			copy_one(op, file, bytes[at], items[at]);
			break;
		case OP_TRASH:
			set_current(op, file);
			if (!g_file_trash(file, op->cancel, &error)) {
				if (g_error_matches(error, G_IO_ERROR,
						G_IO_ERROR_NOT_SUPPORTED)) {
					g_ptr_array_add(op->untrashable, g_object_ref(file));
				} else {
					fail(op, file, error);
				}
				g_error_free(error);
			}
			set_done(op, get_done(op) + 1);
			break;
		case OP_DELETE:
			set_current(op, file);
			if (!remove_tree(op, file, &error) && error &&
					!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
				fail(op, file, error);
			}
			g_clear_error(&error);
			set_done(op, get_done(op) + 1);
			break;
		case OP_RESTORE:
			set_current(op, file);
			restore_one(op, file);
			set_done(op, get_done(op) + 1);
			break;
		case OP_EXTRACT:
			arc_extract(op, file, op->into, before);
			before += bytes[at];
			set_done(op, before);
			break;
		case OP_COMPRESS:
			break;
		}
	}
	g_free(bytes);
	g_free(items);
	g_task_return_boolean(task, TRUE);
}

/* The row in the window */

static void cancel_clicked(struct c8ui_widget *w, void *data) {
	struct op *op = data;
	g_cancellable_cancel(op->cancel);
}

static void row_gone(struct c8ui_widget *w, void *data) {
	struct op *op = data;
	op->row = op->label = op->bar = op->detail = NULL;
}

/* What it's doing, and Cancel; the bar; then the file and the figures */
static void show_row(struct op *op) {
	if (op->win == NULL) {
		/* Its window closed: another shows it, and hears how it went */
		op->win = browser_any_window();
	}
	struct c8ui_widget *box = op->win ? browser_ops_box(op->win) : NULL;
	if (box == NULL) {
		return;
	}
	op->row = c8ui_box_new(C8UI_VERTICAL, 6);
	op->row->fill = true;
	op->row->user_data = op;
	op->row->on_destroy = row_gone;
	struct c8ui_widget *top = c8ui_box_new(C8UI_HORIZONTAL, 16);
	top->fill = true;
	op->label = c8ui_label_new("", C8UI_TEXT_BODY_STRONG);
	c8ui_label_set_max_lines(op->label, 1);
	op->label->expand = true;
	op->label->align = C8UI_ALIGN_CENTER;
	c8ui_widget_add(top, op->label);
	struct c8ui_widget *cancel = c8ui_link_new("Cancel", cancel_clicked, op);
	cancel->align = C8UI_ALIGN_CENTER;
	c8ui_widget_add(top, cancel);
	c8ui_widget_add(op->row, top);
	op->bar = c8ui_progress_new(-1);
	op->bar->fill = true;
	c8ui_widget_add(op->row, op->bar);
	op->detail = c8ui_label_new("", C8UI_TEXT_CAPTION);
	c8ui_label_set_color(op->detail, C8UI_COLOR_SECONDARY);
	c8ui_label_set_max_lines(op->detail, 1);
	op->detail->fill = true;
	c8ui_widget_add(op->row, op->detail);
	c8ui_widget_add(box, op->row);
	box->hidden = false;
	c8ui_widget_queue_layout(box->parent ? box->parent : box);
}

/* "About 2 minutes left": rough on purpose, the speed wanders */
static char *time_left(double seconds) {
	if (seconds < 5) {
		return g_strdup("a few seconds left");
	}
	if (seconds < 55) {
		return g_strdup_printf("about %d seconds left",
			(int)(seconds / 5 + 0.5) * 5);
	}
	if (seconds < 3300) {
		int m = (int)(seconds / 60 + 0.5);
		return g_strdup_printf("about %d minute%s left", m, m == 1 ? "" : "s");
	}
	int h = (int)(seconds / 3600 + 0.5);
	return g_strdup_printf("about %d hour%s left", h, h == 1 ? "" : "s");
}

static gboolean tick(gpointer data) {
	struct op *op = data;
	g_mutex_lock(&op->lock);
	gint64 done = op->done, total = op->total;
	gint64 items = op->items, items_done = op->items_done;
	char *current = g_strdup(op->current);
	bool asking = op->asking;
	g_mutex_unlock(&op->lock);
	bool bytes = op->kind == OP_COPY || op->kind == OP_MOVE ||
		op->kind == OP_EXTRACT || op->kind == OP_COMPRESS;
	gint64 now = g_get_monotonic_time();
	/* Not while a question waits: nothing moves then */
	if (bytes && !asking && op->seen_at && now > op->seen_at) {
		double rate = (done - op->seen_done) * 1e6 / (now - op->seen_at);
		op->speed = op->speed > 0 ? op->speed * 0.8 + rate * 0.2 : rate;
	}
	op->seen_done = done;
	op->seen_at = now;
	if (op->row == NULL) {
		if (now - op->started >= SHOW_AFTER_MS * 1000) {
			show_row(op);
		}
		if (op->row == NULL) {
			g_free(current);
			return G_SOURCE_CONTINUE;
		}
	}
	guint n = g_list_length(op->files);
	char *title = g_strdup_printf("%s %s%s%s", op->verb, op->what,
		op->where ? " " : "", op->where ? op->where : "");
	char *shown = c8_stealth_text(title);
	c8ui_label_set_text(op->label, shown);
	g_free(shown);
	g_free(title);

	GString *d = g_string_new(NULL);
	if (total <= 0) {
		g_string_append(d, "Working out how much there is…");
	} else if (bytes) {
		/* The file in hand only when it isn't the title's one */
		if (current && (n > 1 || items > 1 || op->kind == OP_EXTRACT)) {
			g_string_append_printf(d, "%s · ", current);
		}
		char *have = format_size(MIN(done, total));
		char *all = format_size(total);
		g_string_append_printf(d, "%s of %s", have, all);
		g_free(have);
		g_free(all);
		if (items > 1) {
			g_string_append_printf(d, " · %" G_GINT64_FORMAT " of %"
				G_GINT64_FORMAT " files", MIN(items_done + 1, items), items);
		}
		if (op->speed > 1 && done < total) {
			char *speed = format_size((guint64)op->speed);
			char *left = time_left((total - done) / op->speed);
			g_string_append_printf(d, " · %s a second · %s", speed, left);
			g_free(speed);
			g_free(left);
		}
	} else {
		if (current && n > 1) {
			g_string_append_printf(d, "%s · ", current);
		}
		g_string_append_printf(d, "%" G_GINT64_FORMAT " of %" G_GINT64_FORMAT,
			MIN(done + 1, total), total);
	}
	shown = c8_stealth_text(d->str);
	c8ui_label_set_text(op->detail, shown);
	g_free(shown);
	g_string_free(d, TRUE);
	g_free(current);
	c8ui_progress_set(op->bar, total > 0 ? (double)done / total : -1);
	return G_SOURCE_CONTINUE;
}

/* Done */

static void op_free(struct op *op) {
	g_list_free_full(op->files, g_object_unref);
	g_clear_object(&op->into);
	g_object_unref(op->cancel);
	g_mutex_clear(&op->lock);
	g_cond_clear(&op->answered);
	g_ptr_array_unref(op->failed);
	g_ptr_array_unref(op->untrashable);
	g_free(op->current);
	g_free(op->clash_name);
	g_free(op->secret_name);
	g_free(op->secret);
	g_clear_object(&op->made);
	g_free(op->verb);
	g_free(op->what);
	g_free(op->where);
	free(op);
}

static void erase_untrashable(int choice, void *data) {
	struct op *op = data;
	if (choice == 0) {
		GList *files = NULL;
		for (guint i = 0; i < op->untrashable->len; i++) {
			files = g_list_append(files,
				g_object_ref(op->untrashable->pdata[i]));
		}
		struct op *again = calloc(1, sizeof(*again));
		again->kind = OP_DELETE;
		again->files = files;
		again->win = op->win;
		run(again);
	}
	op_free(op); // kept for this answer: see finished
}

static void finished(GObject *source, GAsyncResult *result, gpointer data) {
	struct op *op = data;
	g_source_remove(op->tick);
	if (op->row) {
		struct c8ui_widget *box = op->row->parent;
		c8ui_widget_destroy(op->row);
		box->hidden = box->child_count == 0;
		c8ui_widget_queue_layout(box->parent ? box->parent : box);
	}
	ops = g_list_remove(ops, op);
	if (op->made_cb) {
		op->made_cb(op->made, op->made_data);
	}
	bool keep = false;
	if (op->win && op->failed->len > 0) {
		GString *s = g_string_new("");
		for (guint i = 0; i < op->failed->len && i < 5; i++) {
			char *shown = c8_stealth_text(op->failed->pdata[i]);
			g_string_append_printf(s, "%s%s", i ? "\n" : "", shown);
			g_free(shown);
		}
		if (op->failed->len > 5) {
			g_string_append_printf(s, "\nand %u more", op->failed->len - 5);
		}
		const char *ok[] = { "OK" };
		c8ui_dialog_show(c8ui_window_root(op->win),
			op->failed->len == 1 ? "Something couldn't be done" :
				"Some things couldn't be done", s->str, ok, 1, NULL, NULL);
		g_string_free(s, TRUE);
	}
	if (op->win && op->untrashable->len > 0) {
		/* USB sticks and network folders often have no trash */
		char *message = g_strdup_printf("%u %s can't go in the Trash where "
			"%s. Delete %s for good? You can't undo this.",
			op->untrashable->len, op->untrashable->len == 1 ? "item" : "items",
			op->untrashable->len == 1 ? "it is" : "they are",
			op->untrashable->len == 1 ? "it" : "them");
		const char *buttons[] = { "Delete", "Cancel" };
		c8ui_dialog_show(c8ui_window_root(op->win), "Delete for good?",
			message, buttons, 2, erase_untrashable, op);
		g_free(message);
		keep = true;
	}
	c8ui_app_release(files_app());
	if (!keep) {
		op_free(op);
	}
}

static void run(struct op *op) {
	op->cancel = g_cancellable_new();
	op->failed = g_ptr_array_new_with_free_func(g_free);
	op->untrashable = g_ptr_array_new_with_free_func(g_object_unref);
	g_mutex_init(&op->lock);
	g_cond_init(&op->answered);
	op->started = g_get_monotonic_time();
	char *where = op->into ? folder_title_real(op->into) : NULL;
	switch (op->kind) {
	case OP_COPY:
		op->verb = g_strdup("Copying");
		break;
	case OP_MOVE:
		op->verb = g_strdup("Moving");
		break;
	case OP_TRASH:
		op->verb = g_strdup("Deleting");
		break;
	case OP_DELETE:
		op->verb = g_strdup("Deleting for good");
		break;
	case OP_RESTORE:
		op->verb = g_strdup("Restoring");
		break;
	case OP_EXTRACT:
		op->verb = g_strdup("Extracting");
		break;
	case OP_COMPRESS:
		op->verb = g_strdup("Compressing");
		g_clear_pointer(&where, g_free);
		where = g_file_get_basename(op->into);
		break;
	}
	if (where) {
		op->where = g_strdup_printf(op->kind == OP_COMPRESS ? "into %s" :
			"to %s", where);
		g_free(where);
	}
	guint n = g_list_length(op->files);
	op->what = n == 1 ? g_file_get_basename(op->files->data) :
		g_strdup_printf("%u items", n);
	ops = g_list_prepend(ops, op);
	c8ui_app_hold(files_app());
	op->tick = g_timeout_add(TICK_MS, tick, op);
	GTask *task = g_task_new(NULL, NULL, finished, op);
	g_task_set_task_data(task, op, NULL);
	g_task_run_in_thread(task, work);
	g_object_unref(task);
}

static gpointer ref(gconstpointer object, gpointer unused) {
	return g_object_ref((gpointer)object);
}

static GList *copy_list(GList *files) {
	return g_list_copy_deep(files, ref, NULL);
}

void ops_copy(struct c8ui_window *win, GList *files, GFile *into, bool move) {
	struct op *op = calloc(1, sizeof(*op));
	op->kind = move ? OP_MOVE : OP_COPY;
	op->files = copy_list(files);
	op->into = g_object_ref(into);
	op->win = win;
	run(op);
}

void ops_trash(struct c8ui_window *win, GList *files) {
	struct op *op = calloc(1, sizeof(*op));
	op->kind = OP_TRASH;
	op->files = copy_list(files);
	op->win = win;
	run(op);
}

void ops_extract(struct c8ui_window *win, GList *archives, GFile *into,
		made_fn fn, void *data) {
	struct op *op = calloc(1, sizeof(*op));
	op->kind = OP_EXTRACT;
	op->files = copy_list(archives);
	op->into = g_object_ref(into);
	op->win = win;
	op->made_cb = fn;
	op->made_data = data;
	run(op);
}

void ops_compress(struct c8ui_window *win, GList *files, GFile *dest,
		enum arc_format format, made_fn fn, void *data) {
	struct op *op = calloc(1, sizeof(*op));
	op->kind = OP_COMPRESS;
	op->files = copy_list(files);
	op->into = g_object_ref(dest);
	op->format = format;
	op->win = win;
	op->made_cb = fn;
	op->made_data = data;
	run(op);
}

struct confirm {
	struct c8ui_window *win;
	GList *files;
};

static void delete_confirmed(int choice, void *data) {
	struct confirm *c = data;
	if (choice == 0) {
		struct op *op = calloc(1, sizeof(*op));
		op->kind = OP_DELETE;
		op->files = c->files;
		op->win = c->win;
		run(op);
	} else {
		g_list_free_full(c->files, g_object_unref);
	}
	free(c);
}

static void confirm_delete(struct c8ui_window *win, GList *files,
		const char *title) {
	int n = g_list_length(files);
	char *message;
	if (n == 1) {
		char *name = display_name(files->data);
		message = g_strdup_printf("Delete %s for good? You can't undo this.",
			c8_stealth_show(name));
		g_free(name);
	} else {
		message = g_strdup_printf("Delete these %d items for good? You "
			"can't undo this.", n);
	}
	struct confirm *c = calloc(1, sizeof(*c));
	c->win = win;
	c->files = files;
	const char *buttons[] = { "Delete", "Cancel" };
	c8ui_dialog_show(c8ui_window_root(win), title, message, buttons, 2,
		delete_confirmed, c);
	g_free(message);
}

void ops_delete(struct c8ui_window *win, GList *files) {
	confirm_delete(win, copy_list(files), "Delete for good?");
}

void ops_empty_trash(struct c8ui_window *win) {
	GFile *trash = g_file_new_for_uri("trash:///");
	GFileEnumerator *en = g_file_enumerate_children(trash,
		G_FILE_ATTRIBUTE_STANDARD_NAME, G_FILE_QUERY_INFO_NONE, NULL, NULL);
	GList *files = NULL;
	GFileInfo *info;
	while (en && (info = g_file_enumerator_next_file(en, NULL, NULL))) {
		files = g_list_prepend(files, g_file_enumerator_get_child(en, info));
		g_object_unref(info);
	}
	g_clear_object(&en);
	g_object_unref(trash);
	if (files) {
		confirm_delete(win, files, "Empty the Trash?");
	}
}

void ops_restore(struct c8ui_window *win, GList *files) {
	struct op *op = calloc(1, sizeof(*op));
	op->kind = OP_RESTORE;
	op->files = copy_list(files);
	op->win = win;
	run(op);
}

/* Quick ones, on the main loop */

struct made {
	struct c8ui_window *win;
	GFile *file;
	made_fn fn;
	void *data;
};

static void error_dialog(struct c8ui_window *win, const char *title,
		const char *message) {
	if (win) {
		const char *ok[] = { "OK" };
		char *shown = c8_stealth_text(message); // errors name paths
		c8ui_dialog_show(c8ui_window_root(win), title, shown, ok, 1, NULL,
			NULL);
		g_free(shown);
	}
}

static void made_dir(GObject *source, GAsyncResult *result, gpointer data) {
	struct made *m = data;
	GError *error = NULL;
	bool ok = g_file_make_directory_finish(G_FILE(source), result, &error);
	if (!ok) {
		error_dialog(m->win, "Couldn't make the folder", error->message);
		g_error_free(error);
	}
	if (m->fn) {
		m->fn(ok ? m->file : NULL, m->data);
	}
	quick = g_list_remove(quick, m);
	g_object_unref(m->file);
	free(m);
}

void ops_new_folder(struct c8ui_window *win, GFile *in, made_fn fn,
		void *data) {
	struct made *m = calloc(1, sizeof(*m));
	m->win = win;
	m->file = files_unique_child(in, "New folder");
	m->fn = fn;
	m->data = data;
	quick = g_list_prepend(quick, m);
	g_file_make_directory_async(m->file, G_PRIORITY_DEFAULT, NULL, made_dir, m);
}

static void renamed(GObject *source, GAsyncResult *result, gpointer data) {
	struct made *m = data;
	GError *error = NULL;
	GFile *file = g_file_set_display_name_finish(G_FILE(source), result,
		&error);
	if (file == NULL) {
		error_dialog(m->win, "Couldn't rename it", error->message);
		g_error_free(error);
	} else {
		g_object_unref(file);
	}
	quick = g_list_remove(quick, m);
	free(m);
}

void ops_rename(struct c8ui_window *win, GFile *file, const char *name) {
	struct made *m = calloc(1, sizeof(*m));
	m->win = win;
	quick = g_list_prepend(quick, m);
	g_file_set_display_name_async(file, name, G_PRIORITY_DEFAULT, NULL,
		renamed, m);
}

void ops_window_gone(struct c8ui_window *win) {
	for (GList *l = ops; l; l = l->next) {
		struct op *op = l->data;
		if (op->win == win) {
			op->win = NULL;
			/* Its dialog went with it and won't answer */
			op->secret_dialog = op->secret_entry = NULL;
			give_answer(op, CLASH_SKIP);
		}
	}
	for (GList *l = quick; l; l = l->next) {
		struct made *m = l->data;
		if (m->win == win) {
			m->win = NULL;
		}
	}
}

/* The clipboard, shared with other apps and file managers: GNOME's
 * x-special/gnome-copied-files ("copy" or "cut", then a URI a line),
 * text/uri-list with KDE's cut mark, and the paths as text */

#define GNOME_FILES "x-special/gnome-copied-files"
#define URI_LIST "text/uri-list"
#define KDE_CUT "application/x-kde-cutselection"

void clipboard_set(struct c8ui_window *win, char **uris, bool cut) {
	c8ui_window_set_clipboard_files(win, uris, cut, NULL, 0);
}

bool clipboard_has(void) {
	struct c8ui_app *app = files_app();
	return c8ui_app_clipboard_offers(app, GNOME_FILES) ||
		c8ui_app_clipboard_offers(app, URI_LIST);
}

struct pasted {
	GList *files;
	bool cut;
};

GList *files_from_uris(const char *text, bool gnome, bool *cut) {
	GList *files = NULL;
	char **lines = g_strsplit(text, "\n", -1);
	int i = 0;
	if (gnome && lines[0]) {
		if (cut) {
			*cut = strcmp(g_strstrip(lines[0]), "cut") == 0;
		}
		i = 1;
	}
	for (; lines[i]; i++) {
		char *uri = g_strstrip(lines[i]);
		/* uri-list allows comments */
		if (uri[0] && uri[0] != '#') {
			files = g_list_append(files, g_file_new_for_uri(uri));
		}
	}
	g_strfreev(lines);
	return files;
}

static void got_files(const char *mime, const char *data, size_t len,
		void *userdata) {
	struct pasted *p = userdata;
	if (mime) {
		p->files = files_from_uris(data, strcmp(mime, GNOME_FILES) == 0,
			&p->cut);
	}
}

static void got_cut(const char *mime, const char *data, size_t len,
		void *userdata) {
	bool *cut = userdata;
	*cut = mime && len > 0 && data[0] == '1';
}

void clipboard_paste(struct c8ui_window *win, GFile *into) {
	struct pasted p = { 0 };
	static const char *const types[] = { GNOME_FILES, URI_LIST };
	c8ui_window_paste(win, types, G_N_ELEMENTS(types), got_files, &p);
	if (p.files == NULL) {
		return;
	}
	if (!c8ui_app_clipboard_offers(files_app(), GNOME_FILES)) {
		static const char *const kde[] = { KDE_CUT };
		c8ui_window_paste(win, kde, 1, got_cut, &p.cut);
	}
	ops_copy(win, p.files, into, p.cut);
	g_list_free_full(p.files, g_object_unref);
	if (p.cut && c8ui_app_clipboard_owned(files_app())) {
		/* Moved: pasting again would find nothing */
		c8ui_window_set_clipboard(win, NULL, 0);
	}
}
