/*
 * Decoding through glycin: every decoder runs in a bubblewrap sandbox,
 * which matters for a viewer that opens whatever someone downloaded.
 * glycin turns the picture the way its EXIF says and hands frames over
 * in cairo's own pixel layout, so a frame becomes a surface without a
 * copy. Animations ask for the next frame when the one shown is due.
 */
#include <glycin.h>
#include "photos.h"

#if G_BYTE_ORDER == G_LITTLE_ENDIAN
#define CAIRO_LAYOUT GLY_MEMORY_SELECTION_B8G8R8A8_PREMULTIPLIED
#else
#define CAIRO_LAYOUT GLY_MEMORY_SELECTION_A8R8G8B8_PREMULTIPLIED
#endif

/* SVGs are drawn at a size of our choosing: big enough to zoom into */
#define SVG_SIZE 4096

static const cairo_user_data_key_t bytes_key;

static struct ph_picture *ref(struct ph_picture *pic) {
	pic->refs++;
	return pic;
}

static void unref(struct ph_picture *pic) {
	if (--pic->refs > 0) {
		return;
	}
	if (pic->surface) {
		cairo_surface_destroy(pic->surface);
	}
	if (pic->image) {
		g_object_unref(pic->image);
	}
	g_object_unref(pic->cancel);
	g_free(pic->uri);
	g_free(pic->error);
	g_free(pic);
}

static void tell(struct ph_picture *pic) {
	if (!pic->released && pic->fn) {
		pic->fn(pic, pic->data);
	}
}

static void fail(struct ph_picture *pic, GError *err) {
	pic->state = PH_FAILED;
	if (g_error_matches(err, GLY_LOADER_ERROR,
			GLY_LOADER_ERROR_UNKNOWN_IMAGE_FORMAT)) {
		pic->error = g_strdup("Photos can't show this kind of file.");
	} else if (g_error_matches(err, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) {
		pic->error = g_strdup("This picture isn't there any more.");
	} else {
		pic->error = g_strdup("This picture can't be shown. It may be "
			"damaged, or not a picture at all.");
		g_message("%s: %s", pic->uri, err->message);
	}
	tell(pic);
}

static cairo_surface_t *surface_of(GlyFrame *frame) {
	GBytes *bytes = gly_frame_get_buf_bytes(frame);
	int w = gly_frame_get_width(frame), h = gly_frame_get_height(frame);
	int stride = gly_frame_get_stride(frame);
	gsize len;
	const guint8 *data = g_bytes_get_data(bytes, &len);
	if (w <= 0 || h <= 0 || stride < w * 4 || stride % 4 ||
			len < (gsize)stride * (h - 1) + w * 4) {
		return NULL;
	}
	cairo_surface_t *s = cairo_image_surface_create_for_data((guint8 *)data,
		CAIRO_FORMAT_ARGB32, w, h, stride);
	if (cairo_surface_status(s) != CAIRO_STATUS_SUCCESS) {
		cairo_surface_destroy(s);
		return NULL;
	}
	/* The surface keeps the bytes; nothing draws into it */
	cairo_surface_set_user_data(s, &bytes_key, g_bytes_ref(bytes),
		(cairo_destroy_func_t)g_bytes_unref);
	return s;
}

static void fetch(struct ph_picture *pic);

static gboolean frame_due(gpointer data) {
	struct ph_picture *pic = data;
	pic->timer = 0;
	fetch(pic);
	return G_SOURCE_REMOVE;
}

static void schedule(struct ph_picture *pic) {
	if (pic->animated && pic->playing && !pic->fetching && !pic->timer &&
			!pic->released) {
		/* Browsers show frames that say 0 or 10 ms at 100 ms */
		int64_t ms = pic->delay / 1000;
		pic->timer = g_timeout_add(ms > 10 ? ms : 100, frame_due, pic);
	}
}

static void got_frame(GObject *src, GAsyncResult *res, gpointer data) {
	struct ph_picture *pic = data;
	GError *err = NULL;
	GlyFrame *frame = gly_image_next_frame_finish(GLY_IMAGE(src), res, &err);
	pic->fetching = false;
	if (pic->released) {
		g_clear_error(&err);
		if (frame) {
			g_object_unref(frame);
		}
		unref(pic);
		return;
	}
	if (frame == NULL) {
		if (pic->state == PH_LOADING) {
			fail(pic, err);
		}
		/* A later frame failing leaves the one shown */
		g_error_free(err);
		unref(pic);
		return;
	}
	cairo_surface_t *s = surface_of(frame);
	pic->delay = gly_frame_get_delay(frame);
	g_object_unref(frame);
	if (s == NULL) {
		if (pic->state == PH_LOADING) {
			pic->state = PH_FAILED;
			pic->error = g_strdup("This picture can't be shown.");
			tell(pic);
		}
		unref(pic);
		return;
	}
	if (pic->surface) {
		cairo_surface_destroy(pic->surface);
	}
	pic->surface = s;
	pic->width = cairo_image_surface_get_width(s);
	pic->height = cairo_image_surface_get_height(s);
	pic->animated = pic->delay > 0;
	pic->state = PH_READY;
	tell(pic);
	schedule(pic);
	unref(pic);
}

static void fetch(struct ph_picture *pic) {
	if (pic->fetching || pic->released || pic->image == NULL) {
		return;
	}
	pic->fetching = true;
	GlyImage *image = pic->image;
	const char *mime = gly_image_get_mime_type(image);
	if (pic->state == PH_LOADING && mime &&
			g_str_has_prefix(mime, "image/svg")) {
		GlyFrameRequest *req = gly_frame_request_new();
		gly_frame_request_set_scale(req, SVG_SIZE, SVG_SIZE);
		gly_image_get_specific_frame_async(image, req, pic->cancel,
			got_frame, ref(pic));
		g_object_unref(req);
		return;
	}
	gly_image_next_frame_async(image, pic->cancel, got_frame, ref(pic));
}

static void loaded(GObject *src, GAsyncResult *res, gpointer data) {
	struct ph_picture *pic = data;
	GError *err = NULL;
	GlyImage *image = gly_loader_load_finish(GLY_LOADER(src), res, &err);
	g_object_unref(src);
	if (pic->released) {
		g_clear_error(&err);
		if (image) {
			g_object_unref(image);
		}
		unref(pic);
		return;
	}
	if (image == NULL) {
		fail(pic, err);
		g_error_free(err);
		unref(pic);
		return;
	}
	pic->image = image;
	fetch(pic);
	unref(pic);
}

struct ph_picture *ph_picture_load(const char *uri,
		void (*fn)(struct ph_picture *pic, void *data), void *data) {
	struct ph_picture *pic = g_new0(struct ph_picture, 1);
	pic->refs = 1;
	pic->owners = 1;
	pic->uri = g_strdup(uri);
	pic->fn = fn;
	pic->data = data;
	pic->cancel = g_cancellable_new();
	GFile *file = g_file_new_for_uri(uri);
	GlyLoader *loader = gly_loader_new(file);
	g_object_unref(file);
	gly_loader_set_accepted_memory_formats(loader, CAIRO_LAYOUT);
	gly_loader_load_async(loader, pic->cancel, loaded, ref(pic));
	return pic;
}

struct ph_picture *ph_picture_ref(struct ph_picture *pic) {
	pic->owners++;
	return pic;
}

void ph_picture_release(struct ph_picture *pic) {
	if (pic == NULL || --pic->owners > 0) {
		return;
	}
	pic->released = true;
	pic->fn = NULL;
	if (pic->timer) {
		g_source_remove(pic->timer);
		pic->timer = 0;
	}
	g_cancellable_cancel(pic->cancel);
	unref(pic);
}

void ph_picture_set_playing(struct ph_picture *pic, bool playing) {
	if (pic == NULL || pic->playing == playing) {
		return;
	}
	pic->playing = playing;
	if (!playing && pic->timer) {
		g_source_remove(pic->timer);
		pic->timer = 0;
	}
	schedule(pic);
}
