#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <png.h>
#include <zlib.h>

#include "pdfw.h"
#include "ttf.h"
#include "util.h"

#define MAX_FONTS	8
#define MAX_IMAGES	64
#define MAX_PIXELS	(4u * 1024 * 1024)	/* Per PNG, not an aggregate RSS bound. */

enum { OBJ_CATALOG = 1, OBJ_PAGES, OBJ_RESOURCES, OBJ_HELVETICA, OBJ_FIRST_FREE };

struct pfont {
	char *path;
	struct ttf ttf;
	int obj;		/* Type0 font object, reserved at load time */
	uint32_t *used;		/* gid -> code point (0 = unused) */
};

struct pimage {
	char *path;
	int obj, w, h;
};

struct pdfw {
	FILE *f;
	long *offs;
	int nobj, cap;
	struct pfont fonts[MAX_FONTS];
	int nfonts;
	struct pimage images[MAX_IMAGES];
	int nimages;
	int *pages;
	int npages;
	char *content;
	size_t clen, ccap;
	double pw, ph;
	int in_page, err;
};

/* Standard Helvetica advance widths for 0x20..0x7E (AFM, 1/1000 em). */
static const short helv_w[95] = {
	278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333,
	278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278,
	584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278,
	500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944,
	667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556,
	278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500,
	278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584
};

static int
new_obj(pdfw *p)
{
	if (p->nobj + 1 >= p->cap) {
		int cap = p->cap ? p->cap * 2 : 64;
		long *n = realloc(p->offs, (size_t)cap * sizeof(long));

		if (n == NULL) {
			p->err = 1;
			return 0;
		}
		memset(n + p->cap, 0, (size_t)(cap - p->cap) * sizeof(long));
		p->offs = n;
		p->cap = cap;
	}
	return ++p->nobj;
}

static void
begin_obj(pdfw *p, int obj)
{
	if (obj <= 0 || obj >= p->cap) {
		p->err = 1;
		return;
	}
	p->offs[obj] = ftell(p->f);
	fprintf(p->f, "%d 0 obj\n", obj);
}

static void
stream_obj(pdfw *p, int obj, const char *dict, const void *data, size_t len)
{
	begin_obj(p, obj);
	fprintf(p->f, "<< %s /Length %zu >>\nstream\n", dict, len);
	if (len && fwrite(data, 1, len, p->f) != len)
		p->err = 1;
	fputs("\nendstream\nendobj\n", p->f);
}

/* An indirect length lets compression write straight to the PDF, not a second
 * image/font-sized buffer alongside the decoded pixels or loaded font bytes. */
static int
deflate_obj(pdfw *p, int obj, const char *dict, const unsigned char *in,
    size_t len)
{
	z_stream z;
	unsigned char buf[16384];
	uLong total;
	int length, rc;
	size_t n;

	if (p->err || len > UINT_MAX)
		goto fail;
	if ((length = new_obj(p)) == 0)
		return -1;
	memset(&z, 0, sizeof(z));
	if (deflateInit(&z, 6) != Z_OK)
		goto fail;
	begin_obj(p, obj);
	fprintf(p->f, "<< %s /Filter /FlateDecode /Length %d 0 R >>\nstream\n",
	    dict, length);
	z.next_in = (Bytef *)in;
	z.avail_in = (uInt)len;
	do {
		z.next_out = buf;
		z.avail_out = sizeof(buf);
		rc = deflate(&z, Z_FINISH);
		n = sizeof(buf) - z.avail_out;
		if ((rc != Z_OK && rc != Z_STREAM_END) ||
		    fwrite(buf, 1, n, p->f) != n) {
			deflateEnd(&z);
			goto fail;
		}
	} while (rc != Z_STREAM_END);
	total = z.total_out;
	if (deflateEnd(&z) != Z_OK)
		goto fail;
	fputs("\nendstream\nendobj\n", p->f);
	begin_obj(p, length);
	fprintf(p->f, "%lu\nendobj\n", total);
	if (ferror(p->f))
		goto fail;
	return 0;
fail:
	p->err = 1;
	return -1;
}

static void
cprintf(pdfw *p, const char *fmt, ...)
{
	va_list ap;
	char *content;
	size_t cap;
	int n;

	if (p->err)
		return;
	for (;;) {
		va_start(ap, fmt);
		n = vsnprintf(p->content ? p->content + p->clen : NULL,
		    p->ccap - p->clen, fmt, ap);
		va_end(ap);
		if (n >= 0 && (size_t)n < p->ccap - p->clen) {
			p->clen += (size_t)n;
			return;
		}
		if (n < 0 || p->ccap > SIZE_MAX / 2) {
			p->err = 1;
			return;
		}
		cap = p->ccap ? p->ccap * 2 : 4096;
		if ((content = realloc(p->content, cap)) == NULL) {
			p->err = 1;
			return;
		}
		p->content = content;
		p->ccap = cap;
	}
}

static void
end_page(pdfw *p)
{
	int cobj, pobj, *np;

	if (!p->in_page)
		return;
	p->in_page = 0;
	cobj = new_obj(p);
	stream_obj(p, cobj, "", p->content, p->clen);
	pobj = new_obj(p);
	begin_obj(p, pobj);
	fprintf(p->f, "<< /Type /Page /Parent %d 0 R /MediaBox [0 0 %.2f %.2f] "
	    "/Resources %d 0 R /Contents %d 0 R >>\nendobj\n",
	    OBJ_PAGES, p->pw, p->ph, OBJ_RESOURCES, cobj);
	if ((np = realloc(p->pages, (size_t)(p->npages + 1) * sizeof(int))) == NULL) {
		p->err = 1;
		return;
	}
	p->pages = np;
	p->pages[p->npages++] = pobj;
}

pdfw *
pdfw_open(const char *path)
{
	pdfw *p;

	if ((p = calloc(1, sizeof(*p))) == NULL)
		return NULL;
	if ((p->f = fopen(path, "wb")) == NULL) {
		free(p);
		return NULL;
	}
	fputs("%PDF-1.5\n%\xE2\xE3\xCF\xD3\n", p->f);
	while (p->nobj < OBJ_HELVETICA)
		if (new_obj(p) == 0) {
			fclose(p->f);
			free(p->offs);
			free(p);
			return NULL;
		}
	begin_obj(p, OBJ_HELVETICA);
	fputs("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica "
	    "/Encoding /WinAnsiEncoding >>\nendobj\n", p->f);
	return p;
}

int
pdfw_page(pdfw *p, double w, double h)
{
	end_page(p);
	p->pw = w;
	p->ph = h;
	p->clen = 0;
	p->in_page = 1;
	return 0;
}

int
pdfw_font(pdfw *p, const char *path)
{
	struct pfont *ft;
	int i;

	if (path == NULL || *path == '\0')
		return PDFW_HELVETICA;
	for (i = 0; i < p->nfonts; i++)
		if (strcmp(p->fonts[i].path, path) == 0)
			return i + 1;
	if (p->nfonts == MAX_FONTS)
		return PDFW_HELVETICA;
	ft = &p->fonts[p->nfonts];
	if (ttf_load(&ft->ttf, path) == -1) {
		fprintf(stderr, "signet: unusable font %s, using Helvetica\n", path);
		return PDFW_HELVETICA;
	}
	ft->used = calloc((size_t)ft->ttf.nglyphs + 1, sizeof(uint32_t));
	ft->path = strdup(path);
	if (ft->used == NULL || ft->path == NULL) {
		ttf_free(&ft->ttf);
		free(ft->used);
		free(ft->path);
		memset(ft, 0, sizeof(*ft));
		p->err = 1;
		return PDFW_HELVETICA;
	}
	ft->obj = new_obj(p);
	return ++p->nfonts;
}

void
pdfw_font_metrics(pdfw *p, int font, double *asc, double *desc)
{
	if (font > 0 && font <= p->nfonts) {
		const struct ttf *t = &p->fonts[font - 1].ttf;

		*asc = (double)t->ascent / t->units;
		*desc = (double)t->descent / t->units;
	} else {
		*asc = 0.718;
		*desc = -0.207;
	}
}

double
pdfw_text_width(pdfw *p, int font, const char *s, double size)
{
	double w = 0;
	uint32_t cp;

	while (*s) {
		cp = utf8_next(&s);
		if (font > 0 && font <= p->nfonts) {
			const struct ttf *t = &p->fonts[font - 1].ttf;

			w += (double)ttf_advance(t, ttf_gid(t, cp)) / t->units;
		} else
			w += (cp >= 0x20 && cp <= 0x7E ? helv_w[cp - 0x20] : 556) / 1000.0;
	}
	return w * size;
}

void
pdfw_text(pdfw *p, int font, double size, double x, double y, const char *s)
{
	uint32_t cp;

	if (!p->in_page)
		return;
	if (font > 0 && font <= p->nfonts) {
		struct pfont *ft = &p->fonts[font - 1];

		cprintf(p, "BT 0 g /F%d %.3f Tf %.3f %.3f Td <", font, size, x, y);
		while (*s) {
			uint16_t gid;

			cp = utf8_next(&s);
			gid = ttf_gid(&ft->ttf, cp);
			if (ft->used[gid] == 0)
				ft->used[gid] = cp ? cp : 0xFFFD;
			cprintf(p, "%04X", gid);
		}
		cprintf(p, "> Tj ET\n");
		return;
	}
	cprintf(p, "BT 0 g /F0 %.3f Tf %.3f %.3f Td (", size, x, y);
	while (*s) {
		cp = utf8_next(&s);
		if (cp == '(' || cp == ')' || cp == '\\')
			cprintf(p, "\\%c", (int)cp);
		else
			cprintf(p, "%c", cp >= 0x20 && cp <= 0x7E ? (int)cp : '?');
	}
	cprintf(p, ") Tj ET\n");
}

/* --- images ---------------------------------------------------------------- */
/* Interpolate colour and alpha streams, matching browser image upscaling. */

static int
jpeg_info(const unsigned char *d, size_t len, int *w, int *h, int *ncomp)
{
	size_t i = 2;

	if (len < 4 || d[0] != 0xFF || d[1] != 0xD8)
		return -1;
	while (i + 9 < len) {
		int m, seglen;

		if (d[i] != 0xFF)
			return -1;
		m = d[i + 1];
		if (m == 0xFF) {
			i++;
			continue;
		}
		seglen = d[i + 2] << 8 | d[i + 3];
		if (m >= 0xC0 && m <= 0xCF && m != 0xC4 && m != 0xC8 && m != 0xCC) {
			*h = d[i + 5] << 8 | d[i + 6];
			*w = d[i + 7] << 8 | d[i + 8];
			*ncomp = d[i + 9];
			return 0;
		}
		i += 2 + (size_t)seglen;
	}
	return -1;
}

static int
embed_jpeg(pdfw *p, struct pimage *im, const char *path)
{
	FILE *f;
	long sz;
	unsigned char *d = NULL;
	int nc, rc = -1;
	char dict[256];

	if ((f = fopen(path, "rb")) == NULL)
		return -1;
	if (fseek(f, 0, SEEK_END) == 0 && (sz = ftell(f)) > 0 &&
	    sz < 16 * 1024 * 1024 && (d = malloc((size_t)sz)) != NULL) {
		rewind(f);
		if (fread(d, 1, (size_t)sz, f) == (size_t)sz &&
		    jpeg_info(d, (size_t)sz, &im->w, &im->h, &nc) == 0 &&
		    im->w > 0 && im->h > 0) {
			snprintf(dict, sizeof(dict), "/Type /XObject /Subtype /Image "
			    "/Width %d /Height %d /BitsPerComponent 8 /ColorSpace %s "
			    "/Interpolate true /Filter /DCTDecode%s", im->w, im->h,
			    nc == 1 ? "/DeviceGray" : nc == 4 ? "/DeviceCMYK" : "/DeviceRGB",
			    nc == 4 ? " /Decode [1 0 1 0 1 0 1 0]" : "");
			im->obj = new_obj(p);
			stream_obj(p, im->obj, dict, d, (size_t)sz);
			rc = 0;
		}
	}
	free(d);
	fclose(f);
	return rc;
}

static int
embed_png(pdfw *p, struct pimage *im, const char *path)
{
	png_image png;
	unsigned char *pixels = NULL, *rgb = NULL, *a = NULL;
	size_t npx, i;
	int channels, has_alpha = 0, smask = 0, rc = -1;
	char dict[256];

	memset(&png, 0, sizeof(png));
	png.version = PNG_IMAGE_VERSION;
	if (!png_image_begin_read_from_file(&png, path))
		return -1;
	npx = (size_t)png.width * png.height;
	if (npx == 0 || npx > MAX_PIXELS) {
		png_image_free(&png);
		return -1;
	}
	channels = (png.format & PNG_FORMAT_FLAG_ALPHA) ? 4 : 3;
	png.format = channels == 4 ? PNG_FORMAT_RGBA : PNG_FORMAT_RGB;
	if ((pixels = malloc(PNG_IMAGE_SIZE(png))) == NULL ||
	    !png_image_finish_read(&png, NULL, pixels, 0, NULL)) {
		png_image_free(&png);
		goto out;
	}
	im->w = (int)png.width;
	im->h = (int)png.height;
	rgb = pixels;
	if (channels == 4) {
		for (i = 0; i < npx; i++)
			if (pixels[i * 4 + 3] != 0xFF) {
				has_alpha = 1;
				break;
			}
		/* Split in place; opaque images need no alpha-plane allocation. */
		if (has_alpha && (a = malloc(npx)) == NULL)
			goto out;
		for (i = 0; i < npx; i++) {
			if (has_alpha)
				a[i] = pixels[i * 4 + 3];
			rgb[i * 3] = pixels[i * 4];
			rgb[i * 3 + 1] = pixels[i * 4 + 1];
			rgb[i * 3 + 2] = pixels[i * 4 + 2];
		}
	}
	if (has_alpha) {
		snprintf(dict, sizeof(dict), "/Type /XObject /Subtype /Image "
		    "/Width %d /Height %d /BitsPerComponent 8 "
		    "/ColorSpace /DeviceGray /Interpolate true", im->w, im->h);
		smask = new_obj(p);
		if (deflate_obj(p, smask, dict, a, npx) == -1)
			goto out;
	}
	free(a);
	a = NULL;
	i = (size_t)snprintf(dict, sizeof(dict), "/Type /XObject /Subtype /Image "
	    "/Width %d /Height %d /BitsPerComponent 8 "
	    "/ColorSpace /DeviceRGB /Interpolate true",
	    im->w, im->h);
	if (smask)
		snprintf(dict + i, sizeof(dict) - i, " /SMask %d 0 R", smask);
	im->obj = new_obj(p);
	rc = deflate_obj(p, im->obj, dict, rgb, npx * 3);
out:
	free(a);
	free(pixels);
	return rc;
}

static struct pimage *
get_image(pdfw *p, const char *path)
{
	struct pimage *im;
	FILE *f;
	unsigned char magic[2];
	int i, rc;

	for (i = 0; i < p->nimages; i++)
		if (strcmp(p->images[i].path, path) == 0)
			return &p->images[i];
	if (p->nimages == MAX_IMAGES)
		return NULL;
	im = &p->images[p->nimages];
	memset(im, 0, sizeof(*im));
	/* Frozen assets have opaque names; format belongs to the bytes, not the path. */
	if ((f = fopen(path, "rb")) == NULL)
		return NULL;
	rc = fread(magic, 1, sizeof(magic), f) == sizeof(magic);
	fclose(f);
	if (!rc)
		return NULL;
	if (magic[0] == 0xFF && magic[1] == 0xD8)
		rc = embed_jpeg(p, im, path);
	else
		rc = embed_png(p, im, path);
	if (rc == -1 || (im->path = strdup(path)) == NULL)
		return NULL;
	p->nimages++;
	return im;
}

int
pdfw_image_size(pdfw *p, const char *path, int *w, int *h)
{
	struct pimage *im = get_image(p, path);

	if (im == NULL)
		return -1;
	*w = im->w;
	*h = im->h;
	return 0;
}

int
pdfw_image(pdfw *p, const char *path, double x, double y, double w, double h)
{
	struct pimage *im = get_image(p, path);

	if (im == NULL || !p->in_page)
		return -1;
	cprintf(p, "q %.3f 0 0 %.3f %.3f %.3f cm /Im%d Do Q\n", w, h, x, y,
	    (int)(im - p->images) + 1);
	return 0;
}

void
pdfw_clip_circle(pdfw *p, double cx, double cy, double r)
{
	if (!p->in_page)
		return;
	/* Draw circle using four Bezier curves and set as clipping path */
	double k = 0.5522847498;  /* magic constant for circle approximation */
	cprintf(p, "q\n");
	cprintf(p, "%.3f %.3f m\n", cx + r, cy);
	cprintf(p, "%.3f %.3f %.3f %.3f %.3f %.3f c\n",
	    cx + r, cy + k * r, cx + k * r, cy + r, cx, cy + r);
	cprintf(p, "%.3f %.3f %.3f %.3f %.3f %.3f c\n",
	    cx - k * r, cy + r, cx - r, cy + k * r, cx - r, cy);
	cprintf(p, "%.3f %.3f %.3f %.3f %.3f %.3f c\n",
	    cx - r, cy - k * r, cx - k * r, cy - r, cx, cy - r);
	cprintf(p, "%.3f %.3f %.3f %.3f %.3f %.3f c\n",
	    cx + k * r, cy - r, cx + r, cy - k * r, cx + r, cy);
	cprintf(p, "h\nW n\n");  /* close path and set clipping */
}

void
pdfw_clip_end(pdfw *p)
{
	if (!p->in_page)
		return;
	cprintf(p, "Q\n");
}

/* --- trailer --------------------------------------------------------------- */

static void
write_font(pdfw *p, int idx)
{
	struct pfont *ft = &p->fonts[idx];
	const struct ttf *t = &ft->ttf;
	double k = 1000.0 / t->units;
	int file, desc, cid, tou, g, n;
	char dict[128], *cm;
	size_t cmlen = 0, cmcap;

	file = new_obj(p);
	snprintf(dict, sizeof(dict), "/Length1 %zu", t->len);
	if (deflate_obj(p, file, dict, t->data, t->len) == -1)
		return;

	desc = new_obj(p);
	begin_obj(p, desc);
	fprintf(p->f, "<< /Type /FontDescriptor /FontName /SignetF%d /Flags 4 "
	    "/FontBBox [%.0f %.0f %.0f %.0f] /ItalicAngle 0 /Ascent %.0f "
	    "/Descent %.0f /CapHeight %.0f /StemV 80 /FontFile2 %d 0 R >>\nendobj\n",
	    idx + 1, t->bbox[0] * k, t->bbox[1] * k, t->bbox[2] * k,
	    t->bbox[3] * k, t->ascent * k, t->descent * k, t->ascent * k, file);

	cid = new_obj(p);
	begin_obj(p, cid);
	fprintf(p->f, "<< /Type /Font /Subtype /CIDFontType2 /BaseFont /SignetF%d "
	    "/CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) "
	    "/Supplement 0 >> /FontDescriptor %d 0 R /CIDToGIDMap /Identity "
	    "/DW 1000 /W [", idx + 1, desc);
	for (g = 0; g < t->nglyphs; g++)
		if (ft->used[g])
			fprintf(p->f, " %d [%.0f]", g, ttf_advance(t, (uint16_t)g) * k);
	fputs(" ] >>\nendobj\n", p->f);

	/* ToUnicode keeps the stamped text searchable and copyable */
	cmcap = 512;
	for (g = 0; g < t->nglyphs; g++)
		if (ft->used[g])
			cmcap += 32;
	if ((cm = malloc(cmcap)) == NULL) {
		p->err = 1;
		return;
	}
	cmlen += (size_t)snprintf(cm + cmlen, cmcap - cmlen,
	    "/CIDInit /ProcSet findresource begin 12 dict begin begincmap "
	    "/CMapName /Adobe-Identity-UCS def /CMapType 2 def "
	    "1 begincodespacerange <0000> <FFFF> endcodespacerange\n");
	for (g = 0, n = 0; g < t->nglyphs; g++) {
		uint32_t cp = ft->used[g];

		if (cp == 0)
			continue;
		if (n % 100 == 0)
			cmlen += (size_t)snprintf(cm + cmlen, cmcap - cmlen,
			    "%s100 beginbfchar\n", n ? "endbfchar\n" : "");
		if (cp > 0xFFFF)
			cmlen += (size_t)snprintf(cm + cmlen, cmcap - cmlen,
			    "<%04X> <%04X%04X>\n", g,
			    0xD800 + ((cp - 0x10000) >> 10),
			    0xDC00 + ((cp - 0x10000) & 0x3FF));
		else
			cmlen += (size_t)snprintf(cm + cmlen, cmcap - cmlen,
			    "<%04X> <%04X>\n", g, cp);
		n++;
	}
	cmlen += (size_t)snprintf(cm + cmlen, cmcap - cmlen,
	    "%sendcmap CMapName currentdict /CMap defineresource pop end end",
	    n ? "endbfchar\n" : "");
	tou = new_obj(p);
	stream_obj(p, tou, "", cm, cmlen);
	free(cm);

	begin_obj(p, ft->obj);
	fprintf(p->f, "<< /Type /Font /Subtype /Type0 /BaseFont /SignetF%d "
	    "/Encoding /Identity-H /DescendantFonts [%d 0 R] /ToUnicode %d 0 R >>"
	    "\nendobj\n", idx + 1, cid, tou);
}

int
pdfw_close(pdfw *p)
{
	long xref;
	int i, err;

	if (p->err)
		goto out;
	end_page(p);
	if (p->err)
		goto out;
	for (i = 0; i < p->nfonts; i++) {
		write_font(p, i);
		if (p->err)
			goto out;
	}

	begin_obj(p, OBJ_RESOURCES);
	fprintf(p->f, "<< /Font << /F0 %d 0 R", OBJ_HELVETICA);
	for (i = 0; i < p->nfonts; i++)
		fprintf(p->f, " /F%d %d 0 R", i + 1, p->fonts[i].obj);
	fputs(" >> /XObject <<", p->f);
	for (i = 0; i < p->nimages; i++)
		fprintf(p->f, " /Im%d %d 0 R", i + 1, p->images[i].obj);
	fputs(" >> >>\nendobj\n", p->f);

	begin_obj(p, OBJ_PAGES);
	fputs("<< /Type /Pages /Kids [", p->f);
	for (i = 0; i < p->npages; i++)
		fprintf(p->f, " %d 0 R", p->pages[i]);
	fprintf(p->f, " ] /Count %d >>\nendobj\n", p->npages);

	begin_obj(p, OBJ_CATALOG);
	fprintf(p->f, "<< /Type /Catalog /Pages %d 0 R >>\nendobj\n", OBJ_PAGES);

	xref = ftell(p->f);
	fprintf(p->f, "xref\n0 %d\n0000000000 65535 f \n", p->nobj + 1);
	for (i = 1; i <= p->nobj; i++)
		fprintf(p->f, "%010ld 00000 n \n", p->offs[i]);
	fprintf(p->f, "trailer\n<< /Size %d /Root %d 0 R >>\nstartxref\n%ld\n%%%%EOF\n",
	    p->nobj + 1, OBJ_CATALOG, xref);

out:
	err = p->err || ferror(p->f);
	if (fclose(p->f) != 0)
		err = 1;
	for (i = 0; i < p->nfonts; i++) {
		ttf_free(&p->fonts[i].ttf);
		free(p->fonts[i].used);
		free(p->fonts[i].path);
	}
	for (i = 0; i < p->nimages; i++)
		free(p->images[i].path);
	free(p->pages);
	free(p->content);
	free(p->offs);
	free(p);
	return err ? -1 : 0;
}
