From 76c55b5bce0f181b0b15b16596c900397dfef544 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 6 Nov 2026 06:24:42 -0300 Subject: kinds #13, pdf.so: addons/pdf/pdf.c is the PDF kind against ABI 2.1 (its record the file's bytes, renders on jobs over two MuPDF lanes a cookie aborts, its strip laid out at `at` with crops and repainted rows for hover and selection, its text the body, search, links and PdfSections through look and text, P:F S places, PdfFit, PdfTint, PdfSections, its keys), pdf_bridge moves beside it, and the build makes it from position-independent MuPDF, FreeType and zlib exporting pardes_addon alone, installs /lib/pardes/addons/pdf.so, -Dmupdf now builds it or not and mupdf-check runs its addon-test script Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge --- addons/pdf/pdf.c | 1607 ++++++++++++++++++++++++++++++++++++++++++ addons/pdf/pdf.out | 129 ++++ addons/pdf/pdf.script | 15 + addons/pdf/pdf_bridge.c | 1802 +++++++++++++++++++++++++++++++++++++++++++++++ addons/pdf/pdf_bridge.h | 402 +++++++++++ build.zig | 116 +-- build/snap.zig | 13 +- mupdf.zig | 3 + src/pdf_bridge.c | 1789 ---------------------------------------------- src/pdf_bridge.h | 399 ----------- 10 files changed, 4023 insertions(+), 2252 deletions(-) create mode 100644 addons/pdf/pdf.c create mode 100644 addons/pdf/pdf.out create mode 100644 addons/pdf/pdf.script create mode 100644 addons/pdf/pdf_bridge.c create mode 100644 addons/pdf/pdf_bridge.h delete mode 100644 src/pdf_bridge.c delete mode 100644 src/pdf_bridge.h diff --git a/addons/pdf/pdf.c b/addons/pdf/pdf.c new file mode 100644 index 00000000..55820785 --- /dev/null +++ b/addons/pdf/pdf.c @@ -0,0 +1,1607 @@ +/* pdf.c: PDFs as a pardes addon, over MuPDF (pdf_bridge.c, which keeps + * MuPDF's throws in C). + * + * A pane is a strip of pages laid out at its window's pixels, each fitted + * to the window's width or height (PdfFit), a gap between two, tinted to + * the theme or not (PdfTint). Pages render off the loop on jobs, two at + * once: a pane's document has two lanes (a context and a document of + * their own each, MuPDF's threading rule), found by the jobs in a table + * of the open documents under its own lock, and a cookie stops a job + * nobody waits for. A raster is shown whole or cropped (`src`) at whole + * pixels (`at`); a highlight (the pointer's word or link, the search's + * hits, the selection) is MuPDF's highlight pass over the page's clean + * rows, repainted on the loop and said as rows (`from`, `dirty_*`). The + * body is the text of the page shown; `/` lists hits as `file.pdf:P:H`; + * PdfSections lists the outline; a click on a link follows it. The record + * in a dump is the file's bytes, with its fit, tint and place. */ +#include +#include +#include +#include +#include /* strtod; no malloc: memory is pardes's */ +#include + +#include "pardes_addon.h" +#include "pdf_bridge.h" + +#define GAP_PX 8u /* between two pages of the strip */ +#define SLOTS 16 /* pages a pane holds at once */ +#define LANES 2 /* jobs a document runs at once */ +#define MAX_HITS 512 /* rows a search lists */ +#define BAND_BYTES (4096u * 4096u * 4u) /* the most one raster holds */ +#define BAND_ROWS 8192u +#define CHUNK 512u /* a tall page's bands start on these */ +#define OVERLAP 32u /* rows rendered past a band's edges */ +#define HOVER_NS 32000000ull /* the pointer's rest before its word shows */ +#define MARKS 1024 /* highlights on a page */ +#define RECORD_VERSION 1u + +static const pa_api *api; + +/* ---- memory: pardes's heap, for MuPDF and the pixels ---- */ + +static void *heap(size_t n) { return api->heap(0, n); } +static void unheap(void *p) { + if (p) api->heap(p, 0); +} +static void *bridge_alloc(void *user, size_t n) { (void)user; return api->heap(0, n ? n : 1); } +static void *bridge_realloc(void *user, void *p, size_t n) { (void)user; return api->heap(p, n ? n : 1); } +static void bridge_free(void *user, void *p) { (void)user; unheap(p); } + +static int init(const pa_api *a) { + if (a->size < sizeof(pa_api)) return 1; /* a core before 2.1: no heap */ + api = a; + static const pardes_pdf_allocator hooks = {0, bridge_alloc, bridge_realloc, bridge_free}; + return pardes_pdf_set_allocator(&hooks) == PARDES_PDF_OK ? PA_OK : 1; +} + +/* ---- the tint: a page's ink and paper to the theme's ---- */ + +enum { TINT_DISABLED, TINT_FILTERED, TINT_FULL }; +static const char *const tint_names[] = {"disabled", "filtered", "full"}; + +/* Rec. 601 luminance (77/150/29). `full` maps black to the theme's text + * and white to its paper; `filtered` starts there and adds back 3/4 of each + * channel's distance from the luminance, so grey is the same in both and + * colour keeps its hue. Alpha is never touched. A page is runs of one + * value, so the last pixel's answer is kept. */ +static void tint(uint8_t *px, size_t len, int mode, uint32_t ink, uint32_t paper) { + if (mode == TINT_DISABLED) return; + uint8_t target[256][3]; + for (int l = 0; l < 256; l++) + for (int c = 0; c < 3; c++) { + uint32_t f = (ink >> (16 - 8 * c)) & 0xff, b = (paper >> (16 - 8 * c)) & 0xff; + target[l][c] = (uint8_t)((f * (uint32_t)(255 - l) + b * (uint32_t)l + 127) / 255); + } + uint32_t last_in = 0, last_out = 0; + int have = 0; + for (size_t i = 0; i + 4 <= len; i += 4) { + uint32_t word; + memcpy(&word, px + i, 4); + if (have && word == last_in) { + memcpy(px + i, &last_out, 4); + continue; + } + uint8_t *p = px + i; + int lum = (p[0] * 77 + p[1] * 150 + p[2] * 29 + 128) >> 8; + for (int c = 0; c < 3; c++) { + int v = target[lum][c]; + if (mode == TINT_FILTERED) v += (p[c] - lum) * 3 / 4; + p[c] = (uint8_t)(v < 0 ? 0 : v > 255 ? 255 : v); + } + last_in = word, have = 1; + memcpy(&last_out, p, 4); + } +} + +/* ---- the documents the jobs see ---- */ + +/* A pane's document and its lanes, shared with the jobs: found by id in + * `docs` under `docs_lock`, alive while its pane is open or a job runs on + * it. A job's pixels are its until the pane takes them (`unclaimed`): an + * answer nobody takes is freed with the document. */ +typedef struct doc { + uint64_t id; + int refs, closed; + pardes_pdf_document *base, *lane[LANES]; + int busy[LANES]; + pardes_pdf_cookie cookie[4]; + void *unclaimed[24]; +} doc; + +static pthread_mutex_t docs_lock = PTHREAD_MUTEX_INITIALIZER; +static doc *docs[64]; +static uint64_t doc_ids; + +static void doc_free(doc *d) { + for (int i = 0; i < 24; i++) unheap(d->unclaimed[i]); + for (int i = 0; i < LANES; i++) pardes_pdf_close(d->lane[i]); + pardes_pdf_close(d->base); + unheap(d); +} + +static doc *doc_open(const uint8_t *bytes, uint64_t len, int *pages) { + doc *d = heap(sizeof *d); + if (!d) return 0; + memset(d, 0, sizeof *d); + d->base = pardes_pdf_open_memory(bytes, (size_t)len, pages); + for (int i = 0; d->base && i < LANES; i++) d->lane[i] = pardes_pdf_lane_clone(d->base); + int at = -1; + pthread_mutex_lock(&docs_lock); + for (int i = 0; i < 64 && at < 0; i++) + if (!docs[i]) at = i; + if (d->base && at >= 0) d->id = ++doc_ids, d->refs = 1, docs[at] = d; + pthread_mutex_unlock(&docs_lock); + if (!d->base || at < 0) { + doc_free(d); + return 0; + } + return d; +} + +/* One more reference to the open document `id`, or null. */ +static doc *doc_take(uint64_t id) { + doc *got = 0; + pthread_mutex_lock(&docs_lock); + for (int i = 0; i < 64 && !got; i++) + if (docs[i] && docs[i]->id == id && !docs[i]->closed) got = docs[i], got->refs++; + pthread_mutex_unlock(&docs_lock); + return got; +} + +static void doc_drop(doc *d, int closing) { + int last = 0; + pthread_mutex_lock(&docs_lock); + if (closing) d->closed = 1; + if (--d->refs == 0) { + last = 1; + for (int i = 0; i < 64; i++) + if (docs[i] == d) docs[i] = 0; + } + pthread_mutex_unlock(&docs_lock); + if (last) doc_free(d); +} + +/* `p`, a job's, the pane's now. */ +static void claim(doc *d, const void *p) { + if (!p) return; + pthread_mutex_lock(&docs_lock); + for (int i = 0; i < 24; i++) + if (d->unclaimed[i] == p) d->unclaimed[i] = 0; + pthread_mutex_unlock(&docs_lock); +} + +/* ---- a pane ---- */ + +typedef struct marks { + pardes_pdf_highlight *at; + uint32_t n; +} marks; + +/* A page's pixels: `band_h` rows from `band_y` of its `w` x `h` raster, as + * `req`, the tint and `shown` made them; and the job it waits for. */ +typedef struct slot { + int page; /* -1: empty */ + uint8_t *rgba, *clean; /* clean: before highlights and tint, kept once highlighted */ + uint32_t w, h, band_y, band_h; + uint32_t rev, from, dirty_y, dirty_h; + pardes_pdf_request req; + int tint; + uint32_t ink, paper; + marks shown; + uint32_t token, want_y, want_h; + pardes_pdf_request want; + marks asked; + int failed; +} slot; + +typedef struct job { + uint32_t token; + int sizes; +} job; + +typedef struct pdf { + doc *d; + char name[256]; /* the file's, in the rows a pane lists */ + int pages, page; /* page: the one at the window's top */ + pardes_pdf_page_size *size; + int sizes_assumed, sizes_asked; + uint64_t *y; /* each page's top on the strip */ + uint32_t *ph; /* and its height there */ + uint64_t height; /* the strip's */ + uint32_t vw, vh; /* the window the strip is laid out for, in pixels */ + int laid, laid_fit, fit; + pa_view view; + double top; /* the strip's pixel at the window's top */ + int want_page; /* -1, else laid out next at this page, want_frac down it */ + double want_frac, want_x, want_y; /* or an outline's place there (NAN: none) */ + uint16_t pan; /* fit height: how far across, 0..65535 */ + int tint; + slot s[SLOTS]; + uint32_t revs; + job jobs[4]; + int warm; + uint8_t blank[4]; /* the paper a page shows until its pixels land */ + /* the text of the page shown, the search, the selection, the pointer */ + char *text; + uint32_t text_len; + int text_page; + char query[256]; + uint32_t query_len; + pardes_pdf_search_quad *hits; + uint32_t nhits, hit_count, hit; + int hits_page, reveal; + pardes_pdf_quad *sel; + uint32_t nsel, sel_len; + char *sel_text; + int sel_page, press_page; + pardes_pdf_point anchor, head; + int pressed, chorded, look_pending; + uint16_t look_col, look_row; + pardes_pdf_quad hover; + int hover_page, hover_link, hover_wait; + uint16_t hover_col, hover_row; + uint64_t hover_at; + uint32_t count; /* a key's count, typed before it */ + int g; +} pdf; + +static void say(const char *text, int err) { api->say(text, (uint32_t)strlen(text), err); } + +/* ---- the strip ---- */ + +static uint32_t page_height(const pdf *st, int p) { + if (st->fit) return st->vh; + double h = round((double)st->vw * st->size[p].height / st->size[p].width); + return h < 1 ? 1 : h > 4e9 ? 4000000000u : (uint32_t)h; +} + +static int page_at(const pdf *st, double y) { + if (st->pages == 0 || !st->laid) return st->page; + double last = st->height ? (double)(st->height - 1) : 0, top = floor(y); + uint64_t at = (uint64_t)(top < 0 ? 0 : top > last ? last : top); + int lo = 0, hi = st->pages; + while (lo + 1 < hi) { + int mid = lo + (hi - lo) / 2; + if (st->y[mid] <= at) lo = mid; else hi = mid; + } + if (at >= st->y[lo] + st->ph[lo] && lo + 1 < st->pages) lo++; + return lo; +} + +static void clamp_top(pdf *st) { + double m = st->height > st->vh ? (double)(st->height - st->vh) : 0; + st->top = st->top < 0 ? 0 : st->top > m ? m : st->top; +} + +/* Where the window's top is: its page and how far down it. */ +static void anchor_here(pdf *st) { + int p = page_at(st, st->top); + st->want_page = p; + st->want_frac = (st->top - (double)st->y[p]) / (st->ph[p] ? st->ph[p] : 1); + st->want_x = st->want_y = NAN; +} + +/* The strip laid out for the view, keeping the page and how far down it + * the window's top was (a resize, a fit, the sizes landed), or at + * `want_page`. */ +static void layout(pdf *st) { + uint32_t vw = (uint32_t)st->view.cols * st->view.cell_w, vh = (uint32_t)st->view.rows * st->view.cell_h; + if (vw == 0 || vh == 0 || st->pages == 0) return; + int moved = !st->laid || vw != st->vw || vh != st->vh || st->fit != st->laid_fit; + if (moved && st->laid && st->want_page < 0) anchor_here(st); + if (!moved && st->want_page < 0) return; + st->vw = vw, st->vh = vh, st->laid_fit = st->fit; + uint64_t at = 0; + for (int p = 0; p < st->pages; p++) { + st->y[p] = at; + st->ph[p] = page_height(st, p); + at += st->ph[p] + (p + 1 < st->pages ? GAP_PX : 0); + } + st->height = at; + st->laid = 1; + if (st->want_page >= 0) { + int p = st->want_page < st->pages ? st->want_page : st->pages - 1; + double frac = st->want_frac < 0 ? 0 : st->want_frac > 1 ? 1 : st->want_frac; + if (!isnan(st->want_y) && isfinite(st->want_y)) { + double y = st->want_y < 0 ? 0 : st->want_y > st->size[p].height ? st->size[p].height : st->want_y; + frac = y / st->size[p].height; + } + st->top = round((double)st->y[p] + frac * st->ph[p]); /* a pixel's: P:F rounds */ + if (!isnan(st->want_x) && isfinite(st->want_x) && st->fit) { + double shown = (double)vh * st->size[p].width / st->size[p].height; + if (shown > vw) { + double x = st->want_x < 0 ? 0 : st->want_x > st->size[p].width ? st->size[p].width : st->want_x; + double over = shown - vw, want = x / st->size[p].width * shown - vw / 2.0; + st->pan = (uint16_t)round((want < 0 ? 0 : want > over ? over : want) / over * 65535.0); + } + } + st->want_page = -1; + } + clamp_top(st); +} + +/* Where a raster of `iw` x `ih` lies in a page's `bw` x `bh` box: the part + * of it shown (`s*`) and where (`d*`, the box's pixels), its axis fitted, + * the other letterboxed or, past the box, cropped (at `pan`, fit height). */ +typedef struct geo { uint32_t sx, sy, sw, sh, dx, dy, dw, dh; } geo; + +static int fit_geo(uint32_t iw, uint32_t ih, uint32_t bw, uint32_t bh, int by_height, uint16_t pan, geo *g) { + memset(g, 0, sizeof *g); + if (!iw || !ih || !bw || !bh) return 0; + if (!by_height) { + uint64_t sh = (uint64_t)ih * bw; + if (sh <= (uint64_t)bh * iw) { + uint32_t full = (uint32_t)(sh / iw); + full += !full; + *g = (geo){0, 0, iw, ih, 0, (bh - full) / 2, bw, full}; + return 1; + } + uint64_t crop = (uint64_t)bh * iw / bw; + if (!crop) return 0; + uint32_t ch = crop < ih ? (uint32_t)crop : ih; + uint64_t d = (uint64_t)ch * bw / iw; + uint32_t dh = d < 1 ? 1 : d > bh ? bh : (uint32_t)d; + *g = (geo){0, 0, iw, ch, 0, (bh - dh) / 2, bw, dh}; + return 1; + } + uint64_t sw = (uint64_t)iw * bh; + if (sw <= (uint64_t)bw * ih) { + uint32_t full = (uint32_t)(sw / ih); + full += !full; + *g = (geo){0, 0, iw, ih, (bw - full) / 2, 0, full, bh}; + return 1; + } + uint64_t crop = (uint64_t)bw * ih / bh; + if (!crop) return 0; + uint32_t cw = crop < iw ? (uint32_t)crop : iw; + uint64_t d = (uint64_t)cw * bh / ih; + uint32_t dw = d < 1 ? 1 : d > bw ? bw : (uint32_t)d; + uint32_t over = iw - cw; + uint32_t x = over == 0 || pan == 0 ? 0 : pan == 65535 ? over : (uint32_t)(((uint64_t)over * pan + 32767) / 65535); + *g = (geo){x, 0, cw, ih, (bw - dw) / 2, 0, dw, bh}; + return 1; +} + +/* Rows y0..y1 of page `p`'s raster over a window `vh` pixels tall, and + * where (`at_y`, `at_h`); 0 when none of it is there. */ +typedef struct rows { geo g; uint32_t y0, y1, at_y, at_h; } rows; + +static int page_rows(const pdf *st, int p, uint32_t iw, uint32_t ih, uint32_t vh, rows *r) { + if (!fit_geo(iw, ih, st->vw, st->ph[p], st->fit, st->pan, &r->g) || !r->g.dh || !r->g.sh) return 0; + int64_t full_y = (int64_t)st->y[p] - (int64_t)floor(st->top) + r->g.dy, full_b = full_y + r->g.dh; + int64_t vy = full_y > 0 ? full_y : 0, vb = full_b < (int64_t)vh ? full_b : (int64_t)vh; + if (vb <= vy) return 0; + uint64_t ry0 = (uint64_t)(vy - full_y), ry1 = (uint64_t)(vb - full_y); + r->y0 = r->g.sy + (uint32_t)(ry0 * r->g.sh / r->g.dh); + uint64_t e = (ry1 * r->g.sh + r->g.dh - 1) / r->g.dh; + r->y1 = r->g.sy + (uint32_t)(e < r->g.sh ? e : r->g.sh); + r->at_y = (uint32_t)vy, r->at_h = (uint32_t)(vb - vy); + return r->y1 > r->y0; +} + +/* The pages over the window: the first, and how many. */ +static int visible(const pdf *st, int *first) { + *first = 0; + if (!st->laid) return 0; + int p = page_at(st, st->top); + if (p > 0 && (double)(st->y[p - 1] + st->ph[p - 1]) > st->top) p--; + *first = p; + int n = 0; + for (; p < st->pages && (double)st->y[p] < st->top + st->vh; p++) n++; + return n; +} + +static pardes_pdf_request request_now(const pdf *st) { + return (pardes_pdf_request){ + .dpi = st->view.dpi ? st->view.dpi : 96, + .minimum_width = st->view.fill ? (int)st->vw : 0, + .minimum_height = st->view.fill ? (int)st->vh : 0, + .max_dimension = st->view.max_px ? st->view.max_px : 1200, + .display_width = st->fit ? 0 : (int)st->vw, + .display_height = st->fit ? (int)st->vh : 0, + }; +} + +static int same_req(pardes_pdf_request a, pardes_pdf_request b) { return !memcmp(&a, &b, sizeof a); } + +/* The raster page `p` renders to under `q`, as the bridge's geometry + * computes it, give or take the rounding of its corners. */ +static void raster_of(const pdf *st, int p, pardes_pdf_request q, uint32_t *w, uint32_t *h) { + float pw = st->size[p].width, ph = st->size[p].height, scale = (float)q.dpi / 72.0f, shown = 0; + if (q.minimum_width > 0) scale = fmaxf(scale, (float)q.minimum_width / pw); + if (q.minimum_height > 0) scale = fmaxf(scale, (float)q.minimum_height / ph); + if (pw * scale > (float)q.max_dimension) scale = (float)q.max_dimension / pw; + if (q.display_width > 0) shown = fmaxf(shown, (float)q.display_width / pw); + if (q.display_height > 0) shown = fmaxf(shown, (float)q.display_height / ph); + if (ph * scale > (float)q.max_dimension) scale = fminf(scale, fmaxf((float)q.max_dimension / ph, shown)); + if (ph * scale > (float)PARDES_PDF_MAX_RASTER_ROWS) scale = (float)PARDES_PDF_MAX_RASTER_ROWS / ph; + *w = (uint32_t)fmaxf(1, roundf(pw * scale)), *h = (uint32_t)fmaxf(1, roundf(ph * scale)); +} + +static slot *slot_of(pdf *st, int p) { + for (int i = 0; i < SLOTS; i++) + if (st->s[i].page == p) return &st->s[i]; + return 0; +} + +static void slot_clear(slot *s) { + unheap(s->rgba), unheap(s->clean), unheap(s->shown.at), unheap(s->asked.at); + memset(s, 0, sizeof *s); + s->page = -1; +} + +/* ---- highlights ---- */ + +static pardes_pdf_highlight mark(pardes_pdf_quad q, uint32_t rgb, uint8_t a, int kind) { + return (pardes_pdf_highlight){q, {(uint8_t)(rgb >> 16), (uint8_t)(rgb >> 8), (uint8_t)rgb, a}, kind}; +} + +/* Page `p`'s highlights, as painted: the pointer's, the search's, the + * selection's. */ +static uint32_t marks_of(const pdf *st, int p, pardes_pdf_highlight *out) { + uint32_t n = 0; + if (st->hover_page == p) out[n++] = mark(st->hover, st->hover_link ? st->view.link : st->view.sel, 0x2c, PARDES_PDF_HIGHLIGHT_CUSTOM); + if (st->hits_page == p) + for (uint32_t i = 0; i < st->nhits && n < MARKS; i++) out[n++] = mark(st->hits[i].quad, 0xffd54f, 0x70, PARDES_PDF_HIGHLIGHT_SEARCH); + if (st->sel_page == p) + for (uint32_t i = 0; i < st->nsel && n < MARKS; i++) out[n++] = mark(st->sel[i], st->view.sel, 0x78, PARDES_PDF_HIGHLIGHT_SELECTION); + return n; +} + +static int same_marks(marks m, const pardes_pdf_highlight *now, uint32_t n) { + return m.n == n && (n == 0 || !memcmp(m.at, now, n * sizeof *now)); +} + +static int keep_marks(marks *m, const pardes_pdf_highlight *now, uint32_t n) { + pardes_pdf_highlight *copy = n ? heap(n * sizeof *copy) : 0; + if (n && !copy) return 0; + if (n) memcpy(copy, now, n * sizeof *copy); + unheap(m->at); + m->at = copy, m->n = n; + return 1; +} + +/* ---- jobs ---- */ + +enum { JOB_RENDER = 1, JOB_SIZES = 2 }; + +typedef struct job_in { + uint32_t op, cookie; + uint64_t doc; + int32_t page, tint; + pardes_pdf_request req; + uint32_t band_y, band_h, ink, paper, keep_clean, n; + pardes_pdf_highlight hl[]; +} job_in; + +typedef struct job_out { + uint32_t ok, busy, w, h, band_y, band_h, n; + uint8_t *rgba, *clean; + pardes_pdf_page_size *sizes; +} job_out; + +/* Jobs out, renders only when not `all`. */ +static int jobs_out(const pdf *st, int all) { + int n = 0; + for (int i = 0; i < 4; i++) n += st->jobs[i].token != 0 && (all || !st->jobs[i].sizes); + return n; +} + +/* A job of `in` asked: its token, 0 when none could be. */ +static uint32_t ask(pdf *st, job_in *in, uint32_t n, int sizes) { + int at = -1; + for (int i = 0; i < 4 && at < 0; i++) + if (!st->jobs[i].token) at = i; + if (at < 0) return 0; + in->doc = st->d->id, in->cookie = (uint32_t)at; + atomic_store((_Atomic int *)&st->d->cookie[at].abort, 0); + uint32_t token = api->job(in, n); + if (token) st->jobs[at] = (job){token, sizes}; + return token; +} + +static void abort_job(pdf *st, uint32_t token) { + for (int i = 0; i < 4; i++) + if (token && st->jobs[i].token == token) atomic_store((_Atomic int *)&st->d->cookie[i].abort, 1); +} + +/* The band of page `p` (a `w` x `h` raster) asked for: the whole, or for + * a page too tall for one raster, the chunks round what the window shows + * and a screenful either side. */ +static void band_of(const pdf *st, int p, uint32_t w, uint32_t h, uint32_t *y, uint32_t *bh) { + uint32_t cap = BAND_BYTES / (w * 4); + cap = (cap > BAND_ROWS ? BAND_ROWS : cap) / CHUNK * CHUNK; + rows r = {0}; + if (h <= cap) { + *y = 0, *bh = h; + return; + } + uint32_t y0 = 0, y1 = CHUNK; + if (page_rows(st, p, w, h, st->vh, &r)) { + uint32_t seen = r.y1 - r.y0; + y0 = r.y0 > seen ? r.y0 - seen : 0, y1 = r.y1 + seen; + } + y0 = y0 / CHUNK * CHUNK, y1 = (y1 + CHUNK - 1) / CHUNK * CHUNK; + if (y1 - y0 > cap) y0 = r.y0 / CHUNK * CHUNK, y1 = y0 + cap; + *y = y0, *bh = (y1 < h ? y1 : h) - y0; +} + +static void ask_page(pdf *st, slot *s, pardes_pdf_request q, uint32_t y, uint32_t h, const pardes_pdf_highlight *now, uint32_t n) { + size_t size = sizeof(job_in) + n * sizeof(pardes_pdf_highlight); + job_in *in = heap(size); + if (!in) return; + memset(in, 0, size); + in->op = JOB_RENDER, in->page = s->page, in->tint = st->tint, in->req = q; + in->band_y = y, in->band_h = h, in->ink = st->view.fg, in->paper = st->view.bg; + in->n = n, in->keep_clean = n > 0 || s->clean; + if (n) memcpy(in->hl, now, n * sizeof *now); + uint32_t token = keep_marks(&s->asked, now, n) ? ask(st, in, (uint32_t)size, 0) : 0; + unheap(in); + if (!token) return; + s->token = token, s->want = q, s->want_y = y, s->want_h = h, s->failed = 0; +} + +/* Only the highlights moved: their rows painted again from the clean + * copy on the loop, never the page, and said as those rows. */ +static int repaint(pdf *st, slot *s, const pardes_pdf_highlight *now, uint32_t n) { + if (!s->clean || !s->rgba) return 0; + static pardes_pdf_highlight both[2 * MARKS]; /* the loop's alone */ + memcpy(both, s->shown.at, s->shown.n * sizeof *both); + memcpy(both + s->shown.n, now, n * sizeof *both); + int y0 = 0, y1 = 0; + if (pardes_pdf_highlight_rows(st->d->base, s->page, &s->req, both, s->shown.n + n, &y0, &y1) != PARDES_PDF_OK) return 0; + if (y0 < (int)s->band_y) y0 = (int)s->band_y; + if (y1 > (int)(s->band_y + s->band_h)) y1 = (int)(s->band_y + s->band_h); + if (y1 > y0) { + size_t stride = (size_t)s->w * 4, at = (size_t)((uint32_t)y0 - s->band_y) * stride, len = (size_t)(y1 - y0) * stride; + memcpy(s->rgba + at, s->clean + at, len); + if (pardes_pdf_paint_highlights(st->d->base, s->page, &s->req, now, n, s->rgba + at, len, (int)s->w, (int)s->h, (int)stride, y0, y1 - y0) != PARDES_PDF_OK) { + unheap(s->rgba), s->rgba = 0; /* half made: rendered again */ + return 0; + } + tint(s->rgba + at, len, s->tint, s->ink, s->paper); + s->from = s->rev, s->rev = ++st->revs; + s->dirty_y = (uint32_t)y0 - s->band_y, s->dirty_h = (uint32_t)(y1 - y0); + } + return keep_marks(&s->shown, now, n); +} + +/* What the window shows (and the page past it) made so: pages gone + * dropped, highlights moved repainted, the rest asked of the lanes. */ +static void reconcile(pdf *st) { + if (!st->laid || !st->d) return; + if (st->sizes_assumed && !st->sizes_asked) { + job_in in = {.op = JOB_SIZES, .page = st->pages}; + st->sizes_asked = ask(st, &in, sizeof in, 1) != 0; + } + int first, n = visible(st, &first); + if (n > 0 && first + n < st->pages) n++; /* the page ahead */ + for (int i = 0; i < SLOTS; i++) + if (st->s[i].page >= 0 && (st->s[i].page < first || st->s[i].page >= first + n)) { + abort_job(st, st->s[i].token); + slot_clear(&st->s[i]); + } + pardes_pdf_request q = request_now(st); + static pardes_pdf_highlight now[MARKS]; /* the loop's alone */ + for (int p = first; p < first + n; p++) { + slot *s = slot_of(st, p); + for (int i = 0; i < SLOTS && !s; i++) + if (st->s[i].page < 0) s = &st->s[i], s->page = p; + if (!s) break; + uint32_t w, h, y, bh; + raster_of(st, p, q, &w, &h); + band_of(st, p, s->rgba && same_req(s->req, q) ? s->w : w, s->rgba && same_req(s->req, q) ? s->h : h, &y, &bh); + uint32_t k = marks_of(st, p, now); + if (s->rgba && same_req(s->req, q) && s->tint == st->tint && s->ink == st->view.fg && s->paper == st->view.bg && + s->band_y <= y && s->band_y + s->band_h >= y + bh) { + if (same_marks(s->shown, now, k) || repaint(st, s, now, k)) continue; + } + if (s->token) { + if (same_req(s->want, q) && s->want_y == y && s->want_h == bh && same_marks(s->asked, now, k)) continue; + abort_job(st, s->token); + s->token = 0; + } + if (s->failed && same_req(s->want, q)) continue; + /* a lane's first job parses the document and loads its fonts: the + * second starts once the first is warm */ + if (jobs_out(st, 1) >= LANES || jobs_out(st, 0) >= (st->warm ? LANES : 1)) continue; + ask_page(st, s, q, y, bh, now, k); + } +} + +/* A job's pixels the pane's to take (`unclaimed`), or freed when its pane + * is gone. */ +static void hand(doc *d, job_out *res) { + void *ps[3] = {res->rgba, res->clean, res->sizes}; + int kept = 1; + pthread_mutex_lock(&docs_lock); + for (int k = 0; k < 3; k++) + if (ps[k]) { + int at = -1; + for (int i = 0; i < 24 && at < 0 && !d->closed; i++) + if (!d->unclaimed[i]) at = i; + if (at < 0) kept = 0; else d->unclaimed[at] = ps[k]; + } + pthread_mutex_unlock(&docs_lock); + if (kept) return; + for (int k = 0; k < 3; k++) claim(d, ps[k]), unheap(ps[k]); + res->rgba = res->clean = 0, res->sizes = 0, res->ok = 0; +} + +static void render_job(pardes_pdf_document *ld, const job_in *in, job_out *res) { + pardes_pdf_raster_layout L; + if (pardes_pdf_measure_render(ld, in->page, &in->req, &L) != PARDES_PDF_OK) return; + uint32_t full = (uint32_t)L.height, by = in->band_y < full ? in->band_y : 0; + uint32_t bh = in->band_h && by + in->band_h <= full ? in->band_h : full - by; + /* a tall page's chunk renders past its edges, thrown away: a row is the + * same row however its band was cut */ + int cut = bh < full; + uint32_t ry = cut && by > OVERLAP ? by - OVERLAP : cut ? 0 : by; + uint32_t rb = cut && by + bh + OVERLAP < full ? by + bh + OVERLAP : by + bh; + size_t stride = (size_t)L.stride, len = stride * bh, rlen = stride * (rb - ry); + uint8_t *px = heap(rlen ? rlen : 1); + int ok = px && pardes_pdf_render_into(ld, in->page, &in->req, 0, 0, px, rlen, L.width, L.height, L.stride, (int)ry, (int)(rb - ry), 0) == PARDES_PDF_OK; + if (ok && ry != by) memmove(px, px + (size_t)(by - ry) * stride, len); + if (ok && in->keep_clean) { + res->clean = heap(len ? len : 1); + ok = res->clean != 0; + if (ok) memcpy(res->clean, px, len); + } + if (ok && in->n) ok = pardes_pdf_paint_highlights(ld, in->page, &in->req, in->hl, in->n, px, len, L.width, L.height, L.stride, (int)by, (int)bh) == PARDES_PDF_OK; + if (ok) tint(px, len, in->tint, in->ink, in->paper); + if (!ok) { + unheap(px), unheap(res->clean), res->clean = 0; + return; + } + res->rgba = px, res->w = (uint32_t)L.width, res->h = full, res->band_y = by, res->band_h = bh, res->ok = 1; +} + +/* On a worker: the job on a free lane of its document. */ +static uint32_t job_run(const uint8_t *bytes, uint32_t n, pa_out *out) { + job_out *res = out->alloc(out, sizeof *res); + if (!res || n < sizeof(job_in)) return 0; + memset(res, 0, sizeof *res); + const job_in *in = (const job_in *)bytes; + doc *d = doc_take(in->doc); + if (!d) return sizeof *res; + int lane = -1; + pthread_mutex_lock(&docs_lock); + for (int i = 0; i < LANES && lane < 0; i++) + if (!d->busy[i] && d->lane[i]) lane = i, d->busy[i] = 1; + pthread_mutex_unlock(&docs_lock); + if (lane >= 0) { + pardes_pdf_document *ld = d->lane[lane]; + pardes_pdf_cookie *cookie = &d->cookie[in->cookie & 3]; + if (pardes_pdf_lane_open(ld) == PARDES_PDF_OK) { + if (in->op == JOB_SIZES) { + res->sizes = heap((size_t)(in->page > 0 ? in->page : 1) * sizeof *res->sizes); + int ok = res->sizes != 0; + for (int p = 0; ok && p < in->page; p++) + ok = !(p % 64 == 0 && atomic_load((_Atomic int *)&cookie->abort)) && pardes_pdf_get_page_size(ld, p, &res->sizes[p]) == PARDES_PDF_OK; + res->n = (uint32_t)in->page, res->ok = (uint32_t)ok; + } else { + pardes_pdf_set_cookie(ld, cookie); + render_job(ld, in, res); + pardes_pdf_set_cookie(ld, 0); + } + } + pthread_mutex_lock(&docs_lock); + d->busy[lane] = 0; + pthread_mutex_unlock(&docs_lock); + hand(d, res); + } else { + res->busy = 1; + } + doc_drop(d, 0); + return sizeof *res; +} + +static void job_done(void *v, uint32_t token, const uint8_t *bytes, uint32_t n) { + pdf *st = v; + if (!st || !st->d || n < sizeof(job_out)) return; + job_out res; + memcpy(&res, bytes, sizeof res); + claim(st->d, res.rgba), claim(st->d, res.clean), claim(st->d, res.sizes); + int at = -1; + for (int i = 0; i < 4 && at < 0; i++) + if (st->jobs[i].token == token) at = i; + if (at < 0) { + unheap(res.rgba), unheap(res.clean), unheap(res.sizes); + return; + } + int sizes = st->jobs[at].sizes; + st->jobs[at].token = 0; + st->warm = 1; + if (sizes) { + st->sizes_assumed = 0; + if (res.ok && (int)res.n == st->pages && memcmp(res.sizes, st->size, res.n * sizeof *res.sizes)) { + if (st->laid && st->want_page < 0) anchor_here(st); + memcpy(st->size, res.sizes, res.n * sizeof *res.sizes); + st->laid = 0; + } + unheap(res.sizes); + return; + } + slot *s = 0; + for (int i = 0; i < SLOTS && !s; i++) + if (st->s[i].token == token) s = &st->s[i]; + if (!s || !res.ok) { + if (s) s->token = 0, s->failed = !res.busy; + unheap(res.rgba), unheap(res.clean); + return; + } + unheap(s->rgba), unheap(s->clean), unheap(s->shown.at); + s->rgba = res.rgba, s->clean = res.clean; + s->w = res.w, s->h = res.h, s->band_y = res.band_y, s->band_h = res.band_h; + s->req = s->want, s->tint = st->tint, s->ink = st->view.fg, s->paper = st->view.bg; + s->shown = s->asked, s->asked = (marks){0, 0}; + s->token = 0, s->from = 0, s->dirty_y = s->dirty_h = 0; + s->rev = ++st->revs; +} + +/* ---- the page shown: its text, its search ---- */ + +static void drop_text(pdf *st) { + unheap(st->text); + st->text = 0, st->text_len = 0, st->text_page = -1; +} + +static const char *page_text(pdf *st, uint32_t *len) { + if (st->text_page != st->page && st->d) { + drop_text(st); + pardes_pdf_text t; + if (pardes_pdf_page_text(st->d->base, st->page, &t) == PARDES_PDF_OK) { + st->text = heap(t.len ? t.len : 1); + if (st->text) memcpy(st->text, t.data, t.len), st->text_len = (uint32_t)t.len; + pardes_pdf_drop_text(st->d->base, t.handle); + } + st->text_page = st->page; + } + *len = st->text_len; + return st->text ? st->text : ""; +} + +static void drop_hits(pdf *st) { + unheap(st->hits); + st->hits = 0, st->nhits = st->hit_count = 0, st->hits_page = -1; +} + +/* The search's hits on `page`: their count, its quads kept when `keep`. */ +static uint32_t search_page(pdf *st, int page, int keep) { + char q[257]; + memcpy(q, st->query, st->query_len), q[st->query_len] = 0; + pardes_pdf_search_result r; + if (!st->query_len || pardes_pdf_search_page(st->d->base, page, q, &r) != PARDES_PDF_OK) return 0; + uint32_t hits = (uint32_t)r.hit_count; + if (keep) { + drop_hits(st); + st->hits = r.quad_count ? heap(r.quad_count * sizeof *st->hits) : 0; + if (st->hits) memcpy(st->hits, r.quads, r.quad_count * sizeof *st->hits), st->nhits = (uint32_t)r.quad_count; + st->hit_count = hits, st->hits_page = page; + if (st->hit >= hits) st->hit = hits ? hits - 1 : 0; + } + pardes_pdf_drop_search_result(st->d->base, r.handle); + return hits; +} + +/* The page at the window's top is `p` now: what was the old one's goes. */ +static void to_page(pdf *st, int p) { + if (p == st->page) return; + st->page = p; + drop_hits(st); + st->hit = 0; + st->reveal = st->query_len > 0; +} + +static void set_top(pdf *st, double top) { + st->top = top; + clamp_top(st); + to_page(st, page_at(st, st->top)); +} + +/* Turn to page `p`, its top at the window's. */ +static void go_page(pdf *st, int p) { + p = p < 0 ? 0 : p >= st->pages ? st->pages - 1 : p; + to_page(st, p); + st->want_page = p, st->want_frac = 0, st->want_x = st->want_y = NAN; + if (st->laid) layout(st); +} + +static void scroll_by(pdf *st, double px) { + if (st->laid) set_top(st, st->top + px); +} + +/* The search's hit `hit` in the window: centred (fit width), or panned to + * (fit height). */ +static void reveal_hit(pdf *st) { + st->reveal = 0; + if (!st->laid || st->hits_page != st->page || !st->hit_count) return; + const pardes_pdf_quad *q = 0; + for (uint32_t i = 0; i < st->nhits && !q; i++) + if (st->hits[i].hit == st->hit) q = &st->hits[i].quad; + if (!q) return; + float cx = (q->ul.x + q->ur.x + q->ll.x + q->lr.x) / 4, cy = (q->ul.y + q->ur.y + q->ll.y + q->lr.y) / 4; + if (!st->fit) { + set_top(st, (double)st->y[st->page] + cy * st->ph[st->page] - st->vh / 2.0); + return; + } + slot *s = slot_of(st, st->page); + if (!s || !s->rgba) return; + geo g; + if (!fit_geo(s->w, s->h, st->vw, st->ph[st->page], 1, st->pan, &g)) return; + uint32_t at = (uint32_t)(cx * s->w); + if (at >= g.sx && at < g.sx + g.sw) return; + uint32_t over = s->w - g.sw; + if (!over) return; + uint32_t want = at > g.sw / 2 ? at - g.sw / 2 : 0; + st->pan = (uint16_t)(((uint64_t)(want < over ? want : over) * 65535 + over / 2) / over); +} + +/* ---- the selection and the pointer ---- */ + +static void drop_sel(pdf *st) { + int had = st->nsel > 0; + unheap(st->sel), unheap(st->sel_text); + st->sel = 0, st->sel_text = 0, st->nsel = st->sel_len = 0, st->sel_page = -1; + if (had) api->select("", 0); +} + +/* The page and its point under the middle of cell (col, row), from where + * its pixels are shown; clamped to the page when `clamp`. */ +static int point_at(pdf *st, uint16_t col, uint16_t row, int clamp, int *page, pardes_pdf_point *pt) { + if (!st->laid) return 0; + int64_t px = (int64_t)col * st->view.cell_w + st->view.cell_w / 2, py = (int64_t)row * st->view.cell_h + st->view.cell_h / 2; + int p = clamp && *page >= 0 ? *page : page_at(st, st->top + (double)py); + slot *s = slot_of(st, p); + if (!s || !s->rgba) return 0; + geo g; + if (!fit_geo(s->w, s->h, st->vw, st->ph[p], st->fit, st->pan, &g)) return 0; + double left = g.dx, top = (double)st->y[p] - floor(st->top) + g.dy; + double x = (double)px, y = (double)py; + if (clamp) { + double e = 1.0 / 1024; + x = x < left ? left : x > left + g.dw - e ? left + g.dw - e : x; + y = y < top ? top : y > top + g.dh - e ? top + g.dh - e : y; + } else if (x < left || x >= left + g.dw || y < top || y >= top + g.dh) { + return 0; + } + double sx = g.sx + (x - left) * g.sw / g.dw, sy = g.sy + (y - top) * g.sh / g.dh; + uint32_t ix = (uint32_t)sx < s->w ? (uint32_t)sx : s->w - 1, iy = (uint32_t)sy < s->h ? (uint32_t)sy : s->h - 1; + *page = p; + pt->x = ((float)ix + 0.5f) / (float)s->w, pt->y = ((float)iy + 0.5f) / (float)s->h; + return 1; +} + +/* The selection from the anchor to `to` on `page`, word-snapped by MuPDF; + * what it holds handed to pardes. */ +static int select_to(pdf *st, int page, pardes_pdf_point to) { + pardes_pdf_selection sel; + if (pardes_pdf_select(st->d->base, page, st->anchor, to, &sel) != PARDES_PDF_OK) return 0; + pardes_pdf_owned_text t; + if (pardes_pdf_copy_selection(st->d->base, page, sel.start, sel.end, &t) != PARDES_PDF_OK) { + pardes_pdf_drop_selection(st->d->base, sel.handle); + return 0; + } + unheap(st->sel), unheap(st->sel_text); + st->sel = sel.quad_count ? heap(sel.quad_count * sizeof *st->sel) : 0; + st->nsel = st->sel ? (uint32_t)sel.quad_count : 0; + if (st->sel) memcpy(st->sel, sel.quads, sel.quad_count * sizeof *st->sel); + st->sel_text = t.len ? heap(t.len) : 0; + st->sel_len = st->sel_text ? (uint32_t)t.len : 0; + if (st->sel_text) memcpy(st->sel_text, t.data, t.len); + st->sel_page = page, st->head = to; + api->select((const char *)t.data, (uint32_t)t.len); + pardes_pdf_drop_owned_text(st->d->base, t.handle); + pardes_pdf_drop_selection(st->d->base, sel.handle); + return 1; +} + +static int sel_contains(const pdf *st, int page, pardes_pdf_point pt) { + if (st->sel_page != page) return 0; + for (uint32_t i = 0; i < st->nsel; i++) + if (pardes_pdf_point_inside_quad(pt, st->sel[i])) return 1; + return 0; +} + +/* The word or link under a cell: its quad and its text (heap), and the + * link when it is one. */ +typedef struct probe { + int page, has_link; + pardes_pdf_quad quad; + char *text; + uint32_t len; + pardes_pdf_link link; + char uri[1024]; +} probe; + +static int probe_at(pdf *st, uint16_t col, uint16_t row, probe *pr) { + memset(pr, 0, sizeof *pr); + pr->page = -1; + pardes_pdf_point pt; + if (!point_at(st, col, row, 0, &pr->page, &pt)) return 0; + pardes_pdf_owned_text t; + if (pardes_pdf_link_at(st->d->base, pr->page, pt, &pr->link) == PARDES_PDF_OK && pr->link.uri && pr->link.uri_len < sizeof pr->uri && + pr->link.destination_kind != PARDES_PDF_OUTLINE_DESTINATION_NONE) { + memcpy(pr->uri, pr->link.uri, pr->link.uri_len), pr->uri[pr->link.uri_len] = 0; + pr->has_link = 1, pr->quad = pr->link.quad; + if (pardes_pdf_copy_rectangle(st->d->base, pr->page, pr->quad, &t) == PARDES_PDF_OK) { + pr->text = heap(t.len + 1); + if (pr->text) memcpy(pr->text, t.data, t.len), pr->len = (uint32_t)t.len; + pardes_pdf_drop_owned_text(st->d->base, t.handle); + } + return 1; + } + pardes_pdf_selection sel; + if (pardes_pdf_select(st->d->base, pr->page, pt, pt, &sel) != PARDES_PDF_OK) return 0; + int ok = sel.quad_count > 0 && pardes_pdf_copy_selection(st->d->base, pr->page, sel.start, sel.end, &t) == PARDES_PDF_OK; + if (ok) { + pr->quad = sel.quads[0]; + pr->text = t.len ? heap(t.len) : 0; + if (pr->text) memcpy(pr->text, t.data, t.len), pr->len = (uint32_t)t.len; + pardes_pdf_drop_owned_text(st->d->base, t.handle); + ok = pr->len > 0; + } + pardes_pdf_drop_selection(st->d->base, sel.handle); + if (!ok) unheap(pr->text); + return ok; +} + +static void hover_off(pdf *st) { + st->hover_page = -1, st->hover_wait = 0; +} + +/* A link followed: a place in the document scrolled to, else looked at + * (its URI); one whose text names another place than it goes to offers + * both, a +Links. */ +static void follow(pdf *st, const probe *pr) { + if (pr->link.destination_kind == PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) { + to_page(st, pr->link.page); + st->want_page = pr->link.page, st->want_frac = 0; + st->want_x = pr->link.has_x ? pr->link.x : NAN, st->want_y = pr->link.has_y ? pr->link.y : NAN; + layout(st); + return; + } + char shown[512]; + uint32_t k = 0; + for (uint32_t i = 0; i < pr->len && k + 1 < sizeof shown; i++) + if ((unsigned char)pr->text[i] > ' ') shown[k++] = pr->text[i]; + shown[k] = 0; + if (k && strstr(shown, "://") && strcmp(shown, pr->uri)) { + char both[1600]; + int n = snprintf(both, sizeof both, "%s\n%s\n", shown, pr->uri); + if (n > 0 && (size_t)n < sizeof both) { + api->text("+Links", 6, both, (uint32_t)n); + return; + } + } + api->look(pr->uri, (uint32_t)strlen(pr->uri)); +} + +/* ---- the kind ---- */ + +static int reopen_bytes(pdf *st, const uint8_t *bytes, uint64_t len) { + int pages = 0; + st->d = doc_open(bytes, len, &pages); + if (!st->d) return 0; + st->pages = pages; + st->size = api->alloc((size_t)pages * sizeof *st->size); + st->y = api->alloc((size_t)pages * sizeof *st->y); + st->ph = api->alloc((size_t)pages * sizeof *st->ph); + if (!st->size || !st->y || !st->ph || pardes_pdf_get_page_size(st->d->base, 0, &st->size[0]) != PARDES_PDF_OK) { + doc_drop(st->d, 1), st->d = 0; + return 0; + } + /* every page the first's size until a lane measures them */ + for (int p = 1; p < pages; p++) st->size[p] = st->size[0]; + st->sizes_assumed = pages > 1; + return 1; +} + +static void *open(const char *path, const uint8_t *bytes, uint64_t len) { + pdf *st = api->alloc(sizeof *st); + if (!st) return 0; + for (int i = 0; i < SLOTS; i++) st->s[i].page = -1; + st->tint = TINT_FILTERED, st->want_page = 0, st->want_x = st->want_y = NAN; + st->hits_page = st->sel_page = st->hover_page = st->text_page = st->press_page = -1; + if (path) { + const char *b = path; + for (const char *p = path; *p; p++) + if (*p == '/' && p[1]) b = p + 1; + snprintf(st->name, sizeof st->name, "%s", b); + } + if (bytes && !reopen_bytes(st, bytes, len)) say("not a PDF pardes can read", 1); + return st; +} + +static void close(void *v) { + pdf *st = v; + if (!st) return; + for (int i = 0; i < SLOTS; i++) slot_clear(&st->s[i]); + for (int i = 0; i < 4; i++) abort_job(st, st->jobs[i].token); + drop_text(st), drop_hits(st), drop_sel(st); + if (st->d) doc_drop(st->d, 1); + st->d = 0; +} + +static uint64_t tick(void *v, uint64_t now, uint32_t flags) { + pdf *st = v; + (void)flags; + if (!st || !st->d) return 0; + api->view(&st->view); + layout(st); + to_page(st, page_at(st, st->top)); + /* white tinted is the theme's paper */ + uint32_t paper = st->tint == TINT_DISABLED ? 0xffffff : st->view.bg; + st->blank[0] = (uint8_t)(paper >> 16), st->blank[1] = (uint8_t)(paper >> 8), st->blank[2] = (uint8_t)paper, st->blank[3] = 255; + if (st->hover_wait == 1) st->hover_at = now + HOVER_NS, st->hover_wait = 2; + if (st->hover_wait == 2 && now >= st->hover_at) { + probe pr; + st->hover_wait = 0; + if (probe_at(st, st->hover_col, st->hover_row, &pr)) st->hover = pr.quad, st->hover_page = pr.page, st->hover_link = pr.has_link; + unheap(pr.text); + } + if (st->query_len && st->hits_page != st->page) search_page(st, st->page, 1); + if (st->reveal) reveal_hit(st); + reconcile(st); + return st->hover_wait == 2 ? st->hover_at : 0; +} + +static void paint(void *v, const pa_window *win, pa_paint *out) { + const pdf *st = v; + int n = st && st->d ? snprintf(out->prefix, sizeof out->prefix, "[%d/%d]", st->page + 1, st->pages) : 0; + out->prefix_len = n > 0 ? (uint32_t)n : 0; + if (!st || !st->laid) return; + uint32_t vh = (uint32_t)win->rows * win->cell_h; + if (vh > st->vh) vh = st->vh; + int first, count = visible(st, &first); + for (int p = first; p < first + count && out->n < out->cap; p++) { + const slot *s = 0; + for (int i = 0; i < SLOTS && !s; i++) + if (st->s[i].page == p && st->s[i].rgba) s = &st->s[i]; + rows r; + pa_placement *pl = &out->placements[out->n]; + if (s) { + if (!page_rows(st, p, s->w, s->h, vh, &r) || r.y0 < s->band_y || r.y1 > s->band_y + s->band_h) continue; + *pl = (pa_placement){.rgba = s->rgba, .w = s->w, .h = s->band_h, .src = {r.g.sx, r.y0 - s->band_y, r.g.sw, r.y1 - r.y0}, + .dst = {0, 0, win->cols, win->rows}, .at = {r.g.dx, r.at_y, r.g.dw, r.at_h}, .key = (uint64_t)p << 32 | s->rev, + .from = s->from ? (uint64_t)p << 32 | s->from : 0, .dirty_y = s->dirty_y, .dirty_h = s->dirty_h}; + } else { + /* not landed yet: its paper, where it will be */ + uint32_t w = (uint32_t)fmaxf(1, roundf(st->size[p].width * 8)), h = (uint32_t)fmaxf(1, roundf(st->size[p].height * 8)); + if (!page_rows(st, p, w, h, vh, &r)) continue; + *pl = (pa_placement){.rgba = st->blank, .w = 1, .h = 1, .src = {0, 0, 1, 1}, .dst = {0, 0, win->cols, win->rows}, + .at = {r.g.dx, r.at_y, r.g.dw, r.at_h}, .key = (uint64_t)p << 32}; + } + out->n++; + } + if (st->height) { /* the rail's thumb; init refused a core before 2.1 */ + out->at = (float)(st->top / (double)st->height); + out->span = (float)((double)st->vh / (double)st->height); + } +} + +/* ---- keys ---- */ + +static uint32_t counted(pdf *st) { + uint32_t n = st->count ? st->count : 1; + st->count = 0; + return n; +} + +static void pan_by(pdf *st, int dir, uint32_t px) { + slot *s = slot_of(st, st->page); + geo g; + if (!s || !s->rgba || !fit_geo(s->w, s->h, st->vw, st->ph[st->page], st->fit, st->pan, &g)) return; + uint32_t over = s->w - g.sw; + if (!over || (dir < 0 && g.sx == 0) || (dir > 0 && g.sx >= over)) return; + uint64_t step = ((uint64_t)px * g.sw + g.dw - 1) / (g.dw ? g.dw : 1); + uint64_t norm = (step * 65535 + over - 1) / over; + norm = norm < 1 ? 1 : norm > 65535 ? 65535 : norm; + int v = (int)st->pan + dir * (int)norm; + st->pan = (uint16_t)(v < 0 ? 0 : v > 65535 ? 65535 : v); +} + +static void edge(pdf *st, int end) { + slot *s = slot_of(st, st->page); + geo g; + if (s && s->rgba && fit_geo(s->w, s->h, st->vw, st->ph[st->page], st->fit, st->pan, &g) && s->w > g.sw) st->pan = end ? 65535 : 0; +} + +/* Esc: the selection and the search go first; with neither, it leaves. */ +static int cancel(pdf *st) { + int had = st->nsel > 0 || st->query_len > 0; + drop_sel(st); + st->query_len = 0, st->reveal = 0; + drop_hits(st); + return had; +} + +static int key(void *v, const pa_key *k) { + pdf *st = v; + if (!st || !st->d) return 0; + uint32_t cp = k->cp, cell = st->view.cell_h ? st->view.cell_h : 16; + int ctrl = k->ctrl; + if (cp == 0x1b) return k->shift ? 0 : cancel(st); /* Shift-Esc: the editor's, leaving at once */ + if (cp > 0 && cp < 0x20 && cp != '\r' && cp != '\t') ctrl = 1, cp += 0x60; /* ^D as Ctrl-d */ + if (ctrl) { + uint32_t half = st->vh / 2 ? st->vh / 2 : 1, n = counted(st); + switch (cp) { + case 'd': scroll_by(st, (double)half * n); return 1; + case 'u': scroll_by(st, -(double)half * n); return 1; + case 'f': scroll_by(st, (double)st->vh * n); return 1; + case 'b': scroll_by(st, -(double)st->vh * n); return 1; + case 'e': scroll_by(st, cell); return 1; + case 'y': scroll_by(st, -(double)cell); return 1; + default: return 0; /* the editor's: windows, jumps */ + } + } + if (k->alt) return 0; + if (st->g) { + uint32_t n = st->count; + st->g = 0, st->count = 0; + uint32_t cell_n = cell * (n ? n : 1); + if (cp == 'g') go_page(st, n ? (int)n - 1 : 0); + else if (cp == 'e') go_page(st, st->pages - 1); + else if (cp == 'j') scroll_by(st, cell_n); + else if (cp == 'k') scroll_by(st, -(double)cell_n); + else if (cp == 'h' || cp == 's') edge(st, 0); + else if (cp == 'l') edge(st, 1); + return 1; + } + if (cp >= '0' && cp <= '9' && (cp != '0' || st->count)) { + st->count = st->count * 10 + (cp - '0'); + if (st->count > 1000000) st->count = 1000000; + return 1; + } + switch (cp) { + case ':': case ' ': case '/': case 'n': case 'N': case '\t': st->count = 0; return 0; /* the editor's */ + case 'g': st->g = 1; return 1; + case 'f': st->count = 0, api->exec("PdfSections", 11); return 1; + case 'G': { + uint32_t n = st->count; + st->count = 0; + go_page(st, n ? (int)n - 1 : st->pages - 1); + return 1; + } + case 'j': case PA_KEY_DOWN: scroll_by(st, (double)cell * counted(st)); return 1; + case 'k': case PA_KEY_UP: scroll_by(st, -(double)cell * counted(st)); return 1; + case PA_KEY_PAGE_DOWN: scroll_by(st, (double)st->vh * counted(st)); return 1; + case PA_KEY_PAGE_UP: scroll_by(st, -(double)st->vh * counted(st)); return 1; + case 'h': case PA_KEY_LEFT: pan_by(st, -1, st->view.cell_w * counted(st)); return 1; + case 'l': case PA_KEY_RIGHT: pan_by(st, 1, st->view.cell_w * counted(st)); return 1; + case '0': case '^': case PA_KEY_HOME: st->count = 0, edge(st, 0); return 1; + case '$': case PA_KEY_END: st->count = 0, edge(st, 1); return 1; + default: st->count = 0; return 1; /* the editing keys: nothing here */ + } +} + +/* ---- the mouse: wheel, hover, select, look and exec ---- */ + +static int mouse(void *v, const pa_mouse *m) { + pdf *st = v; + if (!st || !st->d) return 0; + uint32_t cell = st->view.cell_h ? st->view.cell_h : 16; + if (m->button == PA_WHEEL_UP || m->button == PA_WHEEL_DOWN) { + scroll_by(st, m->button == PA_WHEEL_UP ? -(double)cell : (double)cell); + return 1; + } + if (m->button == PA_WHEEL_LEFT || m->button == PA_WHEEL_RIGHT) { + if (st->fit) pan_by(st, m->button == PA_WHEEL_LEFT ? -1 : 1, st->view.cell_w * 4); + return 1; + } + if (m->action == PA_MOTION) { + if (m->col == 0xffff) { + hover_off(st); + return 1; + } + if (st->pressed || (st->hover_wait && m->col == st->hover_col && m->row == st->hover_row) || + (st->hover_page >= 0 && m->col == st->hover_col && m->row == st->hover_row)) return 1; + hover_off(st); + st->hover_col = m->col, st->hover_row = m->row, st->hover_wait = 1; + return 1; + } + int page = -1; + pardes_pdf_point pt; + if (m->action == PA_PRESS) { + hover_off(st); + if (st->pressed) { /* a chord: B1 and B2 copies, a PDF being nothing to cut */ + st->chorded = 1; + if (m->button == PA_MIDDLE && st->nsel) api->exec("ClipYank", 8); + return 1; + } + st->pressed = m->button + 1, st->chorded = 0, st->look_pending = 0; + if (m->button == PA_RIGHT) { + st->look_pending = 1, st->look_col = m->col, st->look_row = m->row; + return 1; + } + if (!point_at(st, m->col, m->row, 0, &page, &pt)) { + st->pressed = 0; + return 1; + } + st->press_page = page, st->anchor = st->head = pt; + if (m->button == PA_MIDDLE && !sel_contains(st, page, pt)) select_to(st, page, pt); + return 1; + } + if (m->action == PA_DRAG) { + if (!st->pressed || st->chorded) return 1; + if (st->look_pending) { + if (m->col == st->look_col && m->row == st->look_row) return 1; + st->look_pending = 0; + if (!point_at(st, st->look_col, st->look_row, 0, &page, &pt)) return 1; + st->press_page = page, st->anchor = st->head = pt; + } + page = st->press_page; + if (point_at(st, m->col, m->row, 1, &page, &pt) && (pt.x != st->head.x || pt.y != st->head.y)) select_to(st, page, pt); + return 1; + } + if (m->action != PA_RELEASE || !st->pressed) return 1; + int button = st->pressed - 1, chorded = st->chorded; + st->pressed = 0, st->chorded = 0; + if (chorded) return 1; + if (button == PA_RIGHT && st->look_pending) { + st->look_pending = 0; + probe pr; + if (!probe_at(st, st->look_col, st->look_row, &pr)) return 1; + if (pr.has_link) follow(st, &pr); + else if (pr.len) api->look(pr.text, pr.len); + unheap(pr.text); + return 1; + } + if (button == PA_LEFT) { + if (st->anchor.x == st->head.x && st->anchor.y == st->head.y) drop_sel(st); + return 1; + } + /* the selection, looked at (B3) or run (B2) */ + if (st->sel_len) (button == PA_RIGHT ? api->look : api->exec)(st->sel_text, st->sel_len); + return 1; +} + +/* ---- the body, places, search ---- */ + +static uint64_t body_len(void *v) { + uint32_t n = 0; + if (v && ((pdf *)v)->d) page_text(v, &n); + return n; +} + +static uint32_t body(void *v, uint64_t off, char *buf, uint32_t n) { + uint32_t len = 0; + if (!v || !((pdf *)v)->d) return 0; + const char *t = page_text(v, &len); + return pa_copy(t, len, off, buf, n); +} + +/* `text` as a number from `*i`, stopped at `end`: 0 when none is there. */ +static int number(const char *t, uint32_t *i, uint32_t end, uint64_t *out) { + uint32_t from = *i; + uint64_t v = 0; + while (*i < end && t[*i] >= '0' && t[*i] <= '9' && v < 100000000) v = v * 10 + (uint64_t)(t[(*i)++] - '0'); + *out = v; + return *i > from; +} + +static void missed(const char *fmt, uint64_t a, uint64_t b) { + char said[160]; + snprintf(said, sizeof said, fmt, (unsigned long long)a, (unsigned long long)b); + say(said, 1); +} + +/* The outline as rows `file.pdf:PAGE:N title` (N its place in the outline, + * from 1), indented by depth; an entry with nowhere to go takes its first + * child's that has, and an http(s) one is its URI. */ +static int usable(const pardes_pdf_outline_result *o, size_t i) { + const pardes_pdf_outline_item *it = &o->items[i]; + if (it->destination_kind == PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) return 1; + if (it->destination_kind != PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL || it->uri_len == 0 || it->uri_len > 256) return 0; + const char *u = (const char *)o->bytes + it->uri_offset; + if (strncmp(u, "http://", 7) && strncmp(u, "https://", 8)) return 0; + for (size_t k = 0; k < it->uri_len; k++) + if ((unsigned char)u[k] <= 0x20 || u[k] == 0x7f) return 0; + return 1; +} + +/* Entry `i`'s place: its own, else the first usable one below it. */ +static long resolve(const pardes_pdf_outline_result *o, size_t i) { + if (o->items[i].destination_kind != PARDES_PDF_OUTLINE_DESTINATION_NONE) return usable(o, i) ? (long)i : -1; + for (size_t k = i + 1; k < o->item_count && o->items[k].depth > o->items[i].depth; k++) + if (usable(o, k)) return (long)k; + return -1; +} + +static size_t clean_title(char *out, size_t cap, const char *t, size_t len, int present) { + if (!present) return (size_t)snprintf(out, cap, "[untitled]"); + size_t n = 0; + int wrote = 0, gap = 0; + for (size_t i = 0; i < len;) { + unsigned char c = (unsigned char)t[i]; + size_t k = c < 0x80 ? 1 : (c >> 5) == 6 ? 2 : (c >> 4) == 14 ? 3 : (c >> 3) == 30 ? 4 : 0; + uint32_t cp = 0; + int ok = k > 0 && i + k <= len; + if (ok) { + cp = k == 1 ? c : k == 2 ? c & 0x1f : k == 3 ? c & 0x0f : c & 0x07; + for (size_t j = 1; j < k && ok; j++) ok = ((unsigned char)t[i + j] >> 6) == 2, cp = cp << 6 | ((unsigned char)t[i + j] & 0x3f); + } + if (!ok) { + gap = wrote, i += k ? k : 1; + if (k && i > len) break; + continue; + } + if (cp <= 0x20 || cp == 0x7f || (cp >= 0x80 && cp <= 0x9f) || cp == 0x2028 || cp == 0x2029) gap = wrote; + else { + if (gap && n + 1 < cap) out[n++] = ' '; + for (size_t j = 0; j < k && n + 1 < cap; j++) out[n++] = t[i + j]; + wrote = 1, gap = 0; + } + i += k; + } + if (!wrote) return (size_t)snprintf(out, cap, "[empty title]"); + out[n] = 0; + return n; +} + +/* The outline, loaded (the caller drops it); 0 when it has none. */ +static int outline(pdf *st, pardes_pdf_outline_result *o) { + return pardes_pdf_load_outline(st->d->base, o) == PARDES_PDF_OK && o->item_count > 0; +} + +static void sections(pdf *st) { + pardes_pdf_outline_result o; + if (!outline(st, &o)) { + say("PdfSections: this PDF has no outline", 1); + return; + } + size_t cap = o.item_count * 300 + 1, n = 0; + char *rows = heap(cap); + for (size_t i = 0; rows && i < o.item_count; i++) { + long r = resolve(&o, i); + if (r < 0) continue; + const pardes_pdf_outline_item *it = &o.items[i], *to = &o.items[r]; + if (to->destination_kind == PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) + n += (size_t)snprintf(rows + n, cap - n, "%s:%d:%zu ", st->name, to->page + 1, i + 1); + else + n += (size_t)snprintf(rows + n, cap - n, "%.*s ", (int)to->uri_len, (const char *)o.bytes + to->uri_offset); + for (unsigned d = 0; d < it->depth && n + 2 < cap; d++) rows[n++] = ' ', rows[n++] = ' '; + char title[256]; + size_t tl = clean_title(title, sizeof title, (const char *)o.bytes + it->title_offset, it->title_len, it->title_present); + n += (size_t)snprintf(rows + n, cap - n, "%.*s\n", (int)tl, title); + } + pardes_pdf_drop_outline_result(st->d->base, o.handle); + if (rows && n) api->text("+PdfSections", 12, rows, (uint32_t)n); + else if (rows) say("PdfSections: this PDF has no outline", 1); + unheap(rows); +} + +/* A +PdfSections row's place: page P, section S, which must be on it. */ +static int section(pdf *st, uint64_t page, uint64_t ord) { + pardes_pdf_outline_result o; + char said[200]; + if (!outline(st, &o) || ord == 0 || ord > o.item_count || resolve(&o, ord - 1) < 0) { + if (o.handle) pardes_pdf_drop_outline_result(st->d->base, o.handle); + snprintf(said, sizeof said, "PdfSections: %s has no section %llu", st->name, (unsigned long long)ord); + say(said, 1); + return 0; + } + const pardes_pdf_outline_item to = o.items[resolve(&o, ord - 1)]; + char uri[260] = {0}; + if (to.destination_kind == PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL) memcpy(uri, (const char *)o.bytes + to.uri_offset, to.uri_len < 256 ? to.uri_len : 256); + pardes_pdf_drop_outline_result(st->d->base, o.handle); + if (to.destination_kind == PARDES_PDF_OUTLINE_DESTINATION_INTERNAL && (uint64_t)to.page + 1 != page) { + snprintf(said, sizeof said, "PdfSections: section %llu of %s is on page %d, not %llu", (unsigned long long)ord, st->name, to.page + 1, (unsigned long long)page); + say(said, 1); + return 0; + } + if (uri[0]) { + api->look(uri, (uint32_t)strlen(uri)); + return 1; + } + drop_sel(st); + to_page(st, to.page); + st->want_page = to.page, st->want_frac = 0; + st->want_x = to.has_x ? to.x : NAN, st->want_y = to.has_y ? to.y : NAN; + layout(st); + return 1; +} + +/* `P` (a page), `P:H` (hit H of the search there), `P:F` (F of the way down + * page P, a fraction: a jump, Recent, a Restore), or a +PdfSections row's + * `P:S`. */ +static int address(void *v, const char *t, uint32_t n) { + pdf *st = v; + if (!st || !st->d) return 0; + uint32_t i = 0; + int from_sections = n > 13 && !memcmp(t, "+PdfSections ", 13); + if (from_sections) i = 13; + else if (n > 0 && t[0] == '+') { + while (i < n && t[i] != ' ') i++; + i += i < n; + } + if (i < n && t[i] == ':') i++; + uint64_t page = 0, second = 0; + int frac = 0; + double f = 0; + if (!number(t, &i, n, &page)) goto none; + if (i < n && t[i] == ':') { + i++; + uint32_t at = i; + if (!number(t, &i, n, &second)) goto none; + if (i < n && t[i] == '.') { + char tmp[32]; + uint32_t len = n - at < 31 ? n - at : 31; + memcpy(tmp, t + at, len), tmp[len] = 0; + f = strtod(tmp, 0), frac = 1, i = n; + } + } + if (i < n && t[i] == ' ') i = n; /* where's window, for jumps */ + if (i != n) goto none; + if (from_sections) return section(st, page, second); + if (frac) { + int p = page > 0 ? (int)page - 1 : 0; + p = p < st->pages ? p : st->pages - 1; + drop_sel(st); + to_page(st, p); + st->want_page = p, st->want_frac = f, st->want_x = st->want_y = NAN; + if (st->laid) layout(st); + return 1; + } + if (page == 0 || page > (uint64_t)st->pages) { + missed("has no page %llu", page, 0); + return 0; + } + if (second && (!st->query_len || search_page(st, (int)page - 1, 0) < second)) { + missed("has no search hit %llu on page %llu", second, page); + return 0; + } + drop_sel(st); + go_page(st, (int)page - 1); + if (second) st->hit = (uint32_t)second - 1, st->reveal = 1; + return 1; +none: + say("has no text to address; its address is a page, :N", 1); + return 0; +} + +/* `v` in decimal, at least `w` digits, at `b`: their count. */ +static uint32_t digits(char *b, uint64_t v, uint32_t w) { + char t[20]; + uint32_t n = 0; + do t[n++] = (char)('0' + v % 10), v /= 10; + while (v || n < w); + for (uint32_t i = 0; i < n; i++) b[i] = t[n - 1 - i]; + return n; +} + +/* `P:F S`: its page, how far down it, and the window's height in pages + * (two places within it are one visit of the jumps, as a text's lines + * within a body). Formatted by hand: a jump asks every step. */ +static uint32_t where(void *v, char *buf, uint32_t n) { + pdf *st = v; + if (!st || !st->d) return 0; + double frac = st->laid && st->ph[st->page] ? (st->top - (double)st->y[st->page]) / st->ph[st->page] : 0; + uint64_t f6 = (uint64_t)llround((frac < 0 ? 0 : frac > 1 ? 1 : frac) * 1e6), w3 = (uint64_t)llround(st->laid && st->ph[st->page] ? (double)st->vh / st->ph[st->page] * 1e3 : 0); + char t[64]; + uint32_t k = digits(t, (uint64_t)st->page + 1, 1); + t[k++] = ':', k += digits(t + k, f6 / 1000000, 1), t[k++] = '.', k += digits(t + k, f6 % 1000000, 6); + t[k++] = ' ', k += digits(t + k, w3 / 1000, 1), t[k++] = '.', k += digits(t + k, w3 % 1000, 3); + if (k > n) return 0; + memcpy(buf, t, k); + return k; +} + +/* `/`: every hit, `file.pdf:P:H pattern` a row, at most MAX_HITS. */ +static uint32_t search(void *v, const char *pat, uint32_t n, char *buf, uint32_t cap) { + pdf *st = v; + if (!st || !st->d || n == 0 || n > 255) return 0; + if (st->query_len != n || memcmp(st->query, pat, n)) { + memcpy(st->query, pat, n), st->query_len = n; + drop_hits(st); + st->hit = 0, st->reveal = 1; + } + uint32_t shown = n > 200 ? 200 : n, len = 0, rows = 0; + while (shown > 0 && shown < n && ((unsigned char)pat[shown] & 0xc0) == 0x80) shown--; + for (int p = 0; p < st->pages && rows < MAX_HITS; p++) { + uint32_t hits = search_page(st, p, 0); + for (uint32_t h = 0; h < hits && rows < MAX_HITS; h++, rows++) { + int k = snprintf(buf + len, cap - len, "%s:%d:%u %.*s\n", st->name, p + 1, h + 1, (int)shown, pat); + if (k < 0 || (uint32_t)k >= cap - len) return len; + len += (uint32_t)k; + } + } + return len; +} + +/* ---- words ---- */ + +static int word_arg(const char *line, uint32_t n, const char *word, const char *const *names, int count, int now, char *reply, uint32_t cap) { + uint32_t i = (uint32_t)strlen(word); + while (i < n && (line[i] == ' ' || line[i] == '\t')) i++; + uint32_t end = n; + while (end > i && (line[end - 1] == ' ' || line[end - 1] == '\t' || line[end - 1] == '\n')) end--; + if (i == end) return (now + 1) % count; + for (int k = 0; k < count; k++) + if (strlen(names[k]) == end - i && !memcmp(line + i, names[k], end - i)) return k; + snprintf(reply, cap, "invalid argument: %s takes %s, not \"%.*s\"", word, count == 2 ? "width or height" : "disabled, filtered or full", (int)(end - i > 32 ? 32 : end - i), line + i); + return -1; +} + +static int ctl(void *v, const char *line, uint32_t n, char *reply, uint32_t cap) { + pdf *st = v; + static const char *const fits[] = {"width", "height"}; + if (!st || !st->d) return 1; + if (n >= 11 && !memcmp(line, "PdfSections", 11)) { + sections(st); + return PA_OK; + } + if (n >= 6 && !memcmp(line, "PdfFit", 6)) { + int f = word_arg(line, n, "PdfFit", fits, 2, st->fit, reply, cap); + if (f < 0) return 1; + if (f != st->fit) st->fit = f, st->pan = 0, go_page(st, st->page), st->reveal = st->query_len > 0; + return PA_OK; + } + if (n >= 7 && !memcmp(line, "PdfTint", 7)) { + int t = word_arg(line, n, "PdfTint", tint_names, 3, st->tint, reply, cap); + if (t < 0) return 1; + st->tint = t; + return PA_OK; + } + return 1; +} + +static uint32_t ctl_read(void *v, char *buf, uint32_t n) { + pdf *st = v; + if (!st) return 0; + int k = snprintf(buf, n, "fit:%s tint:%s", st->fit ? "height" : "width", tint_names[st->tint]); + return k > 0 && (uint32_t)k < n ? (uint32_t)k : 0; +} + +/* ---- the record: its fit, tint and place, then the file's bytes ---- */ + +typedef struct record { + uint32_t version, fit, tint, page; + double frac; +} record; + +static uint32_t dump(void *v, uint8_t *buf, uint32_t n) { + pdf *st = v; + if (!st || !st->d) return 0; + size_t len = 0; + const unsigned char *bytes = pardes_pdf_bytes(st->d->base, &len); + if (!bytes || len > 0xffffffffu - sizeof(record)) return 0; + uint32_t total = (uint32_t)(sizeof(record) + len); + if (total > n) return total; + record r = {RECORD_VERSION, (uint32_t)st->fit, (uint32_t)st->tint, (uint32_t)st->page, 0}; + if (st->laid && st->ph[st->page]) r.frac = (st->top - (double)st->y[st->page]) / st->ph[st->page]; + memcpy(buf, &r, sizeof r); + memcpy(buf + sizeof r, bytes, len); + return total; +} + +/* On a state open made from its file (a Restore's, from nothing): the + * document from the record. On one open made from the file as it is now + * (it changed on disk): only its fit, tint and place. */ +static int load(void *v, const uint8_t *buf, uint32_t n, uint32_t version) { + pdf *st = v; + record r; + (void)version; + if (!st || n < sizeof r) return 1; + memcpy(&r, buf, sizeof r); + if (r.version != RECORD_VERSION || r.fit > 1 || r.tint > 2) return 1; + if (!st->d && !reopen_bytes(st, buf + sizeof r, n - sizeof r)) return 1; + st->fit = (int)r.fit, st->tint = (int)r.tint; + st->page = (int)(r.page < (uint32_t)st->pages ? r.page : (uint32_t)st->pages - 1); + st->want_page = st->page, st->want_frac = r.frac; + return PA_OK; +} + +static const pa_word words[] = { + PA_WORD("PdfSections", "ts", PA_ARG_NONE, 0, "list the PDF's sections in a pane, each a place to go"), + PA_WORD("PdfTint", "ti", PA_ARG_OPTIONAL, 0, "tint the PDF to the theme or show it as printed (disabled|filtered|full)"), + PA_WORD("PdfFit", "tz", PA_ARG_OPTIONAL, 0, "fit the PDF's pages to the pane's width or height (width|height)"), +}; + +const pa_ops pardes_addon = { + .head = PA_ADDON("pdf", 1, ".pdf", words, 3), + .init = init, .open = open, .close = close, .tick = tick, .paint = paint, .key = key, .mouse = mouse, + .body_len = body_len, .body = body, .address = address, .where = where, .ctl = ctl, .ctl_read = ctl_read, + .job_run = job_run, .job_done = job_done, .dump = dump, .load = load, .search = search, +}; diff --git a/addons/pdf/pdf.out b/addons/pdf/pdf.out new file mode 100644 index 00000000..08d24595 --- /dev/null +++ b/addons/pdf/pdf.out @@ -0,0 +1,129 @@ +> open docs/design.pdf +window 78x10 +tag [1/16] +| +| +| +| +| +| +| +| +| +| +> size 60 20 +window 58x7 +tag [1/16] +| +| +| +| +| +| +| +placement 794x1123 src 0,0 794x192 over 0,0 58x7 key 3017bc3ce49f9593 at 0,0 464x112 +> key j +tag [1/16] +| +| +| +| +| +| +| +placement 794x1123 src 0,27 794x193 over 0,0 58x7 key 3017bc3ce49f9593 at 0,0 464x112 +> key 3j +tag [1/16] +| +| +| +| +| +| +| +placement 794x1123 src 0,109 794x193 over 0,0 58x7 key 3017bc3ce49f9593 at 0,0 464x112 +> key G +tag [16/16] +| +| +| +| +| +| +| +placement 794x1123 src 0,0 794x192 over 0,0 58x7 key ad6b5307dead8475 at 0,0 464x112 +> key gg +tag [1/16] +| +| +| +| +| +| +| +placement 794x1123 src 0,0 794x192 over 0,0 58x7 key 107dd9d0f0ee5746 at 0,0 464x112 +> key 3gg +tag [3/16] +| +| +| +| +| +| +| +placement 794x1123 src 0,0 794x192 over 0,0 58x7 key e6b017c42b5b77eb at 0,0 464x112 +> PdfFit +tag [3/16] +| +| +| +| +| +| +| +placement 794x1123 src 0,0 794x1123 over 0,0 58x7 key e6b017c42b5b77eb at 192,0 79x112 +> ctl +=fit:height tint:filtered +> PdfTint full +tag [3/16] +| +| +| +| +| +| +| +placement 794x1123 src 0,0 794x1123 over 0,0 58x7 key e6b017c42b5b77eb at 192,0 79x112 +> ctl +=fit:height tint:full +> PdfTint loud +tag [3/16] +|ent: PdfTint takes disabled, filtered or full, not "loud" +| +| +| +| +| +| +placement 794x1123 src 0,0 794x963 over 0,1 58x6 key e6b017c42b5b77eb at 192,0 79x96 +> key +tag [3/16] +|ent: PdfTint takes disabled, filtered or full, not "loud" +| Last +| +| +| +| +| +placement 794x1123 src 0,0 794x1123 over 0,2 58x5 key 3f51689292296629 at 204,0 56x80 +> dump +dump 636117 bytes +tag [3/16] +| +| +| +| +| +| +| +| diff --git a/addons/pdf/pdf.script b/addons/pdf/pdf.script new file mode 100644 index 00000000..dbdbea33 --- /dev/null +++ b/addons/pdf/pdf.script @@ -0,0 +1,15 @@ +# pardes --addon-test pdf.so addons/pdf/pdf.script | diff addons/pdf/pdf.out - +open docs/design.pdf +size 60 20 +key j +key 3j +key G +key gg +key 3gg +PdfFit +ctl +PdfTint full +ctl +PdfTint loud +key +dump diff --git a/addons/pdf/pdf_bridge.c b/addons/pdf/pdf_bridge.c new file mode 100644 index 00000000..3b326655 --- /dev/null +++ b/addons/pdf/pdf_bridge.c @@ -0,0 +1,1802 @@ +#include "pdf_bridge.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#define PARDES_PDF_INITIAL_RESULT_QUADS 64 + +struct pardes_pdf_document { + pardes_pdf_allocator allocator; + fz_alloc_context mupdf_allocator; + int uses_allocator; + + fz_context *ctx; + fz_document *doc; + int page_count; + + /* + * Threads (pardes_pdf_lane_clone). A base document's context is made + * with MuPDF's locks, so it can be cloned; it owns the mutexes and the + * fz_buffer every lane opens its own fz_document from. A lane has + * `base` set and owns neither. + */ + pthread_mutex_t mutexes[FZ_LOCK_MAX]; + fz_locks_context locks; + fz_buffer *buffer; + pardes_pdf_document *base; + fz_cookie *cookie; + + /* One UI thread owns a document. Page switches invalidate this cache. */ + int cached_page_number; + fz_page *cached_page; + fz_stext_page *cached_text; + fz_display_list *cached_display_list; + fz_rect cached_bounds; + fz_link *cached_links; + int cached_links_loaded; + + /* Promote only a page which is rendered twice without changing pages. */ + int display_list_candidate_page_number; +}; + +_Static_assert(sizeof(pardes_pdf_cookie) == sizeof(fz_cookie) && + offsetof(pardes_pdf_cookie, abort) == offsetof(fz_cookie, abort) && + offsetof(pardes_pdf_cookie, progress_max) == offsetof(fz_cookie, progress_max) && + offsetof(pardes_pdf_cookie, incomplete) == offsetof(fz_cookie, incomplete), + "pardes_pdf_cookie must mirror fz_cookie"); + +static void +pardes_pdf_lock(void *user, int lock) +{ + pthread_mutex_lock(&((pthread_mutex_t *)user)[lock]); +} + +static void +pardes_pdf_unlock(void *user, int lock) +{ + pthread_mutex_unlock(&((pthread_mutex_t *)user)[lock]); +} + +static pardes_pdf_allocator pardes_pdf_global_allocator; +static int pardes_pdf_allocator_installed; +static _Atomic size_t pardes_pdf_active_documents; +static atomic_flag pardes_pdf_allocator_lock = ATOMIC_FLAG_INIT; + +static void +pardes_pdf_lock_allocator(void) +{ + while (atomic_flag_test_and_set_explicit( + &pardes_pdf_allocator_lock, memory_order_acquire)) + ; +} + +static void +pardes_pdf_unlock_allocator(void) +{ + atomic_flag_clear_explicit( + &pardes_pdf_allocator_lock, memory_order_release); +} + + +int +pardes_pdf_set_allocator(const pardes_pdf_allocator *allocator) +{ + int status = PARDES_PDF_OK; + + if (allocator != NULL && + (allocator->alloc == NULL || allocator->realloc == NULL || + allocator->free == NULL)) + return PARDES_PDF_ERROR; + + pardes_pdf_lock_allocator(); + if (atomic_load(&pardes_pdf_active_documents) != 0) { + status = PARDES_PDF_ERROR; + } else if (allocator == NULL) { + memset(&pardes_pdf_global_allocator, 0, + sizeof(pardes_pdf_global_allocator)); + pardes_pdf_allocator_installed = 0; + } else { + pardes_pdf_global_allocator = *allocator; + pardes_pdf_allocator_installed = 1; + } + pardes_pdf_unlock_allocator(); + return status; +} + +static pardes_pdf_document * +pardes_pdf_allocate_document(void) +{ + pardes_pdf_document *document; + pardes_pdf_allocator allocator; + int uses_allocator; + + pardes_pdf_lock_allocator(); + uses_allocator = pardes_pdf_allocator_installed; + allocator = pardes_pdf_global_allocator; + atomic_fetch_add(&pardes_pdf_active_documents, 1); + pardes_pdf_unlock_allocator(); + + if (uses_allocator) { + document = (pardes_pdf_document *)allocator.alloc( + allocator.user, sizeof(*document)); + } else { + document = (pardes_pdf_document *)calloc(1, sizeof(*document)); + } + if (document == NULL) { + atomic_fetch_sub(&pardes_pdf_active_documents, 1); + return NULL; + } + if (!uses_allocator) + return document; + + memset(document, 0, sizeof(*document)); + document->allocator = allocator; + document->uses_allocator = 1; + document->mupdf_allocator.user = allocator.user; + document->mupdf_allocator.malloc = allocator.alloc; + document->mupdf_allocator.realloc = allocator.realloc; + document->mupdf_allocator.free = allocator.free; + return document; +} + +static void +pardes_pdf_free_document(pardes_pdf_document *document) +{ + if (document->uses_allocator) + document->allocator.free(document->allocator.user, document); + else + free(document); +} + +static void +pardes_pdf_drop_cached_page(pardes_pdf_document *document) +{ + fz_drop_link(document->ctx, document->cached_links); + fz_drop_display_list(document->ctx, document->cached_display_list); + fz_drop_stext_page(document->ctx, document->cached_text); + fz_drop_page(document->ctx, document->cached_page); + document->cached_display_list = NULL; + document->cached_text = NULL; + document->cached_page = NULL; + document->cached_links = NULL; + document->cached_links_loaded = 0; + document->cached_page_number = -1; + document->display_list_candidate_page_number = -1; +} + +static int +pardes_pdf_valid_bounds(fz_rect bounds) +{ + return isfinite(bounds.x0) && isfinite(bounds.y0) && + isfinite(bounds.x1) && isfinite(bounds.y1) && + bounds.x1 > bounds.x0 && bounds.y1 > bounds.y0; +} + +/* + * Load into temporaries first, then replace the cache in one non-throwing + * commit. Thus a failed page/text load leaves the previous cached page valid. + */ +static void +pardes_pdf_cache_page( + pardes_pdf_document *document, + int page_number, + int require_text) +{ + fz_context *ctx = document->ctx; + fz_page *page = NULL; + fz_stext_page *text = NULL; + fz_rect bounds; + fz_stext_options options = {0}; + options.flags = FZ_STEXT_DEHYPHENATE; + + if (document->cached_page_number == page_number) { + if (require_text && document->cached_text == NULL) + document->cached_text = fz_new_stext_page_from_page( + ctx, document->cached_page, &options); + return; + } + + fz_var(page); + fz_var(text); + fz_try(ctx) + { + page = fz_load_page(ctx, document->doc, page_number); + bounds = fz_bound_page(ctx, page); + if (!pardes_pdf_valid_bounds(bounds)) + fz_throw(ctx, FZ_ERROR_FORMAT, "PDF page has empty bounds"); + if (require_text) + text = fz_new_stext_page_from_page(ctx, page, &options); + } + fz_catch(ctx) + { + fz_drop_stext_page(ctx, text); + fz_drop_page(ctx, page); + fz_rethrow(ctx); + } + + pardes_pdf_drop_cached_page(document); + document->cached_page_number = page_number; + document->cached_page = page; + document->cached_text = text; + document->cached_bounds = bounds; +} + +/* + * Build only after one successful direct render of the still-cached page. + * This keeps cold renders and sequential document passes on their original + * path instead of recording a list which the next page would immediately + * evict. The temporary list is committed only after its device has closed; + * any partially recorded list is dropped before the exception propagates. + */ +static void +pardes_pdf_cache_display_list(pardes_pdf_document *document) +{ + fz_context *ctx = document->ctx; + fz_display_list *list = NULL; + fz_device *device = NULL; + + if (document->cached_display_list != NULL) + return; + + fz_var(list); + fz_var(device); + fz_try(ctx) + { + list = fz_new_display_list(ctx, document->cached_bounds); + device = fz_new_list_device(ctx, list); + fz_run_page(ctx, document->cached_page, device, fz_identity, NULL); + fz_close_device(ctx, device); + } + fz_always(ctx) + { + fz_drop_device(ctx, device); + } + fz_catch(ctx) + { + fz_drop_display_list(ctx, list); + fz_rethrow(ctx); + } + + document->cached_display_list = list; +} + +static float +pardes_pdf_clamp_unit(float value) +{ + if (value < 0.0f) + return 0.0f; + if (value > 1.0f) + return 1.0f; + return value; +} + +static int +pardes_pdf_valid_point(pardes_pdf_point point) +{ + return isfinite(point.x) && isfinite(point.y); +} + +static fz_point +pardes_pdf_point_to_page(pardes_pdf_document *document, pardes_pdf_point point) +{ + fz_rect bounds = document->cached_bounds; + float x = pardes_pdf_clamp_unit(point.x); + float y = pardes_pdf_clamp_unit(point.y); + return fz_make_point( + bounds.x0 + x * (bounds.x1 - bounds.x0), + bounds.y0 + y * (bounds.y1 - bounds.y0)); +} + +static pardes_pdf_point +pardes_pdf_point_from_page(pardes_pdf_document *document, fz_point point) +{ + fz_rect bounds = document->cached_bounds; + pardes_pdf_point result; + result.x = pardes_pdf_clamp_unit( + (point.x - bounds.x0) / (bounds.x1 - bounds.x0)); + result.y = pardes_pdf_clamp_unit( + (point.y - bounds.y0) / (bounds.y1 - bounds.y0)); + return result; +} + +static pardes_pdf_quad +pardes_pdf_quad_from_page(pardes_pdf_document *document, fz_quad quad) +{ + pardes_pdf_quad result; + result.ul = pardes_pdf_point_from_page(document, quad.ul); + result.ur = pardes_pdf_point_from_page(document, quad.ur); + result.ll = pardes_pdf_point_from_page(document, quad.ll); + result.lr = pardes_pdf_point_from_page(document, quad.lr); + return result; +} + +static int +pardes_pdf_valid_quad(pardes_pdf_quad quad) +{ + return pardes_pdf_valid_point(quad.ul) && + pardes_pdf_valid_point(quad.ur) && + pardes_pdf_valid_point(quad.ll) && + pardes_pdf_valid_point(quad.lr); +} + +static fz_quad +pardes_pdf_quad_to_page(pardes_pdf_document *document, pardes_pdf_quad quad) +{ + fz_quad result; + result.ul = pardes_pdf_point_to_page(document, quad.ul); + result.ur = pardes_pdf_point_to_page(document, quad.ur); + result.ll = pardes_pdf_point_to_page(document, quad.ll); + result.lr = pardes_pdf_point_to_page(document, quad.lr); + return result; +} + +static size_t +pardes_pdf_grown_capacity(size_t current, size_t needed, size_t maximum) +{ + size_t capacity = current == 0 ? PARDES_PDF_INITIAL_RESULT_QUADS : current; + while (capacity < needed) { + if (capacity > maximum / 2) { + capacity = maximum; + break; + } + capacity *= 2; + } + return capacity; +} + +/* + * MuPDF's first page lookup loads a map of EVERY page object (the page tree + * flattened, each page's dictionary parsed out of its object stream): the + * SDM's 5363 took 735 ms in Debug, the first page's size alone. Walking the + * tree by its /Count for each lookup loads only the nodes on the way. + */ +static void +pardes_pdf_walk_page_tree(fz_context *ctx, fz_document *doc) +{ + pdf_document *pdf = pdf_specifics(ctx, doc); + if (pdf != NULL) + pdf_set_page_tree_cache(ctx, pdf, 0); +} + +pardes_pdf_document * +pardes_pdf_open_memory(const unsigned char *bytes, size_t length, int *page_count) +{ + pardes_pdf_document *state; + fz_context *ctx; + fz_document *doc = NULL; + fz_buffer *buffer = NULL; + fz_stream *stream = NULL; + int pages = 0; + + if (bytes == NULL || page_count == NULL) + return NULL; + + state = pardes_pdf_allocate_document(); + if (state == NULL) + return NULL; + state->cached_page_number = -1; + state->display_list_candidate_page_number = -1; + for (int i = 0; i < FZ_LOCK_MAX; ++i) + pthread_mutex_init(&state->mutexes[i], NULL); + state->locks.user = state->mutexes; + state->locks.lock = pardes_pdf_lock; + state->locks.unlock = pardes_pdf_unlock; + + ctx = fz_new_context( + state->uses_allocator ? &state->mupdf_allocator : NULL, + &state->locks, + PARDES_PDF_STORE_LIMIT_BYTES); + if (ctx == NULL) { + for (int i = 0; i < FZ_LOCK_MAX; ++i) + pthread_mutex_destroy(&state->mutexes[i]); + pardes_pdf_free_document(state); + atomic_fetch_sub(&pardes_pdf_active_documents, 1); + return NULL; + } + + fz_var(doc); + fz_var(buffer); + fz_var(stream); + fz_try(ctx) + { + fz_register_document_handlers(ctx); + buffer = fz_new_buffer_from_copied_data(ctx, bytes, length); + stream = fz_open_buffer(ctx, buffer); + doc = fz_open_document_with_stream(ctx, "application/pdf", stream); + pardes_pdf_walk_page_tree(ctx, doc); + pages = fz_count_pages(ctx, doc); + if (pages < 1) + fz_throw(ctx, FZ_ERROR_FORMAT, "PDF has no pages"); + } + fz_always(ctx) + { + fz_drop_stream(ctx, stream); + } + fz_catch(ctx) + { + fz_report_error(ctx); + fz_drop_document(ctx, doc); + fz_drop_buffer(ctx, buffer); + fz_drop_context(ctx); + for (int i = 0; i < FZ_LOCK_MAX; ++i) + pthread_mutex_destroy(&state->mutexes[i]); + pardes_pdf_free_document(state); + atomic_fetch_sub(&pardes_pdf_active_documents, 1); + return NULL; + } + + state->ctx = ctx; + state->doc = doc; + state->buffer = buffer; + state->page_count = pages; + *page_count = pages; + return state; +} + +void +pardes_pdf_close(pardes_pdf_document *document) +{ + if (document == NULL) + return; + pardes_pdf_drop_cached_page(document); + fz_drop_document(document->ctx, document->doc); + if (document->base == NULL) + fz_drop_buffer(document->ctx, document->buffer); + fz_drop_context(document->ctx); + if (document->base == NULL) + for (int i = 0; i < FZ_LOCK_MAX; ++i) + pthread_mutex_destroy(&document->mutexes[i]); + pardes_pdf_free_document(document); + atomic_fetch_sub(&pardes_pdf_active_documents, 1); +} + +const unsigned char * +pardes_pdf_bytes(pardes_pdf_document *document, size_t *length) +{ + unsigned char *data = NULL; + pardes_pdf_document *owner = document != NULL && document->base != NULL ? document->base : document; + + *length = 0; + if (owner == NULL || owner->buffer == NULL) + return NULL; + *length = fz_buffer_storage(owner->ctx, owner->buffer, &data); + return data; +} + +pardes_pdf_document * +pardes_pdf_lane_clone(pardes_pdf_document *base) +{ + pardes_pdf_document *lane; + + if (base == NULL || base->base != NULL) + return NULL; + lane = pardes_pdf_allocate_document(); + if (lane == NULL) + return NULL; + lane->ctx = fz_clone_context(base->ctx); + if (lane->ctx == NULL) { + pardes_pdf_free_document(lane); + atomic_fetch_sub(&pardes_pdf_active_documents, 1); + return NULL; + } + lane->base = base; + lane->page_count = base->page_count; + lane->cached_page_number = -1; + lane->display_list_candidate_page_number = -1; + return lane; +} + +/* + * The lane's own document, from the base's bytes: parsed again (the xref, + * the page tree), never shared, so the lane's thread is the only one in it. + * The fz_buffer's count is kept under the shared alloc lock. + */ +int +pardes_pdf_lane_open(pardes_pdf_document *lane) +{ + fz_context *ctx; + fz_stream *stream = NULL; + fz_document *doc = NULL; + + if (lane == NULL || lane->base == NULL) + return PARDES_PDF_ERROR; + if (lane->doc != NULL) + return PARDES_PDF_OK; + ctx = lane->ctx; + fz_var(stream); + fz_var(doc); + fz_try(ctx) + { + stream = fz_open_buffer(ctx, lane->base->buffer); + doc = fz_open_document_with_stream(ctx, "application/pdf", stream); + pardes_pdf_walk_page_tree(ctx, doc); + if (fz_count_pages(ctx, doc) != lane->page_count) + fz_throw(ctx, FZ_ERROR_FORMAT, "PDF lane counts other pages"); + } + fz_always(ctx) + fz_drop_stream(ctx, stream); + fz_catch(ctx) + { + fz_report_error(ctx); + fz_drop_document(ctx, doc); + return PARDES_PDF_ERROR; + } + lane->doc = doc; + return PARDES_PDF_OK; +} + +void +pardes_pdf_set_cookie(pardes_pdf_document *document, pardes_pdf_cookie *cookie) +{ + if (document != NULL) + document->cookie = (fz_cookie *)cookie; +} + +/* + * A page's SIZE, without building a page. + * + * fz_bound_page(fz_load_page(n)) is the obvious spelling and it is what this + * used to do, but fz_load_page builds a whole pdf_page: it resolves the page + * dictionary, then loads and parses every link annotation on it. Laying out a + * 5363-page manual's strip asks for 5363 sizes, and profiling an open showed + * pdf_load_link_annots alone at 29% of the run — parsing links for pages + * nobody has looked at yet, to answer a question about their height. + * + * The page OBJECT answers it directly, and identically: fz_bound_page on a PDF + * is pdf_bound_page(FZ_CROP_BOX), which is pdf_page_obj_transform_box on + * page->obj followed by fz_transform_rect — exactly the two calls below, from + * exactly the same object. Non-PDF documents (cbz, xps, svg) have no page + * objects and keep the loading path. + */ +int +pardes_pdf_get_page_size( + pardes_pdf_document *document, + int page_number, + pardes_pdf_page_size *out) +{ + fz_context *ctx; + fz_rect bounds; + pdf_document *pdf; + + if (document == NULL || out == NULL || page_number < 0 || + page_number >= document->page_count) + return PARDES_PDF_ERROR; + + memset(out, 0, sizeof(*out)); + ctx = document->ctx; + fz_try(ctx) + { + pdf = pdf_specifics(ctx, document->doc); + if (pdf != NULL) { + fz_matrix page_ctm; + fz_rect cropbox; + pdf_obj *page_obj = pdf_lookup_page_obj(ctx, pdf, page_number); + pdf_page_obj_transform_box(ctx, page_obj, &cropbox, &page_ctm, + FZ_CROP_BOX); + bounds = fz_transform_rect(cropbox, page_ctm); + } else { + pardes_pdf_cache_page(document, page_number, 0); + bounds = document->cached_bounds; + } + out->width = bounds.x1 - bounds.x0; + out->height = bounds.y1 - bounds.y0; + if (!(out->width > 0.0f) || !(out->height > 0.0f)) + fz_throw(ctx, FZ_ERROR_FORMAT, "PDF page has empty bounds"); + } + fz_catch(ctx) + { + fz_report_error(ctx); + memset(out, 0, sizeof(*out)); + return PARDES_PDF_ERROR; + } + return PARDES_PDF_OK; +} + +/* Every size in range; zero minimums and display sizes are none. */ +static int +pardes_pdf_request_ok(const pardes_pdf_request *request) +{ + return request != NULL && request->dpi >= 1 && + request->minimum_width >= 0 && request->minimum_height >= 0 && + request->max_dimension >= 1 && + request->display_width >= 0 && request->display_height >= 0; +} + +static void +pardes_pdf_render_geometry( + pardes_pdf_document *document, + int page_number, + const pardes_pdf_request *request, + fz_matrix *ctm_out, + fz_irect *bbox_out) +{ + fz_rect transformed; + fz_rect bounds; + float page_width; + float page_height; + float scale; + float shown = 0.0f; + + pardes_pdf_cache_page(document, page_number, 0); + bounds = document->cached_bounds; + page_width = bounds.x1 - bounds.x0; + page_height = bounds.y1 - bounds.y0; + if (!(page_width > 0.0f) || !(page_height > 0.0f)) + fz_throw(document->ctx, FZ_ERROR_FORMAT, "PDF page has empty bounds"); + scale = (float)request->dpi / 72.0f; + if (request->minimum_width > 0) + scale = fmaxf(scale, (float)request->minimum_width / page_width); + if (request->minimum_height > 0) + scale = fmaxf(scale, (float)request->minimum_height / page_height); + /* + * A row of the raster is never longer than max_dimension: every band of + * the page carries whole rows. The height is held to it too, as the + * budget of one whole-page raster, but never below the scale the page is + * shown at: a page taller than that (a poster, a long web capture) is + * drawn in bands at the display's own resolution (pdf_view.zig) instead + * of being squeezed into max_dimension rows and blown up again, blurred. + */ + if (page_width * scale > (float)request->max_dimension) + scale = (float)request->max_dimension / page_width; + if (request->display_width > 0) + shown = fmaxf(shown, (float)request->display_width / page_width); + if (request->display_height > 0) + shown = fmaxf(shown, (float)request->display_height / page_height); + if (page_height * scale > (float)request->max_dimension) + scale = fminf(scale, fmaxf((float)request->max_dimension / page_height, shown)); + if (page_height * scale > (float)PARDES_PDF_MAX_RASTER_ROWS) + scale = (float)PARDES_PDF_MAX_RASTER_ROWS / page_height; + + /* + * Keep this identical to fz_new_pixmap_from_page/display_list: transform + * non-zero crop boxes to the origin, transform the bounds, then round the + * complete rectangle once. The same CTM also aligns highlight geometry. + */ + *ctm_out = fz_transform_page(bounds, scale * 72.0f, 0.0f); + transformed = fz_transform_rect(bounds, *ctm_out); + *bbox_out = fz_round_rect(transformed); + if (fz_irect_width(*bbox_out) < 1 || fz_irect_height(*bbox_out) < 1) + fz_throw(document->ctx, FZ_ERROR_FORMAT, "PDF page rendered empty"); +} + +int +pardes_pdf_measure_render( + pardes_pdf_document *document, + int page_number, + const pardes_pdf_request *request, + pardes_pdf_raster_layout *out) +{ + fz_context *ctx; + fz_matrix ctm; + fz_irect bbox; + int width = 0; + int height = 0; + int stride = 0; + size_t samples_len = 0; + + if (out == NULL) + return PARDES_PDF_ERROR; + memset(out, 0, sizeof(*out)); + if (document == NULL || page_number < 0 || + page_number >= document->page_count || !pardes_pdf_request_ok(request)) + return PARDES_PDF_ERROR; + + ctx = document->ctx; + fz_try(ctx) + { + pardes_pdf_render_geometry(document, page_number, request, &ctm, &bbox); + width = fz_irect_width(bbox); + height = fz_irect_height(bbox); + if (width > INT_MAX / 4) + fz_throw(ctx, FZ_ERROR_LIMIT, "PDF raster row is too large"); + stride = width * 4; + if ((size_t)height > SIZE_MAX / (size_t)stride) + fz_throw(ctx, FZ_ERROR_LIMIT, "PDF raster is too large"); + samples_len = (size_t)stride * (size_t)height; + } + fz_catch(ctx) + { + fz_report_error(ctx); + memset(out, 0, sizeof(*out)); + return PARDES_PDF_ERROR; + } + + out->width = width; + out->height = height; + out->stride = stride; + out->samples_len = samples_len; + return PARDES_PDF_OK; +} + +/* The highlight pass of a render: fills over whatever the pixmap holds. */ +static void +pardes_pdf_fill_highlights(fz_context *ctx, pardes_pdf_document *document, + fz_device *device, const pardes_pdf_highlight *highlights, size_t highlight_count) +{ + fz_path *path = NULL; + size_t i; + + fz_var(path); + fz_try(ctx) + { + for (i = 0; i < highlight_count; ++i) { + fz_quad quad; + float color[3]; + float alpha; + + if (!pardes_pdf_valid_quad(highlights[i].quad)) + fz_throw(ctx, FZ_ERROR_ARGUMENT, + "PDF highlight contains a non-finite point"); + if (highlights[i].rgba[3] == 0) + continue; + + /* Kind is semantic metadata; caller-supplied RGBA is final. */ + (void)highlights[i].kind; + quad = pardes_pdf_quad_to_page(document, highlights[i].quad); + color[0] = highlights[i].rgba[0] / 255.0f; + color[1] = highlights[i].rgba[1] / 255.0f; + color[2] = highlights[i].rgba[2] / 255.0f; + alpha = highlights[i].rgba[3] / 255.0f; + + path = fz_new_path(ctx); + fz_moveto(ctx, path, quad.ul.x, quad.ul.y); + fz_lineto(ctx, path, quad.ur.x, quad.ur.y); + fz_lineto(ctx, path, quad.lr.x, quad.lr.y); + fz_lineto(ctx, path, quad.ll.x, quad.ll.y); + fz_closepath(ctx, path); + fz_fill_path(ctx, device, path, 0, fz_identity, + fz_device_rgb(ctx), color, alpha, + fz_default_color_params); + fz_drop_path(ctx, path); + path = NULL; + } + } + fz_always(ctx) + fz_drop_path(ctx, path); + fz_catch(ctx) + fz_rethrow(ctx); +} + +int +pardes_pdf_render_into( + pardes_pdf_document *document, + int page_number, + const pardes_pdf_request *request, + const pardes_pdf_highlight *highlights, + size_t highlight_count, + unsigned char *samples, + size_t samples_len, + int width, + int height, + int stride, + int band_y, + int band_height, + int transparent_paper) +{ + fz_context *ctx; + fz_pixmap *pixmap = NULL; + fz_device *device = NULL; + fz_matrix ctm; + fz_irect bbox; + + if (document == NULL || page_number < 0 || + page_number >= document->page_count || !pardes_pdf_request_ok(request) || + (highlight_count != 0 && highlights == NULL) || + highlight_count > PARDES_PDF_MAX_RESULT_QUADS || samples == NULL || + width < 1 || height < 1 || stride < 1 || width > INT_MAX / 4 || + stride != width * 4 || band_y < 0 || band_height < 1 || + band_y > height - band_height || + (size_t)band_height > SIZE_MAX / (size_t)stride || + samples_len != (size_t)stride * (size_t)band_height) + return PARDES_PDF_ERROR; + + ctx = document->ctx; + fz_var(pixmap); + fz_var(device); + fz_try(ctx) + { + pardes_pdf_render_geometry(document, page_number, request, &ctm, &bbox); + if (fz_irect_width(bbox) != width || + fz_irect_height(bbox) != height) + fz_throw(ctx, FZ_ERROR_ARGUMENT, + "PDF raster layout changed between measure and render"); + /* + * The BAND: rows [band_y, band_y + band_height) of the page raster, + * and nothing else. A pixmap's bbox IS the draw device's clip, so the + * page runs under the same CTM it would for a full raster and MuPDF + * discards everything outside these rows. The rows are NOT always + * bit-identical to the full page's: rows at the band's edges, and a + * resampled image anywhere in it, can differ (measured on + * docs/registry.pdf and docs/design.pdf), and an edge crossing the + * clip is stepped from a different start along its whole length, + * a level or two off. Good enough for a band shown while flinging, + * and for the chunks of a page too tall to render whole (pdf_view.zig + * renders those past their edges and keeps the middle); never use a + * band to patch rows into a whole-page raster -- + * `pardes_pdf_paint_highlights` exists for that. + */ + bbox.y0 += band_y; + bbox.y1 = bbox.y0 + band_height; + + /* External samples are never marked FZ_PIXMAP_FLAG_FREE_SAMPLES. */ + pixmap = fz_new_pixmap_with_bbox_and_data( + ctx, fz_device_rgb(ctx), bbox, NULL, 1, samples); + if (fz_pixmap_samples(ctx, pixmap) != samples || + fz_pixmap_width(ctx, pixmap) != width || + fz_pixmap_height(ctx, pixmap) != band_height || + fz_pixmap_stride(ctx, pixmap) != stride || + fz_pixmap_components(ctx, pixmap) != 4) + fz_throw(ctx, FZ_ERROR_FORMAT, + "MuPDF wrapped an unexpected RGBA layout"); + /* + * ponytail: this memset is ~9% of a fast scroll's profile and it has + * twice measured as unremovable. Filling with 32-byte vector stores + * instead (a memset of a multi-megabyte raster goes out through + * non-temporal stores, 7.4 GB/s against 41.7 for a store loop) changed + * a fling's median frame by nothing at all, and skipping the fill + * ENTIRELY changed it by 1-2%: the cache misses it is blamed for are + * paid either way by the glyph spans and the tint pass that walk the + * same buffer immediately afterwards. Leave it alone. + */ + if (transparent_paper) fz_clear_pixmap(ctx, pixmap); + else fz_clear_pixmap_with_value(ctx, pixmap, 0xFF); + + if (document->cached_display_list != NULL || + document->display_list_candidate_page_number == page_number) { + /* + * Only the nodes that reach the band: a band of a tall page + * skips the rest of the page instead of handing every node to + * the draw device to clip away. The scissor is in page space + * (the list runs untransformed under the device's CTM), a pixel + * wider than the band all round. Culling never changes a pixel: + * a node outside it draws nothing here. + */ + fz_rect scissor = fz_rect_from_irect(bbox); + scissor.x0 -= 1; scissor.y0 -= 1; scissor.x1 += 1; scissor.y1 += 1; + scissor = fz_transform_rect(scissor, fz_invert_matrix(ctm)); + pardes_pdf_cache_display_list(document); + device = fz_new_draw_device(ctx, ctm, pixmap); + fz_run_display_list(ctx, document->cached_display_list, device, + fz_identity, scissor, document->cookie); + } else { + device = fz_new_draw_device(ctx, ctm, pixmap); + fz_run_page(ctx, document->cached_page, device, fz_identity, document->cookie); + } + fz_close_device(ctx, device); + fz_drop_device(ctx, device); + device = NULL; + + if (highlight_count != 0) { + device = fz_new_draw_device(ctx, ctm, pixmap); + pardes_pdf_fill_highlights(ctx, document, device, highlights, highlight_count); + fz_close_device(ctx, device); + } + } + fz_always(ctx) + { + fz_drop_device(ctx, device); + /* Drops only the wrapper: caller-owned samples remain untouched. */ + fz_drop_pixmap(ctx, pixmap); + } + fz_catch(ctx) + { + fz_report_error(ctx); + return PARDES_PDF_ERROR; + } + /* An aborted run returns as if done, over half a page: say so. */ + if (document->cookie != NULL && document->cookie->abort) + return PARDES_PDF_ABORTED; + + /* MuPDF draws premultiplied samples. The public RGBA contract and tint + * pass use straight alpha; preserve coverage and undo premultiplication. */ + if (transparent_paper) { + size_t pixel; + for (pixel = 0; pixel < samples_len; pixel += 4) { + unsigned int a = samples[pixel + 3]; + int channel; + if (a == 0 || a == 255) continue; + for (channel = 0; channel < 3; ++channel) { + unsigned int straight = (samples[pixel + channel] * 255u + a / 2) / a; + samples[pixel + channel] = (unsigned char)(straight > 255 ? 255 : straight); + } + } + } + + if (document->cached_display_list == NULL) + document->display_list_candidate_page_number = page_number; + + return PARDES_PDF_OK; +} + +int +pardes_pdf_paint_highlights( + pardes_pdf_document *document, + int page_number, + const pardes_pdf_request *request, + const pardes_pdf_highlight *highlights, + size_t highlight_count, + unsigned char *samples, + size_t samples_len, + int width, + int height, + int stride, + int band_y, + int band_height) +{ + fz_context *ctx; + fz_pixmap *pixmap = NULL; + fz_device *device = NULL; + fz_matrix ctm; + fz_irect bbox; + + if (document == NULL || page_number < 0 || + page_number >= document->page_count || !pardes_pdf_request_ok(request) || + (highlight_count != 0 && highlights == NULL) || + highlight_count > PARDES_PDF_MAX_RESULT_QUADS || samples == NULL || + width < 1 || height < 1 || width > INT_MAX / 4 || stride != width * 4 || + band_y < 0 || band_height < 1 || band_y > height - band_height || + (size_t)band_height > SIZE_MAX / (size_t)stride || + samples_len != (size_t)stride * (size_t)band_height) + return PARDES_PDF_ERROR; + if (highlight_count == 0) + return PARDES_PDF_OK; + + ctx = document->ctx; + fz_var(pixmap); + fz_var(device); + fz_try(ctx) + { + pardes_pdf_render_geometry(document, page_number, request, &ctm, &bbox); + if (fz_irect_width(bbox) != width || fz_irect_height(bbox) != height) + fz_throw(ctx, FZ_ERROR_ARGUMENT, + "PDF raster layout changed between measure and paint"); + bbox.y0 += band_y; + bbox.y1 = bbox.y0 + band_height; + pixmap = fz_new_pixmap_with_bbox_and_data( + ctx, fz_device_rgb(ctx), bbox, NULL, 1, samples); + device = fz_new_draw_device(ctx, ctm, pixmap); + pardes_pdf_fill_highlights(ctx, document, device, highlights, highlight_count); + fz_close_device(ctx, device); + } + fz_always(ctx) + { + fz_drop_device(ctx, device); + fz_drop_pixmap(ctx, pixmap); + } + fz_catch(ctx) + { + fz_report_error(ctx); + return PARDES_PDF_ERROR; + } + return PARDES_PDF_OK; +} + +int +pardes_pdf_highlight_rows( + pardes_pdf_document *document, + int page_number, + const pardes_pdf_request *request, + const pardes_pdf_highlight *highlights, + size_t highlight_count, + int *row_start, + int *row_end) +{ + fz_context *ctx; + fz_matrix ctm; + fz_irect bbox; + float y0 = 0, y1 = 0; + int any = 0; + size_t i; + + if (row_start == NULL || row_end == NULL) + return PARDES_PDF_ERROR; + *row_start = *row_end = 0; + if (document == NULL || page_number < 0 || + page_number >= document->page_count || !pardes_pdf_request_ok(request) || + (highlight_count != 0 && highlights == NULL)) + return PARDES_PDF_ERROR; + + ctx = document->ctx; + fz_try(ctx) + { + pardes_pdf_render_geometry(document, page_number, request, &ctm, &bbox); + for (i = 0; i < highlight_count; ++i) { + fz_rect r; + if (highlights[i].rgba[3] == 0 || + !pardes_pdf_valid_quad(highlights[i].quad)) + continue; + r = fz_rect_from_quad(fz_transform_quad( + pardes_pdf_quad_to_page(document, highlights[i].quad), ctm)); + if (!any || r.y0 < y0) y0 = r.y0; + if (!any || r.y1 > y1) y1 = r.y1; + any = 1; + } + } + fz_catch(ctx) + { + fz_report_error(ctx); + return PARDES_PDF_ERROR; + } + if (any) { + /* + * Antialiasing covers the pixel a fractional edge falls in, and the + * rasterizer paints row floor(y1) even for a zero-height quad. + */ + int lo = (int)floorf(y0) - bbox.y0; + int hi = (int)floorf(y1) + 1 - bbox.y0; + int h = fz_irect_height(bbox); + *row_start = lo < 0 ? 0 : (lo > h ? h : lo); + *row_end = hi < *row_start ? *row_start : (hi > h ? h : hi); + } + return PARDES_PDF_OK; +} + +/* A page's text, a line of it a line of the result: MuPDF's own buffer + * joins a block's lines with spaces, which ran a heading into the + * paragraph under it. Structure blocks are walked into. */ +static void +pardes_append_stext_blocks(fz_context *ctx, fz_buffer *buffer, fz_stext_block *block) +{ + for (; block != NULL; block = block->next) + { + if (block->type == FZ_STEXT_BLOCK_STRUCT) + { + if (block->u.s.down != NULL) + pardes_append_stext_blocks(ctx, buffer, block->u.s.down->first_block); + continue; + } + if (block->type != FZ_STEXT_BLOCK_TEXT) + continue; + for (fz_stext_line *line = block->u.t.first_line; line != NULL; line = line->next) + { + for (fz_stext_char *ch = line->first_char; ch != NULL; ch = ch->next) + fz_append_rune(ctx, buffer, ch->c); + fz_append_byte(ctx, buffer, '\n'); + } + } +} + +int +pardes_pdf_page_text( + pardes_pdf_document *document, + int page_number, + pardes_pdf_text *out) +{ + fz_context *ctx; + fz_buffer *buffer = NULL; + unsigned char *data = NULL; + size_t len = 0; + + if (document == NULL || out == NULL || page_number < 0 || + page_number >= document->page_count) + return PARDES_PDF_ERROR; + + memset(out, 0, sizeof(*out)); + ctx = document->ctx; + fz_var(buffer); + fz_try(ctx) + { + pardes_pdf_cache_page(document, page_number, 1); + buffer = fz_new_buffer(ctx, 1024); + pardes_append_stext_blocks(ctx, buffer, document->cached_text->first_block); + len = fz_buffer_storage(ctx, buffer, &data); + } + fz_catch(ctx) + { + fz_report_error(ctx); + fz_drop_buffer(ctx, buffer); + return PARDES_PDF_ERROR; + } + + out->handle = buffer; + out->data = data; + out->len = len; + return PARDES_PDF_OK; +} + +void +pardes_pdf_drop_text(pardes_pdf_document *document, void *buffer) +{ + if (document != NULL && buffer != NULL) + fz_drop_buffer(document->ctx, (fz_buffer *)buffer); +} + +int +pardes_pdf_search_page( + pardes_pdf_document *document, + int page_number, + const char *needle, + pardes_pdf_search_result *out) +{ + fz_context *ctx; + fz_search *search = NULL; + pardes_pdf_search_quad *items = NULL; + size_t capacity = 0; + size_t quad_count = 0; + size_t hit_count = 0; + int status = PARDES_PDF_ERROR; + + if (document == NULL || needle == NULL || out == NULL || page_number < 0 || + page_number >= document->page_count) + return PARDES_PDF_ERROR; + + memset(out, 0, sizeof(*out)); + ctx = document->ctx; + fz_var(search); + fz_var(items); + fz_var(status); + fz_try(ctx) + { + pardes_pdf_cache_page(document, page_number, 1); + search = fz_new_search(ctx); + fz_search_set_options( + ctx, search, FZ_SEARCH_IGNORE_CASE, needle); + + /* fz_feed_search takes ownership; retain the document's cache ref. */ + fz_feed_search(ctx, search, + fz_keep_stext_page(ctx, document->cached_text), page_number); + + for (;;) { + fz_search_result result = fz_search_forwards(ctx, search); + if (result.reason == FZ_SEARCH_COMPLETE) + break; + if (result.reason == FZ_SEARCH_MORE_INPUT) { + /* This is deliberately a one-page search. */ + fz_feed_search(ctx, search, NULL, + result.u.more_input.seq_needed); + continue; + } + if (result.reason == FZ_SEARCH_MATCH) { + fz_search_result_details *details = result.u.match.result; + size_t match_quads; + size_t needed; + size_t next_capacity; + size_t i; + + if (details == NULL || details->num_quads < 0 || + (details->num_quads > 0 && details->quads == NULL)) + fz_throw(ctx, FZ_ERROR_FORMAT, + "MuPDF returned malformed search geometry"); + if (hit_count >= PARDES_PDF_MAX_RESULT_QUADS) { + status = PARDES_PDF_LIMIT_EXCEEDED; + fz_throw(ctx, FZ_ERROR_LIMIT, + "PDF search result limit exceeded"); + } + + match_quads = (size_t)details->num_quads; + if (match_quads > PARDES_PDF_MAX_RESULT_QUADS - quad_count) { + status = PARDES_PDF_LIMIT_EXCEEDED; + fz_throw(ctx, FZ_ERROR_LIMIT, + "PDF search quad limit exceeded"); + } + needed = quad_count + match_quads; + if (needed > capacity) { + next_capacity = pardes_pdf_grown_capacity( + capacity, needed, PARDES_PDF_MAX_RESULT_QUADS); + items = fz_realloc_array( + ctx, items, next_capacity, pardes_pdf_search_quad); + capacity = next_capacity; + } + for (i = 0; i < match_quads; ++i) { + items[quad_count + i].quad = pardes_pdf_quad_from_page( + document, details->quads[i].quad); + items[quad_count + i].hit = hit_count; + } + quad_count = needed; + ++hit_count; + continue; + } + fz_throw(ctx, FZ_ERROR_FORMAT, + "MuPDF returned an unknown search state"); + } + status = PARDES_PDF_OK; + } + fz_always(ctx) + { + fz_drop_search(ctx, search); + } + fz_catch(ctx) + { + if (status != PARDES_PDF_LIMIT_EXCEEDED) + fz_report_error(ctx); + fz_free(ctx, items); + return status; + } + + out->handle = items; + out->quads = items; + out->quad_count = quad_count; + out->hit_count = hit_count; + return PARDES_PDF_OK; +} + +void +pardes_pdf_drop_search_result(pardes_pdf_document *document, void *result) +{ + if (document != NULL && result != NULL) + fz_free(document->ctx, result); +} + +int +pardes_pdf_select( + pardes_pdf_document *document, + int page_number, + pardes_pdf_point start, + pardes_pdf_point end, + pardes_pdf_selection *out) +{ + fz_context *ctx; + fz_quad *raw = NULL; + pardes_pdf_quad *items = NULL; + fz_point a; + fz_point b; + int capacity = PARDES_PDF_INITIAL_RESULT_QUADS; + int count = 0; + int status = PARDES_PDF_ERROR; + int i; + + if (document == NULL || out == NULL || page_number < 0 || + page_number >= document->page_count || + !pardes_pdf_valid_point(start) || !pardes_pdf_valid_point(end)) + return PARDES_PDF_ERROR; + + memset(out, 0, sizeof(*out)); + ctx = document->ctx; + fz_var(raw); + fz_var(items); + fz_var(status); + fz_try(ctx) + { + pardes_pdf_cache_page(document, page_number, 1); + a = pardes_pdf_point_to_page(document, start); + b = pardes_pdf_point_to_page(document, end); + (void)fz_snap_selection( + ctx, document->cached_text, &a, &b, FZ_SELECT_WORDS); + + raw = fz_malloc_array(ctx, capacity, fz_quad); + for (;;) { + int next_capacity; + count = fz_highlight_selection( + ctx, document->cached_text, a, b, raw, capacity); + if (count < 0) + fz_throw(ctx, FZ_ERROR_FORMAT, + "MuPDF returned an invalid selection count"); + if (count < capacity) + break; + + /* One extra slot distinguishes exactly-at-limit from truncation. */ + if (capacity >= PARDES_PDF_MAX_RESULT_QUADS + 1) { + status = PARDES_PDF_LIMIT_EXCEEDED; + fz_throw(ctx, FZ_ERROR_LIMIT, + "PDF selection quad limit exceeded"); + } + next_capacity = capacity * 2; + if (next_capacity > PARDES_PDF_MAX_RESULT_QUADS + 1) + next_capacity = PARDES_PDF_MAX_RESULT_QUADS + 1; + raw = fz_realloc_array(ctx, raw, next_capacity, fz_quad); + capacity = next_capacity; + } + if (count > PARDES_PDF_MAX_RESULT_QUADS) { + status = PARDES_PDF_LIMIT_EXCEEDED; + fz_throw(ctx, FZ_ERROR_LIMIT, + "PDF selection quad limit exceeded"); + } + + if (count != 0) + items = fz_malloc_array(ctx, (size_t)count, pardes_pdf_quad); + for (i = 0; i < count; ++i) + items[i] = pardes_pdf_quad_from_page(document, raw[i]); + status = PARDES_PDF_OK; + } + fz_always(ctx) + { + fz_free(ctx, raw); + } + fz_catch(ctx) + { + if (status != PARDES_PDF_LIMIT_EXCEEDED) + fz_report_error(ctx); + fz_free(ctx, items); + return status; + } + + out->handle = items; + out->quads = items; + out->quad_count = (size_t)count; + out->start = pardes_pdf_point_from_page(document, a); + out->end = pardes_pdf_point_from_page(document, b); + return PARDES_PDF_OK; +} + +void +pardes_pdf_drop_selection(pardes_pdf_document *document, void *selection) +{ + if (document != NULL && selection != NULL) + fz_free(document->ctx, selection); +} + +int +pardes_pdf_point_inside_quad(pardes_pdf_point point, pardes_pdf_quad quad) +{ + fz_quad native; + + if (!pardes_pdf_valid_point(point) || !pardes_pdf_valid_quad(quad)) + return 0; + native.ul = fz_make_point(quad.ul.x, quad.ul.y); + native.ur = fz_make_point(quad.ur.x, quad.ur.y); + native.ll = fz_make_point(quad.ll.x, quad.ll.y); + native.lr = fz_make_point(quad.lr.x, quad.lr.y); + return fz_is_point_inside_quad( + fz_make_point(point.x, point.y), native) != 0; +} + +int +pardes_pdf_link_at( + pardes_pdf_document *document, + int page_number, + pardes_pdf_point point, + pardes_pdf_link *out) +{ + fz_context *ctx; + + if (out == NULL) + return PARDES_PDF_ERROR; + memset(out, 0, sizeof(*out)); + out->page = -1; + if (document == NULL || page_number < 0 || + page_number >= document->page_count) + return PARDES_PDF_ERROR; + if (!pardes_pdf_valid_point(point) || point.x < 0 || point.x > 1 || + point.y < 0 || point.y > 1) + return PARDES_PDF_OK; + + ctx = document->ctx; + fz_try(ctx) + { + fz_link *link; + fz_point page_point; + pardes_pdf_cache_page(document, page_number, 0); + if (!document->cached_links_loaded) { + document->cached_links = fz_load_links(ctx, document->cached_page); + document->cached_links_loaded = 1; + } + page_point = pardes_pdf_point_to_page(document, point); + for (link = document->cached_links; link != NULL; link = link->next) { + size_t len; + int destination_kind; + int destination_page = -1; + fz_link_dest destination = fz_make_link_dest_none(); + if (!pardes_pdf_valid_bounds(link->rect) || + !fz_is_point_inside_rect(page_point, link->rect) || + link->uri == NULL || link->uri[0] == 0) + continue; + for (len = 0; len <= PARDES_PDF_MAX_LINK_URI_BYTES && + link->uri[len] != 0; ++len) + ; + if (len > PARDES_PDF_MAX_LINK_URI_BYTES) + continue; + destination_kind = PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL; + if (!fz_is_external_link(ctx, link->uri)) { + destination = fz_resolve_link_dest(ctx, document->doc, link->uri); + if (destination.loc.chapter >= 0 && destination.loc.page >= 0) + destination_page = fz_page_number_from_location( + ctx, document->doc, destination.loc); + if (destination_page >= 0 && destination_page < document->page_count) + destination_kind = PARDES_PDF_OUTLINE_DESTINATION_INTERNAL; + else if (link->uri[0] == '#') + continue; + } + out->quad = pardes_pdf_quad_from_page( + document, fz_quad_from_rect(link->rect)); + out->destination_kind = destination_kind; + if (destination_kind == PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) { + out->page = destination_page; + out->has_x = isfinite(destination.x); + out->has_y = isfinite(destination.y); + if (out->has_x) out->x = destination.x; + if (out->has_y) out->y = destination.y; + } + out->uri = (const unsigned char *)link->uri; + out->uri_len = len; + break; + } + } + fz_catch(ctx) + { + memset(out, 0, sizeof(*out)); + return PARDES_PDF_ERROR; + } + return PARDES_PDF_OK; +} + +int +pardes_pdf_copy_selection( + pardes_pdf_document *document, + int page_number, + pardes_pdf_point start, + pardes_pdf_point end, + pardes_pdf_owned_text *out) +{ + fz_context *ctx; + char *text = NULL; + fz_point a; + fz_point b; + + if (document == NULL || out == NULL || page_number < 0 || + page_number >= document->page_count || + !pardes_pdf_valid_point(start) || !pardes_pdf_valid_point(end)) + return PARDES_PDF_ERROR; + + memset(out, 0, sizeof(*out)); + ctx = document->ctx; + fz_var(text); + fz_try(ctx) + { + pardes_pdf_cache_page(document, page_number, 1); + a = pardes_pdf_point_to_page(document, start); + b = pardes_pdf_point_to_page(document, end); + text = fz_copy_selection(ctx, document->cached_text, a, b, 0); + } + fz_catch(ctx) + { + fz_report_error(ctx); + fz_free(ctx, text); + return PARDES_PDF_ERROR; + } + + out->handle = text; + out->data = (const unsigned char *)text; + out->len = text == NULL ? 0 : strlen(text); + return PARDES_PDF_OK; +} + +void +pardes_pdf_drop_owned_text(pardes_pdf_document *document, void *text) +{ + if (document != NULL && text != NULL) + fz_free(document->ctx, text); +} + +int +pardes_pdf_copy_rectangle( + pardes_pdf_document *document, + int page_number, + pardes_pdf_quad quad, + pardes_pdf_owned_text *out) +{ + fz_context *ctx; + char *text = NULL; + fz_quad native; + if (document == NULL || out == NULL || page_number < 0 || + page_number >= document->page_count || !pardes_pdf_valid_quad(quad)) + return PARDES_PDF_ERROR; + memset(out, 0, sizeof(*out)); + ctx = document->ctx; + fz_var(text); + fz_try(ctx) + { + pardes_pdf_cache_page(document, page_number, 1); + native.ul = pardes_pdf_point_to_page(document, quad.ul); + native.ur = pardes_pdf_point_to_page(document, quad.ur); + native.ll = pardes_pdf_point_to_page(document, quad.ll); + native.lr = pardes_pdf_point_to_page(document, quad.lr); + text = fz_copy_rectangle(ctx, document->cached_text, + fz_rect_from_quad(native), 0); + } + fz_catch(ctx) + { + fz_free(ctx, text); + return PARDES_PDF_ERROR; + } + out->handle = text; + out->data = (const unsigned char *)text; + out->len = text == NULL ? 0 : strlen(text); + return PARDES_PDF_OK; +} + +typedef struct pardes_pdf_outline_measurement { + size_t item_count; + size_t bytes_len; + int status; +} pardes_pdf_outline_measurement; + +static int +pardes_pdf_outline_destination(const fz_outline *node, fz_context *ctx) +{ + if (node->page.chapter >= 0 && node->page.page >= 0) + return PARDES_PDF_OUTLINE_DESTINATION_INTERNAL; + if (node->page.chapter >= 0 || node->page.page >= 0) + fz_throw(ctx, FZ_ERROR_FORMAT, + "PDF outline has a partially resolved destination"); + if (node->uri != NULL && fz_is_external_link(ctx, node->uri)) + return PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL; + return PARDES_PDF_OUTLINE_DESTINATION_NONE; +} + +static size_t +pardes_pdf_bounded_outline_string( + fz_context *ctx, + const char *value, + size_t remaining, + int *status) +{ + size_t len; + + if (value == NULL) + return 0; + len = strnlen(value, remaining + 1); + if (len > remaining) { + *status = PARDES_PDF_LIMIT_EXCEEDED; + fz_throw(ctx, FZ_ERROR_LIMIT, + "PDF outline metadata byte limit exceeded"); + } + return len; +} + +static void +pardes_pdf_measure_outline( + fz_context *ctx, + const fz_outline *node, + unsigned int depth, + pardes_pdf_outline_measurement *measurement) +{ + for (; node != NULL; node = node->next) { + size_t remaining; + int destination; + + if (depth >= PARDES_PDF_MAX_OUTLINE_DEPTH || + measurement->item_count >= PARDES_PDF_MAX_OUTLINE_ITEMS) { + measurement->status = PARDES_PDF_LIMIT_EXCEEDED; + fz_throw(ctx, FZ_ERROR_LIMIT, "PDF outline limit exceeded"); + } + ++measurement->item_count; + + remaining = PARDES_PDF_MAX_OUTLINE_BYTES - measurement->bytes_len; + measurement->bytes_len += pardes_pdf_bounded_outline_string( + ctx, node->title, remaining, &measurement->status); + + destination = pardes_pdf_outline_destination(node, ctx); + if (destination == PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL) { + remaining = PARDES_PDF_MAX_OUTLINE_BYTES - + measurement->bytes_len; + measurement->bytes_len += pardes_pdf_bounded_outline_string( + ctx, node->uri, remaining, &measurement->status); + } + + if (node->down != NULL) + pardes_pdf_measure_outline( + ctx, node->down, depth + 1, measurement); + } +} + +static void +pardes_pdf_flatten_outline( + pardes_pdf_document *document, + const fz_outline *node, + unsigned int depth, + pardes_pdf_outline_item *items, + unsigned char *bytes, + size_t item_count, + size_t bytes_len, + size_t *item_at, + size_t *byte_at) +{ + fz_context *ctx = document->ctx; + + for (; node != NULL; node = node->next) { + pardes_pdf_outline_item *item; + int destination; + size_t len; + + if (*item_at >= item_count) + fz_throw(ctx, FZ_ERROR_FORMAT, + "PDF outline changed while flattening"); + item = &items[(*item_at)++]; + memset(item, 0, sizeof(*item)); + item->depth = depth; + item->page = -1; + item->is_open = node->is_open != 0; + item->flags = (unsigned char)node->flags; + item->r = (unsigned char)node->r; + item->g = (unsigned char)node->g; + item->b = (unsigned char)node->b; + + if (node->title != NULL) { + len = strlen(node->title); + if (*byte_at > bytes_len || len > bytes_len - *byte_at) + fz_throw(ctx, FZ_ERROR_FORMAT, + "PDF outline title changed while flattening"); + item->title_present = 1; + item->title_offset = *byte_at; + item->title_len = len; + memcpy(bytes + *byte_at, node->title, len); + *byte_at += len; + } + + destination = pardes_pdf_outline_destination(node, ctx); + item->destination_kind = destination; + if (destination == PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) { + item->page = fz_page_number_from_location( + ctx, document->doc, node->page); + if (item->page < 0 || item->page >= document->page_count) + fz_throw(ctx, FZ_ERROR_FORMAT, + "PDF outline resolved outside the document"); + item->has_x = isfinite(node->x); + item->has_y = isfinite(node->y); + if (item->has_x) + item->x = node->x; + if (item->has_y) + item->y = node->y; + } else if (destination == PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL) { + len = strlen(node->uri); + if (*byte_at > bytes_len || len > bytes_len - *byte_at) + fz_throw(ctx, FZ_ERROR_FORMAT, + "PDF outline URI changed while flattening"); + item->uri_offset = *byte_at; + item->uri_len = len; + memcpy(bytes + *byte_at, node->uri, len); + *byte_at += len; + } + + if (node->down != NULL) + pardes_pdf_flatten_outline(document, node->down, depth + 1, + items, bytes, item_count, bytes_len, item_at, byte_at); + } +} + +static unsigned char +pardes_pdf_outline_color(fz_context *ctx, float value) +{ + if (!isfinite(value) || value < 0.0f || value > 255.0f) + fz_throw(ctx, FZ_ERROR_FORMAT, + "PDF outline has an invalid style color"); + return (unsigned char)(value + 0.5f); +} + +/* + * MuPDF 1.27's generic fz_load_outline adapter does not copy the iterator's + * style fields into fz_outline. Overlay them from a second, allocation-light + * iterator pass while retaining the loaded tree as the destination authority. + */ +static void +pardes_pdf_apply_outline_styles( + fz_context *ctx, + fz_outline_iterator *iterator, + unsigned int depth, + pardes_pdf_outline_item *items, + size_t item_count, + size_t *item_at) +{ + int moved; + + do { + fz_outline_item *style = fz_outline_iterator_item(ctx, iterator); + pardes_pdf_outline_item *item; + + if (style == NULL) + return; + if (*item_at >= item_count || items[*item_at].depth != depth || + style->flags < 0 || style->flags > 127) + fz_throw(ctx, FZ_ERROR_FORMAT, + "PDF outline changed while reading styles"); + item = &items[(*item_at)++]; + item->flags = (unsigned char)style->flags; + item->r = pardes_pdf_outline_color(ctx, style->r); + item->g = pardes_pdf_outline_color(ctx, style->g); + item->b = pardes_pdf_outline_color(ctx, style->b); + + moved = fz_outline_iterator_down(ctx, iterator); + if (moved == FZ_OUTLINE_ITERATOR_AT_ITEM) + pardes_pdf_apply_outline_styles(ctx, iterator, depth + 1, + items, item_count, item_at); + if (moved >= 0) + (void)fz_outline_iterator_up(ctx, iterator); + } while (fz_outline_iterator_next(ctx, iterator) == + FZ_OUTLINE_ITERATOR_AT_ITEM); +} + +int +pardes_pdf_load_outline( + pardes_pdf_document *document, + pardes_pdf_outline_result *out) +{ + fz_context *ctx; + fz_outline *outline = NULL; + fz_outline_iterator *iterator = NULL; + unsigned char *block = NULL; + pardes_pdf_outline_measurement measurement = {0}; + size_t item_bytes; + size_t total_bytes; + size_t item_at = 0; + size_t byte_at = 0; + size_t style_at = 0; + int status = PARDES_PDF_ERROR; + + if (document == NULL || out == NULL) + return PARDES_PDF_ERROR; + memset(out, 0, sizeof(*out)); + ctx = document->ctx; + measurement.status = PARDES_PDF_ERROR; + + fz_var(outline); + fz_var(iterator); + fz_var(block); + fz_var(measurement); + fz_var(status); + fz_try(ctx) + { + outline = fz_load_outline(ctx, document->doc); + pardes_pdf_measure_outline(ctx, outline, 0, &measurement); + if (measurement.item_count > + SIZE_MAX / sizeof(pardes_pdf_outline_item) || + measurement.bytes_len > SIZE_MAX - measurement.item_count * + sizeof(pardes_pdf_outline_item)) { + measurement.status = PARDES_PDF_LIMIT_EXCEEDED; + fz_throw(ctx, FZ_ERROR_LIMIT, + "PDF outline allocation size overflow"); + } + item_bytes = measurement.item_count * + sizeof(pardes_pdf_outline_item); + total_bytes = item_bytes + measurement.bytes_len; + if (total_bytes != 0) { + block = fz_malloc(ctx, total_bytes); + pardes_pdf_flatten_outline(document, outline, 0, + (pardes_pdf_outline_item *)block, block + item_bytes, + measurement.item_count, measurement.bytes_len, + &item_at, &byte_at); + if (item_at != measurement.item_count || + byte_at != measurement.bytes_len) + fz_throw(ctx, FZ_ERROR_FORMAT, + "PDF outline changed while flattening"); + iterator = fz_new_outline_iterator(ctx, document->doc); + if (iterator != NULL) { + pardes_pdf_apply_outline_styles(ctx, iterator, 0, + (pardes_pdf_outline_item *)block, + measurement.item_count, &style_at); + if (style_at != measurement.item_count) + fz_throw(ctx, FZ_ERROR_FORMAT, + "PDF outline changed while reading styles"); + } + } + status = PARDES_PDF_OK; + } + fz_always(ctx) + { + fz_drop_outline_iterator(ctx, iterator); + fz_drop_outline(ctx, outline); + } + fz_catch(ctx) + { + if (measurement.status != PARDES_PDF_LIMIT_EXCEEDED) + fz_report_error(ctx); + fz_free(ctx, block); + memset(out, 0, sizeof(*out)); + return measurement.status == PARDES_PDF_LIMIT_EXCEEDED ? + PARDES_PDF_LIMIT_EXCEEDED : PARDES_PDF_ERROR; + } + + out->handle = block; + out->items = (const pardes_pdf_outline_item *)block; + out->item_count = measurement.item_count; + out->bytes = block == NULL ? NULL : block + item_bytes; + out->bytes_len = measurement.bytes_len; + return status; +} + +void +pardes_pdf_drop_outline_result( + pardes_pdf_document *document, + void *outline) +{ + if (document != NULL && outline != NULL) + fz_free(document->ctx, outline); +} diff --git a/addons/pdf/pdf_bridge.h b/addons/pdf/pdf_bridge.h new file mode 100644 index 00000000..fd5d05d0 --- /dev/null +++ b/addons/pdf/pdf_bridge.h @@ -0,0 +1,402 @@ +#ifndef PARDES_PDF_BRIDGE_H +#define PARDES_PDF_BRIDGE_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * MuPDF reports failures with setjmp/longjmp through fz_try/fz_catch. Those + * jumps must never cross Zig frames, so every operation that can throw lives + * behind this deliberately small C boundary. + */ +typedef struct pardes_pdf_document pardes_pdf_document; + +typedef void *(*pardes_pdf_alloc_fn)(void *user, size_t size); +typedef void *(*pardes_pdf_realloc_fn)( + void *user, + void *pointer, + size_t size +); +typedef void (*pardes_pdf_free_fn)(void *user, void *pointer); + +typedef struct pardes_pdf_allocator { + void *user; + pardes_pdf_alloc_fn alloc; + pardes_pdf_realloc_fn realloc; + pardes_pdf_free_fn free; +} pardes_pdf_allocator; + +/* + * Install one process-global allocator, or restore libc/default MuPDF + * allocation by passing NULL. Changing it while a document is live fails. + */ +int pardes_pdf_set_allocator(const pardes_pdf_allocator *allocator); + +typedef struct pardes_pdf_raster_layout { + int width; + int height; + int stride; + size_t samples_len; +} pardes_pdf_raster_layout; + +/* + * One raster request (pdf.zig's RenderRequest, bounded): every function + * that rasterizes a page, paints over it or measures it takes the same one + * and computes the same raster from it (see pardes_pdf_measure_render). + * Zero minimum or display sizes are none. + */ +typedef struct pardes_pdf_request { + int dpi; + int minimum_width; + int minimum_height; + int max_dimension; + int display_width; + int display_height; +} pardes_pdf_request; + +typedef struct pardes_pdf_page_size { + float width; + float height; +} pardes_pdf_page_size; + +typedef struct pardes_pdf_text { + void *handle; + const unsigned char *data; + size_t len; +} pardes_pdf_text; + +/* + * All geometry crossing this boundary is normalized to the cached page's + * bounds. (0,0) is the page's top-left and (1,1) its bottom-right, regardless + * of the DPI used for a particular render. Corner names retain MuPDF's quad + * orientation; callers must not collapse them to an axis-aligned rectangle. + */ +typedef struct pardes_pdf_point { + float x; + float y; +} pardes_pdf_point; + +typedef struct pardes_pdf_quad { + pardes_pdf_point ul; + pardes_pdf_point ur; + pardes_pdf_point ll; + pardes_pdf_point lr; +} pardes_pdf_quad; + +typedef enum pardes_pdf_highlight_kind { + PARDES_PDF_HIGHLIGHT_CUSTOM = 0, + PARDES_PDF_HIGHLIGHT_SEARCH = 1, + PARDES_PDF_HIGHLIGHT_SELECTION = 2 +} pardes_pdf_highlight_kind; + +typedef struct pardes_pdf_highlight { + pardes_pdf_quad quad; + unsigned char rgba[4]; + int kind; +} pardes_pdf_highlight; + +typedef struct pardes_pdf_search_quad { + pardes_pdf_quad quad; + size_t hit; +} pardes_pdf_search_quad; + +typedef struct pardes_pdf_search_result { + void *handle; + const pardes_pdf_search_quad *quads; + size_t quad_count; + size_t hit_count; +} pardes_pdf_search_result; + +typedef struct pardes_pdf_selection { + void *handle; + const pardes_pdf_quad *quads; + size_t quad_count; + pardes_pdf_point start; + pardes_pdf_point end; +} pardes_pdf_selection; + +typedef struct pardes_pdf_owned_text { + void *handle; + const unsigned char *data; + size_t len; +} pardes_pdf_owned_text; + +typedef enum pardes_pdf_outline_destination_kind { + PARDES_PDF_OUTLINE_DESTINATION_NONE = 0, + PARDES_PDF_OUTLINE_DESTINATION_INTERNAL = 1, + PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL = 2 +} pardes_pdf_outline_destination_kind; + +/* + * One pre-order depth-first row. Offsets address the result's byte arena; + * title_present distinguishes a missing title from a present empty title. + * Internal page numbers are zero-based. has_x/has_y preserve MuPDF's NAN + * sentinel for viewing coordinates that the outline destination omits. + */ +typedef struct pardes_pdf_outline_item { + size_t title_offset; + size_t title_len; + size_t uri_offset; + size_t uri_len; + unsigned int depth; + int page; + float x; + float y; + unsigned char title_present; + unsigned char has_x; + unsigned char has_y; + unsigned char is_open; + unsigned char flags; + unsigned char r; + unsigned char g; + unsigned char b; + int destination_kind; +} pardes_pdf_outline_item; + +typedef struct pardes_pdf_outline_result { + void *handle; + const pardes_pdf_outline_item *items; + size_t item_count; + const unsigned char *bytes; + size_t bytes_len; +} pardes_pdf_outline_result; + +/* URI borrows the current page's lazily loaded link list. Copy it before any + * other document operation. A NULL URI means the point has no usable link. */ +typedef struct pardes_pdf_link { + const unsigned char *uri; + size_t uri_len; + pardes_pdf_quad quad; + int destination_kind; + int page; + float x; + float y; + unsigned char has_x; + unsigned char has_y; +} pardes_pdf_link; + +enum { + PARDES_PDF_OK = 0, + PARDES_PDF_ERROR = -1, + PARDES_PDF_LIMIT_EXCEEDED = -2, + /* A render stopped early through its cookie (pardes_pdf_set_cookie). */ + PARDES_PDF_ABORTED = -3, + + /* Per-document MuPDF eviction cache; render buffers are separate. */ + PARDES_PDF_STORE_LIMIT_BYTES = 64 * 1024 * 1024, + + /* + * Search grows geometrically up to this aggregate count and then fails + * atomically with PARDES_PDF_LIMIT_EXCEEDED; it never returns a silently + * truncated result. Selection uses one extra private probe slot so an + * exact-at-the-limit result remains distinguishable from truncation. + */ + PARDES_PDF_MAX_RESULT_QUADS = 65536, + + /* Outline conversion is atomic: crossing any bound returns no rows. */ + PARDES_PDF_MAX_OUTLINE_ITEMS = 8192, + PARDES_PDF_MAX_OUTLINE_DEPTH = 64, + PARDES_PDF_MAX_OUTLINE_BYTES = 4 * 1024 * 1024, + PARDES_PDF_MAX_LINK_URI_BYTES = 64 * 1024, + + /* No page raster is taller than this, whatever it is shown at. */ + PARDES_PDF_MAX_RASTER_ROWS = 1 << 20 +}; + +pardes_pdf_document *pardes_pdf_open_memory(const unsigned char *bytes, size_t length, int *page_count); +void pardes_pdf_close(pardes_pdf_document *document); +/* The bytes a document was opened from (its own copy, a lane's its base's), + * for as long as it is open. */ +const unsigned char *pardes_pdf_bytes(pardes_pdf_document *document, size_t *length); + +/* + * A render lane: a context cloned from `base`'s (fz_clone_context: the store, + * the allocator and the locks shared) and a document of its OWN, opened from + * the bytes `base` holds (the fz_buffer shared, read only). MuPDF allows one + * thread at a time in a context and in a document; a lane is used by one + * thread at a time and never shares either with `base` or another lane, so + * lanes render while `base` serves the UI thread. Clone on the thread that + * owns `base` (the clone reads its context); `pardes_pdf_lane_open` then runs + * on the lane's thread. Close every lane before `base`. NULL: no lane (out of + * memory). + */ +pardes_pdf_document *pardes_pdf_lane_clone(pardes_pdf_document *base); +int pardes_pdf_lane_open(pardes_pdf_document *lane); + +/* Mirrors fz_cookie (checked in the bridge): set `abort` nonzero from any + * thread and a render running under it stops at its next operator. */ +typedef struct pardes_pdf_cookie { + int abort; + int progress; + size_t progress_max; + int errors; + int incomplete; +} pardes_pdf_cookie; + +/* The cookie the document's renders run under (NULL: none), until set again. */ +void pardes_pdf_set_cookie(pardes_pdf_document *document, pardes_pdf_cookie *cookie); + +/* Page dimensions in PDF points after crop/rotation, without rasterizing. */ +int pardes_pdf_get_page_size( + pardes_pdf_document *document, + int page, + pardes_pdf_page_size *out +); + +/* + * Start at dpi, raise the uniform scale until both optional minimum pixel + * dimensions are met, then clamp the page's width to max_dimension, and its + * height too unless that would draw it smaller than the optional display size + * (the width or height it is shown at): a tall page is then as tall as it is + * shown, and its owner renders it in bands. Every function below takes the + * same request and computes the same raster from it. + * Measuring may populate the page cache, but never advances adaptive display + * list promotion; only a successful render_into does that. + */ +int pardes_pdf_measure_render( + pardes_pdf_document *document, + int page, + const pardes_pdf_request *request, + pardes_pdf_raster_layout *out +); + +/* + * Rasterize one horizontal BAND of a page — rows [band_y, band_y+band_height) + * of the raster `pardes_pdf_measure_render` describes — directly into an + * exactly-sized caller-owned packed RGBA buffer, `stride * band_height` bytes. + * A full page is the band `(0, height)`. + * + * MuPDF wraps but never owns or frees samples. Every successful pixel is + * opaque unless transparent_paper is nonzero. That mode preserves content + * coverage and returns straight-alpha RGBA over an unpainted page. + * The CTM does not depend on the band, so a band is a clip of the same + * rendering -- but not a bit-exact one: its edge rows and resampled images can + * differ from the whole page's (see pardes_pdf_render_into). + */ +int pardes_pdf_render_into( + pardes_pdf_document *document, + int page, + const pardes_pdf_request *request, + const pardes_pdf_highlight *highlights, + size_t highlight_count, + unsigned char *samples, + size_t samples_len, + int width, + int height, + int stride, + int band_y, + int band_height, + int transparent_paper +); + +/* + * The highlight pass of `pardes_pdf_render_into` alone, over caller-supplied + * rows of that page's opaque raster: render_into(h) == paint(render_into({}), h) + * row for row, because a render draws its highlights over the finished page. + */ +int pardes_pdf_paint_highlights( + pardes_pdf_document *document, + int page, + const pardes_pdf_request *request, + const pardes_pdf_highlight *highlights, + size_t highlight_count, + unsigned char *samples, + size_t samples_len, + int width, + int height, + int stride, + int band_y, + int band_height +); + +/* + * The raster rows [*row_start, *row_end) that painting `highlights` can touch + * under the same request, in the coordinates `pardes_pdf_render_into` bands + * use. An empty set (or only transparent ones) yields start == end == 0. + */ +int pardes_pdf_highlight_rows( + pardes_pdf_document *document, + int page, + const pardes_pdf_request *request, + const pardes_pdf_highlight *highlights, + size_t highlight_count, + int *row_start, + int *row_end +); + +int pardes_pdf_page_text( + pardes_pdf_document *document, + int page, + pardes_pdf_text *out +); +void pardes_pdf_drop_text(pardes_pdf_document *document, void *buffer); + +/* Case-insensitive, single-page search using MuPDF 1.27's iterative API. */ +int pardes_pdf_search_page( + pardes_pdf_document *document, + int page, + const char *needle, + pardes_pdf_search_result *out +); +void pardes_pdf_drop_search_result(pardes_pdf_document *document, void *result); + +/* Word-snap two normalized points and return oriented highlight quads. */ +int pardes_pdf_select( + pardes_pdf_document *document, + int page, + pardes_pdf_point start, + pardes_pdf_point end, + pardes_pdf_selection *out +); +void pardes_pdf_drop_selection(pardes_pdf_document *document, void *selection); + +/* Pure/no-throw oriented-quad hit test in normalized page space. */ +int pardes_pdf_point_inside_quad( + pardes_pdf_point point, + pardes_pdf_quad quad +); + +/* The input endpoints are normally the snapped points returned above. */ +int pardes_pdf_copy_selection( + pardes_pdf_document *document, + int page, + pardes_pdf_point start, + pardes_pdf_point end, + pardes_pdf_owned_text *out +); +void pardes_pdf_drop_owned_text(pardes_pdf_document *document, void *text); + +/* + * Flatten fz_load_outline's tree in stable document-order DFS. The borrowed + * table and byte arena remain valid until drop_outline_result. + */ +int pardes_pdf_load_outline( + pardes_pdf_document *document, + pardes_pdf_outline_result *out +); +void pardes_pdf_drop_outline_result( + pardes_pdf_document *document, + void *outline +); + +int pardes_pdf_link_at( + pardes_pdf_document *document, + int page_number, + pardes_pdf_point point, + pardes_pdf_link *out +); +int pardes_pdf_copy_rectangle( + pardes_pdf_document *document, + int page_number, + pardes_pdf_quad quad, + pardes_pdf_owned_text *out +); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/build.zig b/build.zig index 0e01cdec..f275475a 100644 --- a/build.zig +++ b/build.zig @@ -93,12 +93,14 @@ pub fn build(b: *std.Build) void { &.{f} else &.{}; - const enable_mupdf = b.option(bool, "mupdf", "PDF rendering with MuPDF (AGPL/commercial; default on; -Dmupdf=false disables)") orelse true; + const enable_mupdf = b.option(bool, "mupdf", "build the pdf addon, PDF panes over MuPDF (AGPL/commercial; default on; -Dmupdf=false leaves it out)") orelse true; const enable_jpx = b.option(bool, "jpx", "JPEG 2000 in PDFs, for scanned documents (default on; -Djpx=false drops openjpeg)") orelse true; const embed_sources = b.option(bool, "embed-sources", "serve the editor's own sources under /src of its 9P tree (default off)") orelse false; const test_build = b.step("test-build", "compile unit-test programs without running them"); const doc_typ_opts = b.addOptions(); doc_typ_opts.addOptionPathUntracked("dir", b.path("docs/typ")); + // The words the shipped addons bring (PdfFit...), which the docs name too. + doc_typ_opts.addOptionPathUntracked("addons", b.path("addons")); // The docs (docs/typ, docs/site): each output is one typst run, and each // reads docs/typ/builtins-*.json; `builtins-json` refreshes this build's from the // registry first (the tool is wired below, once the core module is). @@ -152,17 +154,11 @@ pub fn build(b: *std.Build) void { const macos_identity = b.option([]const u8, "macos-identity", "codesigning identity for pardes.app (default: ad-hoc)") orelse "-"; const prebuilt_shaders = b.option(bool, "prebuilt-shaders", "embed the committed shaders/prebuilt/*.spv instead of running glslc (default: on for a bare `zig build`, off when -Dplatform names a shell)") orelse also_gui; - const mupdf_check = b.step("mupdf-check", "compile, link, render, and search docs/design.pdf with MuPDF"); - const pdf_bench_step = b.step("pdf-bench", "benchmark real MuPDF page rendering (-- [--json] [--reps N] [--warmup N] [--path FILE] [--page N] [--pages N])"); - const pdf_sections_bench_step = b.step("pdf-sections-bench", "benchmark PDF outline/sections paths in ReleaseFast (-Doptimize=ReleaseFast -- [--json] [--reps N] [--warmup N])"); + const mupdf_check = b.step("mupdf-check", "the pdf addon's check: MuPDF compiles, links, renders and searches docs/design.pdf, and its script runs"); const pdf_pointer_bench_step = b.step("pdf-pointer-bench", "time PDF hover and selection gestures and prove their pixels (-Doptimize=ReleaseFast -- [--label L] [--reps N] [--path FILE] [--cell WxH])"); const pdf_scroll_bench_step = b.step("pdf-scroll-bench", "benchmark fast continuous-strip PDF scrolling in ReleaseFast (-Doptimize=ReleaseFast -- [--json] [--reps N] [--warmup N] [--path FILE])"); if (!enable_mupdf) mupdf_check.dependOn(&b.addFail("mupdf-check is unavailable with -Dmupdf=false").step); - if (!enable_mupdf) - pdf_bench_step.dependOn(&b.addFail("pdf-bench is unavailable with -Dmupdf=false").step); - if (!enable_mupdf) - pdf_sections_bench_step.dependOn(&b.addFail("pdf-sections-bench is unavailable with -Dmupdf=false").step); if (!enable_mupdf) pdf_scroll_bench_step.dependOn(&b.addFail("pdf-scroll-bench is unavailable with -Dmupdf=false").step); if (!enable_mupdf) @@ -239,7 +235,6 @@ pub fn build(b: *std.Build) void { // can name them all. The unconditional ones are ordinary consts below. var ts_mod: ?*std.Build.Module = null; var ts_queries_opts: ?*std.Build.Step.Options = null; - var mupdf_core_mod: ?*std.Build.Module = null; var ghostty_core_vt: ?*std.Build.Module = null; var ts_libs: std.ArrayList(*std.Build.Step.Compile) = .empty; @@ -280,7 +275,6 @@ pub fn build(b: *std.Build) void { const shell_cfg: ShellConfig = .{ .tree_sitter_grammars = tree_sitter_grammars, .tracy = tracy != null, - .mupdf = enable_mupdf, .workspace_tag = workspace_tag, .prebuilt_shaders = prebuilt_shaders, .embed_sources = embed_sources, @@ -476,54 +470,50 @@ pub fn build(b: *std.Build) void { // hands back that same artifact rather than a second copy. const zlib = freetype_dep.builder.dependency("zlib", .{ .target = target, .optimize = c_optimize }).artifact("z"); + // The PDF addon (addons/pdf/pdf.c over MuPDF and pdf_bridge.c), built + // and installed as the image addon is. MuPDF is compiled against the + // build's FreeType and zlib and links them into the library, which holds + // its own copy of each beside a window's FreeType (docs/shared-libs.md); + // so all three are position-independent, and the library exports its + // `pardes_addon` alone. + var pdf_addon: ?*std.Build.Step.Compile = null; if (enable_mupdf) { if (b.lazyDependency("mupdf", .{})) |mupdf_dep| { + freetype.root_module.pic = true; + zlib.root_module.pic = true; const mupdf = mupdf_build.add(b, io, mupdf_dep, .{ .target = target, .optimize = c_optimize, .jpx = enable_jpx, .freetype = freetype, .zlib = zlib, + .pic = true, }); - // src/pdf.zig over this MuPDF: the core's, and pdf-bench's at - // ReleaseFast. - var pdf_mods: [2]*std.Build.Module = undefined; - for (&pdf_mods, [_]std.lang.Optimize{ optimize, .fast }) |*m, o| { - m.* = b.createModule(.{ .target = target, .optimize = o, .root_source_file = b.path("src/pdf.zig"), .link_libc = true }); - mupdf.linkTo(m.*); - m.*.addImport("c_heap", c_heap_mod); - m.*.addImport("pdf_c", b.addTranslateC(.{ .root_source_file = b.path("src/pdf_bridge.h"), .target = target, .optimize = o }).createModule()); - m.*.addIncludePath(b.path("src")); - m.*.addCSourceFile(.{ .file = b.path("src/pdf_bridge.c"), .flags = &.{"-std=gnu11"} }); - } - const mupdf_mod = pdf_mods[0]; - mupdf_core_mod = mupdf_mod; - const mupdf_test = b.addTest(.{ .root_module = mupdf_mod }); - const run_mupdf_test = b.addRunArtifact(mupdf_test); - run_mupdf_test.has_side_effects = true; - mupdf_check.dependOn(&run_mupdf_test.step); + const lib = b.addLibrary(.{ .name = "pdf", .linkage = .dynamic, .root_module = b.createModule(.{ .target = target, .optimize = c_optimize, .link_libc = true }) }); + mupdf.linkTo(lib.root_module); + lib.root_module.addIncludePath(b.path("src/kinds")); + lib.root_module.addIncludePath(b.path("addons/pdf")); + lib.root_module.addCSourceFile(.{ .file = b.path("addons/pdf/pdf.c"), .flags = &.{ "-std=gnu11", "-Wall", "-Wextra", "-Werror" } }); + lib.root_module.addCSourceFile(.{ .file = b.path("addons/pdf/pdf_bridge.c"), .flags = &.{"-std=gnu11"} }); + lib.setVersionScript(b.addWriteFiles().add("pdf.map", "{ global: pardes_addon; local: *; };\n")); + pdf_addon = lib; mupdf_check.dependOn(mupdf_build.addProbe(b, mupdf, .{ .target = target, .pdf = b.path("docs/design.pdf"), })); - // The PDF benches: pdf-bench MuPDF's own rendering at - // ReleaseFast, the others the core over it. + // The PDF benches: the core over the addon, a pane of it. const config = b.addOptions(); config.addOption(bool, "release_fast_core", optimize == .fast); config.addOption([]const u8, "core_optimize", @tagName(optimize)); - for ([_]struct { step: *std.Build.Step, exe: []const u8, file: []const u8, optimize: std.lang.Optimize, config: ?[]const u8 = null }{ - .{ .step = pdf_bench_step, .exe = "pardes-pdf-bench", .file = "test/pdf_bench.zig", .optimize = .fast }, - .{ .step = pdf_sections_bench_step, .exe = "pardes-pdf-sections-bench", .file = "test/pdf_sections_bench.zig", .optimize = .fast, .config = "pdf_sections_bench_config" }, + config.addOptionPath("pdf_addon", lib.getEmittedBin()); + for ([_]struct { step: *std.Build.Step, exe: []const u8, file: []const u8, optimize: std.lang.Optimize }{ .{ .step = pdf_pointer_bench_step, .exe = "pardes-pdf-pointer-bench", .file = "test/pdf_pointer_bench.zig", .optimize = .fast }, - .{ .step = pdf_scroll_bench_step, .exe = "pardes-pdf-scroll-bench", .file = "test/pdf_scroll_bench.zig", .optimize = optimize, .config = "pdf_scroll_bench_config" }, + .{ .step = pdf_scroll_bench_step, .exe = "pardes-pdf-scroll-bench", .file = "test/pdf_scroll_bench.zig", .optimize = optimize }, }) |bench| { const exe = b.addExecutable(.{ .name = bench.exe, .root_module = b.createModule(.{ .target = target, .optimize = bench.optimize, .root_source_file = b.path(bench.file), .link_libc = true }) }); - if (bench.step == pdf_bench_step) exe.root_module.addImport("mupdf", pdf_mods[1]) else { - exe.root_module.addImport("pardes", core_module); - exe.root_module.addImport("mupdf", mupdf_mod); - } - if (bench.config) |name| exe.root_module.addOptions(name, config); + exe.root_module.addImport("pardes", core_module); + exe.root_module.addOptions("pdf_bench_config", config); const run = b.addRunArtifact(exe); run.addPassthruArgs(); run.setCwd(b.path(".")); @@ -843,7 +833,6 @@ pub fn build(b: *std.Build) void { .zstbi = zstbi_mod, .mvzr = mvzr_mod, .c_heap = c_heap_mod, - .mupdf = mupdf_core_mod, .ghostty_vt = ghostty_core_vt, .vaxis = vaxis_mod, .uucode = uucode_mod, @@ -1135,14 +1124,16 @@ pub fn build(b: *std.Build) void { }); installHome(b, exe, home_bin); if (target.result.os.tag == .linux and !static) { - b.getInstallStep().dependOn(&b.addInstallFileWithDir(image_addon.getEmittedBin(), .lib, "pardes/addons/image.so").step); - if (home_bin) |dir| { - const copy = b.addSystemCommand(&.{ "install", "-Dm755" }); - copy.addFileArg(image_addon.getEmittedBin()); - copy.addArg(b.pathJoin(&.{ dir, "..", "lib", "pardes", "addons", "image.so" })); - copy.has_side_effects = true; - b.getInstallStep().dependOn(©.step); - } + for ([_]?*std.Build.Step.Compile{ image_addon, pdf_addon }, [_][]const u8{ "image.so", "pdf.so" }) |lib, name| if (lib) |l| { + b.getInstallStep().dependOn(&b.addInstallFileWithDir(l.getEmittedBin(), .lib, b.fmt("pardes/addons/{s}", .{name})).step); + if (home_bin) |dir| { + const copy = b.addSystemCommand(&.{ "install", "-Dm755" }); + copy.addFileArg(l.getEmittedBin()); + copy.addArg(b.pathJoin(&.{ dir, "..", "lib", "pardes", "addons", name })); + copy.has_side_effects = true; + b.getInstallStep().dependOn(©.step); + } + }; } if (gui_mod) |gm| { var gui_name: []const u8 = "pardes-gui"; @@ -1170,9 +1161,10 @@ pub fn build(b: *std.Build) void { iso_step.dependOn(&run_iso.step); } + const addons: []const *std.Build.Step.Compile = if (pdf_addon) |pdf| b.allocator.dupe(*std.Build.Step.Compile, &.{ image_addon, pdf }) catch @panic("OOM") else &.{image_addon}; snap_build.addTty(b, .{ .exe = exe, - .image_addon = image_addon, + .addons = addons, .target = target, .optimize = optimize, .ghostty_vt = ghostty_vt_for_snap, @@ -1236,12 +1228,13 @@ pub fn build(b: *std.Build) void { b.step("kitty-harness", "kitty graphics through a terminal pane end to end (a client inside, a kitty terminal or the GPU capture outside)").dependOn(&run_kitty_harness.step); const pdf_harness_step = b.step("pdf-harness", "exercise continuous PDF rendering, search, and sections navigation end to end"); - if (enable_mupdf) { + if (pdf_addon != null) { const run_pdf_harness = b.addRunArtifact(image_harness); run_pdf_harness.addArtifactArg(exe); run_pdf_harness.addArtifactArg(image_addon); run_pdf_harness.addArg(if (platform == .gui) "gui" else "tui"); run_pdf_harness.addArg("pdf"); + run_pdf_harness.addArtifactArg(pdf_addon.?); run_pdf_harness.has_side_effects = true; pdf_harness_step.dependOn(&run_pdf_harness.step); } else { @@ -1372,6 +1365,8 @@ pub fn build(b: *std.Build) void { .prebuilt_shaders = platform == .gui and prebuilt_shaders, }); perf_options.addOptionPath("image_addon", image_addon.getEmittedBin()); + perf_options.addOption(bool, "has_pdf_addon", pdf_addon != null); + if (pdf_addon) |l| perf_options.addOptionPath("pdf_addon", l.getEmittedBin()); const perf = b.addExecutable(.{ .name = "pardes-perf", .root_module = b.createModule(.{ @@ -1528,9 +1523,11 @@ pub fn build(b: *std.Build) void { pane_module.addImport("pardes_config", core_module.import_table.get("pardes_config").?); const test_addons = b.addOptions(); test_addons.addOptionPath("image", image_addon.getEmittedBin()); + test_addons.addOption(bool, "has_pdf", pdf_addon != null); + if (pdf_addon) |l| test_addons.addOptionPath("pdf", l.getEmittedBin()); pane_module.addOptions("test_addons", test_addons); const pane_tests = b.addTest(.{ .root_module = pane_module, .filters = test_filters }); - _ = units.add(b, pane_tests, b.step("pane-test", "run pane, output, PDF and namespace integration tests")); + _ = units.add(b, pane_tests, b.step("pane-test", "run pane, output and namespace integration tests")); // The behavioural tests (docs/next-tests.md): their module has the // session alone, so none can reach past what a 9P client sees. @@ -1572,6 +1569,8 @@ pub fn build(b: *std.Build) void { if (std.mem.eql(u8, variant[0], "fake_addon")) fake_addon_lib = lib; } session_options.addOptionPath("image_addon", image_addon.getEmittedBin()); + session_options.addOption(bool, "has_pdf_addon", pdf_addon != null); + if (pdf_addon) |l| session_options.addOptionPath("pdf_addon", l.getEmittedBin()); session_module.addOptions("session_options", session_options); const behaviour_module = b.createModule(.{ .target = target, @@ -1589,21 +1588,26 @@ pub fn build(b: *std.Build) void { // An addon's own test: `--addon-test` over the fake (the template) // and the snake (a shipped example, built but not installed), each // with its script, compared with what it printed when written. - const addon_test_step = b.step("addon-test", "pardes --addon-test over the fake and snake addons, against addons/*/*.out"); + const addon_test_step = b.step("addon-test", "pardes --addon-test over the fake, snake and pdf addons, against addons/*/*.out"); const snake_lib = b.addLibrary(.{ .name = "snake", .linkage = .dynamic, .root_module = b.createModule(.{ .target = target, .optimize = optimize, .link_libc = true }) }); snake_lib.root_module.addIncludePath(b.path("src/kinds")); snake_lib.root_module.addCSourceFile(.{ .file = b.path("addons/snake/snake.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } }); - for ([_]struct { *std.Build.Step.Compile, []const u8 }{ .{ fake_addon_lib.?, "addons/fake/fake" }, .{ snake_lib, "addons/snake/snake" } }) |t| { + // ...and the pdf addon's, which mupdf-check runs too (its script + // opens docs/design.pdf, from the build root). + const libs = [_]struct { ?*std.Build.Step.Compile, []const u8 }{ .{ fake_addon_lib.?, "addons/fake/fake" }, .{ snake_lib, "addons/snake/snake" }, .{ pdf_addon, "addons/pdf/pdf" } }; + for (libs) |t| if (t[0]) |lib| { const run_addon_test = b.addRunArtifact(exe); + run_addon_test.setCwd(b.path(".")); run_addon_test.addArg("--addon-test"); - run_addon_test.addArtifactArg(t[0]); + run_addon_test.addArtifactArg(lib); run_addon_test.addFileArg(b.path(b.fmt("{s}.script", .{t[1]}))); const compare = b.addSystemCommand(&.{ "diff", "-u" }); compare.addFileArg(b.path(b.fmt("{s}.out", .{t[1]}))); compare.addFileArg(run_addon_test.captureStdOut(.{})); behaviour_test_step.dependOn(&compare.step); addon_test_step.dependOn(&compare.step); - } + if (lib == pdf_addon) mupdf_check.dependOn(&compare.step); + }; // The 9P monkey at T1 (test/monkey9p.zig): random requests against // an in-process session, the documented rules checked after each. // Its fixed-seed smoke run is part of behaviour-test. @@ -1891,7 +1895,6 @@ fn gitCommit(b: *std.Build) ?[]const u8 { const ShellConfig = struct { tree_sitter_grammars: TreeSitterGrammars, tracy: bool, - mupdf: bool, /// null = "the platform's own default": the macOS shell hands the row to /// its native menu bar, every other shell keeps the acme topbar. workspace_tag: ?bool, @@ -1908,7 +1911,6 @@ fn shellOptions(b: *std.Build, cfg: ShellConfig, platform: Platform) *std.Build. o.addOption(bool, "syntax_minimal_grammars", cfg.tree_sitter_grammars == .minimal or cfg.tree_sitter_grammars == .full); o.addOption(bool, "syntax_full_grammars", cfg.tree_sitter_grammars == .full); o.addOption(bool, "enable_tracy", cfg.tracy); - o.addOption(bool, "mupdf", cfg.mupdf); o.addOption(bool, "workspace_tag", cfg.workspace_tag orelse (platform != .macos)); o.addOption(bool, "embed_sources", cfg.embed_sources); o.addOption([]const u8, "version", display_version); @@ -1973,7 +1975,6 @@ fn wireCore(m: *std.Build.Module, d: struct { zstbi: ?*std.Build.Module = null, mvzr: ?*std.Build.Module = null, c_heap: ?*std.Build.Module = null, - mupdf: ?*std.Build.Module = null, ghostty_vt: ?*std.Build.Module = null, vaxis: ?*std.Build.Module = null, uucode: ?*std.Build.Module = null, @@ -1988,7 +1989,6 @@ fn wireCore(m: *std.Build.Module, d: struct { if (d.zstbi) |x| m.addImport("zstbi", x); if (d.mvzr) |x| m.addImport("mvzr", x); if (d.c_heap) |x| m.addImport("c_heap", x); - if (d.mupdf) |x| m.addImport("mupdf", x); if (d.ghostty_vt) |x| m.addImport("ghostty-vt", x); if (d.vaxis) |x| m.addImport("vaxis", x); if (d.uucode) |x| m.addImport("uucode", x); diff --git a/build/snap.zig b/build/snap.zig index 981aec64..4f9b8f63 100644 --- a/build/snap.zig +++ b/build/snap.zig @@ -2,8 +2,9 @@ const std = @import("std"); pub fn addTty(b: *std.Build, opts: struct { exe: *std.Build.Step.Compile, - /// The image addon, which every session that opens a picture loads. - image_addon: *std.Build.Step.Compile, + /// The addons the build made (image, pdf), which every session loads: + /// each `--addon=`, linked into its data directory's addons. + addons: []const *std.Build.Step.Compile, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, ghostty_vt: ?*std.Build.Module, @@ -63,7 +64,7 @@ pub fn addTty(b: *std.Build, opts: struct { } const run_process_test = b.addRunArtifact(process_test); run_process_test.addArtifactArg(opts.exe); - run_process_test.addPrefixedFileArg("--image-addon=", opts.image_addon.getEmittedBin()); + for (opts.addons) |a| run_process_test.addPrefixedFileArg("--addon=", a.getEmittedBin()); run_process_test.addArg(if (opts.gui) "--backend=gui" else "--backend=tui"); run_process_test.addPassthruArgs(); run_process_test.has_side_effects = true; @@ -76,14 +77,14 @@ pub fn addTty(b: *std.Build, opts: struct { if (opts.gui) { const run_monkey_gui = b.addRunArtifact(process_test); run_monkey_gui.addArtifactArg(opts.exe); - run_monkey_gui.addPrefixedFileArg("--image-addon=", opts.image_addon.getEmittedBin()); + for (opts.addons) |a| run_monkey_gui.addPrefixedFileArg("--addon=", a.getEmittedBin()); run_monkey_gui.addArgs(&.{ "--backend=gui", "window: a monkey" }); run_monkey_gui.setEnvironmentVariable("PARDES_GUI_MONKEY", "all"); run_monkey_gui.has_side_effects = true; monkey_gui_step.dependOn(&run_monkey_gui.step); const run_gui_golden = b.addRunArtifact(process_test); run_gui_golden.addArtifactArg(opts.exe); - run_gui_golden.addPrefixedFileArg("--image-addon=", opts.image_addon.getEmittedBin()); + for (opts.addons) |a| run_gui_golden.addPrefixedFileArg("--addon=", a.getEmittedBin()); run_gui_golden.addArgs(&.{ "--backend=gui", "window: its scenes" }); run_gui_golden.setEnvironmentVariable("PARDES_GUI_GOLDEN", b.graph.environ_map.get("PARDES_GUI_GOLDEN") orelse "check"); run_gui_golden.setCwd(b.path(".")); @@ -96,7 +97,7 @@ pub fn addTty(b: *std.Build, opts: struct { const run_snap = b.addRunArtifact(snap); run_snap.addArtifactArg(opts.exe); run_snap.addPrefixedFileArg("--lspmock=", lspmock.getEmittedBin()); - run_snap.addPrefixedFileArg("--image-addon=", opts.image_addon.getEmittedBin()); + for (opts.addons) |a| run_snap.addPrefixedFileArg("--addon=", a.getEmittedBin()); run_snap.addPassthruArgs(); // scripts fork children and drive real ptys: never cached, never "up to date" run_snap.has_side_effects = true; diff --git a/mupdf.zig b/mupdf.zig index 761fef92..48dca46b 100644 --- a/mupdf.zig +++ b/mupdf.zig @@ -45,11 +45,14 @@ pub fn add(b: *std.Build, io: std.Io, dependency: *std.Build.Dependency, options /// one it bundles (ZLIB_SRC): the two define the same symbols, as the /// FreeTypes do. zlib: *std.Build.Step.Compile, + /// Position-independent, for a shared library (the pdf addon). + pic: ?bool = null, }) Result { const module = b.createModule(.{ .target = options.target, .optimize = options.optimize, .link_libc = true, + .pic = options.pic, }); configureModule(module, dependency, options.jpx); // MuPDF's upstream release build defines NDEBUG independently of the diff --git a/src/pdf_bridge.c b/src/pdf_bridge.c deleted file mode 100644 index 383e56fb..00000000 --- a/src/pdf_bridge.c +++ /dev/null @@ -1,1789 +0,0 @@ -#include "pdf_bridge.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#define PARDES_PDF_INITIAL_RESULT_QUADS 64 - -struct pardes_pdf_document { - pardes_pdf_allocator allocator; - fz_alloc_context mupdf_allocator; - int uses_allocator; - - fz_context *ctx; - fz_document *doc; - int page_count; - - /* - * Threads (pardes_pdf_lane_clone). A base document's context is made - * with MuPDF's locks, so it can be cloned; it owns the mutexes and the - * fz_buffer every lane opens its own fz_document from. A lane has - * `base` set and owns neither. - */ - pthread_mutex_t mutexes[FZ_LOCK_MAX]; - fz_locks_context locks; - fz_buffer *buffer; - pardes_pdf_document *base; - fz_cookie *cookie; - - /* One UI thread owns a document. Page switches invalidate this cache. */ - int cached_page_number; - fz_page *cached_page; - fz_stext_page *cached_text; - fz_display_list *cached_display_list; - fz_rect cached_bounds; - fz_link *cached_links; - int cached_links_loaded; - - /* Promote only a page which is rendered twice without changing pages. */ - int display_list_candidate_page_number; -}; - -_Static_assert(sizeof(pardes_pdf_cookie) == sizeof(fz_cookie) && - offsetof(pardes_pdf_cookie, abort) == offsetof(fz_cookie, abort) && - offsetof(pardes_pdf_cookie, progress_max) == offsetof(fz_cookie, progress_max) && - offsetof(pardes_pdf_cookie, incomplete) == offsetof(fz_cookie, incomplete), - "pardes_pdf_cookie must mirror fz_cookie"); - -static void -pardes_pdf_lock(void *user, int lock) -{ - pthread_mutex_lock(&((pthread_mutex_t *)user)[lock]); -} - -static void -pardes_pdf_unlock(void *user, int lock) -{ - pthread_mutex_unlock(&((pthread_mutex_t *)user)[lock]); -} - -static pardes_pdf_allocator pardes_pdf_global_allocator; -static int pardes_pdf_allocator_installed; -static _Atomic size_t pardes_pdf_active_documents; -static atomic_flag pardes_pdf_allocator_lock = ATOMIC_FLAG_INIT; - -static void -pardes_pdf_lock_allocator(void) -{ - while (atomic_flag_test_and_set_explicit( - &pardes_pdf_allocator_lock, memory_order_acquire)) - ; -} - -static void -pardes_pdf_unlock_allocator(void) -{ - atomic_flag_clear_explicit( - &pardes_pdf_allocator_lock, memory_order_release); -} - - -int -pardes_pdf_set_allocator(const pardes_pdf_allocator *allocator) -{ - int status = PARDES_PDF_OK; - - if (allocator != NULL && - (allocator->alloc == NULL || allocator->realloc == NULL || - allocator->free == NULL)) - return PARDES_PDF_ERROR; - - pardes_pdf_lock_allocator(); - if (atomic_load(&pardes_pdf_active_documents) != 0) { - status = PARDES_PDF_ERROR; - } else if (allocator == NULL) { - memset(&pardes_pdf_global_allocator, 0, - sizeof(pardes_pdf_global_allocator)); - pardes_pdf_allocator_installed = 0; - } else { - pardes_pdf_global_allocator = *allocator; - pardes_pdf_allocator_installed = 1; - } - pardes_pdf_unlock_allocator(); - return status; -} - -static pardes_pdf_document * -pardes_pdf_allocate_document(void) -{ - pardes_pdf_document *document; - pardes_pdf_allocator allocator; - int uses_allocator; - - pardes_pdf_lock_allocator(); - uses_allocator = pardes_pdf_allocator_installed; - allocator = pardes_pdf_global_allocator; - atomic_fetch_add(&pardes_pdf_active_documents, 1); - pardes_pdf_unlock_allocator(); - - if (uses_allocator) { - document = (pardes_pdf_document *)allocator.alloc( - allocator.user, sizeof(*document)); - } else { - document = (pardes_pdf_document *)calloc(1, sizeof(*document)); - } - if (document == NULL) { - atomic_fetch_sub(&pardes_pdf_active_documents, 1); - return NULL; - } - if (!uses_allocator) - return document; - - memset(document, 0, sizeof(*document)); - document->allocator = allocator; - document->uses_allocator = 1; - document->mupdf_allocator.user = allocator.user; - document->mupdf_allocator.malloc = allocator.alloc; - document->mupdf_allocator.realloc = allocator.realloc; - document->mupdf_allocator.free = allocator.free; - return document; -} - -static void -pardes_pdf_free_document(pardes_pdf_document *document) -{ - if (document->uses_allocator) - document->allocator.free(document->allocator.user, document); - else - free(document); -} - -static void -pardes_pdf_drop_cached_page(pardes_pdf_document *document) -{ - fz_drop_link(document->ctx, document->cached_links); - fz_drop_display_list(document->ctx, document->cached_display_list); - fz_drop_stext_page(document->ctx, document->cached_text); - fz_drop_page(document->ctx, document->cached_page); - document->cached_display_list = NULL; - document->cached_text = NULL; - document->cached_page = NULL; - document->cached_links = NULL; - document->cached_links_loaded = 0; - document->cached_page_number = -1; - document->display_list_candidate_page_number = -1; -} - -static int -pardes_pdf_valid_bounds(fz_rect bounds) -{ - return isfinite(bounds.x0) && isfinite(bounds.y0) && - isfinite(bounds.x1) && isfinite(bounds.y1) && - bounds.x1 > bounds.x0 && bounds.y1 > bounds.y0; -} - -/* - * Load into temporaries first, then replace the cache in one non-throwing - * commit. Thus a failed page/text load leaves the previous cached page valid. - */ -static void -pardes_pdf_cache_page( - pardes_pdf_document *document, - int page_number, - int require_text) -{ - fz_context *ctx = document->ctx; - fz_page *page = NULL; - fz_stext_page *text = NULL; - fz_rect bounds; - fz_stext_options options = {0}; - options.flags = FZ_STEXT_DEHYPHENATE; - - if (document->cached_page_number == page_number) { - if (require_text && document->cached_text == NULL) - document->cached_text = fz_new_stext_page_from_page( - ctx, document->cached_page, &options); - return; - } - - fz_var(page); - fz_var(text); - fz_try(ctx) - { - page = fz_load_page(ctx, document->doc, page_number); - bounds = fz_bound_page(ctx, page); - if (!pardes_pdf_valid_bounds(bounds)) - fz_throw(ctx, FZ_ERROR_FORMAT, "PDF page has empty bounds"); - if (require_text) - text = fz_new_stext_page_from_page(ctx, page, &options); - } - fz_catch(ctx) - { - fz_drop_stext_page(ctx, text); - fz_drop_page(ctx, page); - fz_rethrow(ctx); - } - - pardes_pdf_drop_cached_page(document); - document->cached_page_number = page_number; - document->cached_page = page; - document->cached_text = text; - document->cached_bounds = bounds; -} - -/* - * Build only after one successful direct render of the still-cached page. - * This keeps cold renders and sequential document passes on their original - * path instead of recording a list which the next page would immediately - * evict. The temporary list is committed only after its device has closed; - * any partially recorded list is dropped before the exception propagates. - */ -static void -pardes_pdf_cache_display_list(pardes_pdf_document *document) -{ - fz_context *ctx = document->ctx; - fz_display_list *list = NULL; - fz_device *device = NULL; - - if (document->cached_display_list != NULL) - return; - - fz_var(list); - fz_var(device); - fz_try(ctx) - { - list = fz_new_display_list(ctx, document->cached_bounds); - device = fz_new_list_device(ctx, list); - fz_run_page(ctx, document->cached_page, device, fz_identity, NULL); - fz_close_device(ctx, device); - } - fz_always(ctx) - { - fz_drop_device(ctx, device); - } - fz_catch(ctx) - { - fz_drop_display_list(ctx, list); - fz_rethrow(ctx); - } - - document->cached_display_list = list; -} - -static float -pardes_pdf_clamp_unit(float value) -{ - if (value < 0.0f) - return 0.0f; - if (value > 1.0f) - return 1.0f; - return value; -} - -static int -pardes_pdf_valid_point(pardes_pdf_point point) -{ - return isfinite(point.x) && isfinite(point.y); -} - -static fz_point -pardes_pdf_point_to_page(pardes_pdf_document *document, pardes_pdf_point point) -{ - fz_rect bounds = document->cached_bounds; - float x = pardes_pdf_clamp_unit(point.x); - float y = pardes_pdf_clamp_unit(point.y); - return fz_make_point( - bounds.x0 + x * (bounds.x1 - bounds.x0), - bounds.y0 + y * (bounds.y1 - bounds.y0)); -} - -static pardes_pdf_point -pardes_pdf_point_from_page(pardes_pdf_document *document, fz_point point) -{ - fz_rect bounds = document->cached_bounds; - pardes_pdf_point result; - result.x = pardes_pdf_clamp_unit( - (point.x - bounds.x0) / (bounds.x1 - bounds.x0)); - result.y = pardes_pdf_clamp_unit( - (point.y - bounds.y0) / (bounds.y1 - bounds.y0)); - return result; -} - -static pardes_pdf_quad -pardes_pdf_quad_from_page(pardes_pdf_document *document, fz_quad quad) -{ - pardes_pdf_quad result; - result.ul = pardes_pdf_point_from_page(document, quad.ul); - result.ur = pardes_pdf_point_from_page(document, quad.ur); - result.ll = pardes_pdf_point_from_page(document, quad.ll); - result.lr = pardes_pdf_point_from_page(document, quad.lr); - return result; -} - -static int -pardes_pdf_valid_quad(pardes_pdf_quad quad) -{ - return pardes_pdf_valid_point(quad.ul) && - pardes_pdf_valid_point(quad.ur) && - pardes_pdf_valid_point(quad.ll) && - pardes_pdf_valid_point(quad.lr); -} - -static fz_quad -pardes_pdf_quad_to_page(pardes_pdf_document *document, pardes_pdf_quad quad) -{ - fz_quad result; - result.ul = pardes_pdf_point_to_page(document, quad.ul); - result.ur = pardes_pdf_point_to_page(document, quad.ur); - result.ll = pardes_pdf_point_to_page(document, quad.ll); - result.lr = pardes_pdf_point_to_page(document, quad.lr); - return result; -} - -static size_t -pardes_pdf_grown_capacity(size_t current, size_t needed, size_t maximum) -{ - size_t capacity = current == 0 ? PARDES_PDF_INITIAL_RESULT_QUADS : current; - while (capacity < needed) { - if (capacity > maximum / 2) { - capacity = maximum; - break; - } - capacity *= 2; - } - return capacity; -} - -/* - * MuPDF's first page lookup loads a map of EVERY page object (the page tree - * flattened, each page's dictionary parsed out of its object stream): the - * SDM's 5363 took 735 ms in Debug, the first page's size alone. Walking the - * tree by its /Count for each lookup loads only the nodes on the way. - */ -static void -pardes_pdf_walk_page_tree(fz_context *ctx, fz_document *doc) -{ - pdf_document *pdf = pdf_specifics(ctx, doc); - if (pdf != NULL) - pdf_set_page_tree_cache(ctx, pdf, 0); -} - -pardes_pdf_document * -pardes_pdf_open_memory(const unsigned char *bytes, size_t length, int *page_count) -{ - pardes_pdf_document *state; - fz_context *ctx; - fz_document *doc = NULL; - fz_buffer *buffer = NULL; - fz_stream *stream = NULL; - int pages = 0; - - if (bytes == NULL || page_count == NULL) - return NULL; - - state = pardes_pdf_allocate_document(); - if (state == NULL) - return NULL; - state->cached_page_number = -1; - state->display_list_candidate_page_number = -1; - for (int i = 0; i < FZ_LOCK_MAX; ++i) - pthread_mutex_init(&state->mutexes[i], NULL); - state->locks.user = state->mutexes; - state->locks.lock = pardes_pdf_lock; - state->locks.unlock = pardes_pdf_unlock; - - ctx = fz_new_context( - state->uses_allocator ? &state->mupdf_allocator : NULL, - &state->locks, - PARDES_PDF_STORE_LIMIT_BYTES); - if (ctx == NULL) { - for (int i = 0; i < FZ_LOCK_MAX; ++i) - pthread_mutex_destroy(&state->mutexes[i]); - pardes_pdf_free_document(state); - atomic_fetch_sub(&pardes_pdf_active_documents, 1); - return NULL; - } - - fz_var(doc); - fz_var(buffer); - fz_var(stream); - fz_try(ctx) - { - fz_register_document_handlers(ctx); - buffer = fz_new_buffer_from_copied_data(ctx, bytes, length); - stream = fz_open_buffer(ctx, buffer); - doc = fz_open_document_with_stream(ctx, "application/pdf", stream); - pardes_pdf_walk_page_tree(ctx, doc); - pages = fz_count_pages(ctx, doc); - if (pages < 1) - fz_throw(ctx, FZ_ERROR_FORMAT, "PDF has no pages"); - } - fz_always(ctx) - { - fz_drop_stream(ctx, stream); - } - fz_catch(ctx) - { - fz_report_error(ctx); - fz_drop_document(ctx, doc); - fz_drop_buffer(ctx, buffer); - fz_drop_context(ctx); - for (int i = 0; i < FZ_LOCK_MAX; ++i) - pthread_mutex_destroy(&state->mutexes[i]); - pardes_pdf_free_document(state); - atomic_fetch_sub(&pardes_pdf_active_documents, 1); - return NULL; - } - - state->ctx = ctx; - state->doc = doc; - state->buffer = buffer; - state->page_count = pages; - *page_count = pages; - return state; -} - -void -pardes_pdf_close(pardes_pdf_document *document) -{ - if (document == NULL) - return; - pardes_pdf_drop_cached_page(document); - fz_drop_document(document->ctx, document->doc); - if (document->base == NULL) - fz_drop_buffer(document->ctx, document->buffer); - fz_drop_context(document->ctx); - if (document->base == NULL) - for (int i = 0; i < FZ_LOCK_MAX; ++i) - pthread_mutex_destroy(&document->mutexes[i]); - pardes_pdf_free_document(document); - atomic_fetch_sub(&pardes_pdf_active_documents, 1); -} - -pardes_pdf_document * -pardes_pdf_lane_clone(pardes_pdf_document *base) -{ - pardes_pdf_document *lane; - - if (base == NULL || base->base != NULL) - return NULL; - lane = pardes_pdf_allocate_document(); - if (lane == NULL) - return NULL; - lane->ctx = fz_clone_context(base->ctx); - if (lane->ctx == NULL) { - pardes_pdf_free_document(lane); - atomic_fetch_sub(&pardes_pdf_active_documents, 1); - return NULL; - } - lane->base = base; - lane->page_count = base->page_count; - lane->cached_page_number = -1; - lane->display_list_candidate_page_number = -1; - return lane; -} - -/* - * The lane's own document, from the base's bytes: parsed again (the xref, - * the page tree), never shared, so the lane's thread is the only one in it. - * The fz_buffer's count is kept under the shared alloc lock. - */ -int -pardes_pdf_lane_open(pardes_pdf_document *lane) -{ - fz_context *ctx; - fz_stream *stream = NULL; - fz_document *doc = NULL; - - if (lane == NULL || lane->base == NULL) - return PARDES_PDF_ERROR; - if (lane->doc != NULL) - return PARDES_PDF_OK; - ctx = lane->ctx; - fz_var(stream); - fz_var(doc); - fz_try(ctx) - { - stream = fz_open_buffer(ctx, lane->base->buffer); - doc = fz_open_document_with_stream(ctx, "application/pdf", stream); - pardes_pdf_walk_page_tree(ctx, doc); - if (fz_count_pages(ctx, doc) != lane->page_count) - fz_throw(ctx, FZ_ERROR_FORMAT, "PDF lane counts other pages"); - } - fz_always(ctx) - fz_drop_stream(ctx, stream); - fz_catch(ctx) - { - fz_report_error(ctx); - fz_drop_document(ctx, doc); - return PARDES_PDF_ERROR; - } - lane->doc = doc; - return PARDES_PDF_OK; -} - -void -pardes_pdf_set_cookie(pardes_pdf_document *document, pardes_pdf_cookie *cookie) -{ - if (document != NULL) - document->cookie = (fz_cookie *)cookie; -} - -/* - * A page's SIZE, without building a page. - * - * fz_bound_page(fz_load_page(n)) is the obvious spelling and it is what this - * used to do, but fz_load_page builds a whole pdf_page: it resolves the page - * dictionary, then loads and parses every link annotation on it. Laying out a - * 5363-page manual's strip asks for 5363 sizes, and profiling an open showed - * pdf_load_link_annots alone at 29% of the run — parsing links for pages - * nobody has looked at yet, to answer a question about their height. - * - * The page OBJECT answers it directly, and identically: fz_bound_page on a PDF - * is pdf_bound_page(FZ_CROP_BOX), which is pdf_page_obj_transform_box on - * page->obj followed by fz_transform_rect — exactly the two calls below, from - * exactly the same object. Non-PDF documents (cbz, xps, svg) have no page - * objects and keep the loading path. - */ -int -pardes_pdf_get_page_size( - pardes_pdf_document *document, - int page_number, - pardes_pdf_page_size *out) -{ - fz_context *ctx; - fz_rect bounds; - pdf_document *pdf; - - if (document == NULL || out == NULL || page_number < 0 || - page_number >= document->page_count) - return PARDES_PDF_ERROR; - - memset(out, 0, sizeof(*out)); - ctx = document->ctx; - fz_try(ctx) - { - pdf = pdf_specifics(ctx, document->doc); - if (pdf != NULL) { - fz_matrix page_ctm; - fz_rect cropbox; - pdf_obj *page_obj = pdf_lookup_page_obj(ctx, pdf, page_number); - pdf_page_obj_transform_box(ctx, page_obj, &cropbox, &page_ctm, - FZ_CROP_BOX); - bounds = fz_transform_rect(cropbox, page_ctm); - } else { - pardes_pdf_cache_page(document, page_number, 0); - bounds = document->cached_bounds; - } - out->width = bounds.x1 - bounds.x0; - out->height = bounds.y1 - bounds.y0; - if (!(out->width > 0.0f) || !(out->height > 0.0f)) - fz_throw(ctx, FZ_ERROR_FORMAT, "PDF page has empty bounds"); - } - fz_catch(ctx) - { - fz_report_error(ctx); - memset(out, 0, sizeof(*out)); - return PARDES_PDF_ERROR; - } - return PARDES_PDF_OK; -} - -/* Every size in range; zero minimums and display sizes are none. */ -static int -pardes_pdf_request_ok(const pardes_pdf_request *request) -{ - return request != NULL && request->dpi >= 1 && - request->minimum_width >= 0 && request->minimum_height >= 0 && - request->max_dimension >= 1 && - request->display_width >= 0 && request->display_height >= 0; -} - -static void -pardes_pdf_render_geometry( - pardes_pdf_document *document, - int page_number, - const pardes_pdf_request *request, - fz_matrix *ctm_out, - fz_irect *bbox_out) -{ - fz_rect transformed; - fz_rect bounds; - float page_width; - float page_height; - float scale; - float shown = 0.0f; - - pardes_pdf_cache_page(document, page_number, 0); - bounds = document->cached_bounds; - page_width = bounds.x1 - bounds.x0; - page_height = bounds.y1 - bounds.y0; - if (!(page_width > 0.0f) || !(page_height > 0.0f)) - fz_throw(document->ctx, FZ_ERROR_FORMAT, "PDF page has empty bounds"); - scale = (float)request->dpi / 72.0f; - if (request->minimum_width > 0) - scale = fmaxf(scale, (float)request->minimum_width / page_width); - if (request->minimum_height > 0) - scale = fmaxf(scale, (float)request->minimum_height / page_height); - /* - * A row of the raster is never longer than max_dimension: every band of - * the page carries whole rows. The height is held to it too, as the - * budget of one whole-page raster, but never below the scale the page is - * shown at: a page taller than that (a poster, a long web capture) is - * drawn in bands at the display's own resolution (pdf_view.zig) instead - * of being squeezed into max_dimension rows and blown up again, blurred. - */ - if (page_width * scale > (float)request->max_dimension) - scale = (float)request->max_dimension / page_width; - if (request->display_width > 0) - shown = fmaxf(shown, (float)request->display_width / page_width); - if (request->display_height > 0) - shown = fmaxf(shown, (float)request->display_height / page_height); - if (page_height * scale > (float)request->max_dimension) - scale = fminf(scale, fmaxf((float)request->max_dimension / page_height, shown)); - if (page_height * scale > (float)PARDES_PDF_MAX_RASTER_ROWS) - scale = (float)PARDES_PDF_MAX_RASTER_ROWS / page_height; - - /* - * Keep this identical to fz_new_pixmap_from_page/display_list: transform - * non-zero crop boxes to the origin, transform the bounds, then round the - * complete rectangle once. The same CTM also aligns highlight geometry. - */ - *ctm_out = fz_transform_page(bounds, scale * 72.0f, 0.0f); - transformed = fz_transform_rect(bounds, *ctm_out); - *bbox_out = fz_round_rect(transformed); - if (fz_irect_width(*bbox_out) < 1 || fz_irect_height(*bbox_out) < 1) - fz_throw(document->ctx, FZ_ERROR_FORMAT, "PDF page rendered empty"); -} - -int -pardes_pdf_measure_render( - pardes_pdf_document *document, - int page_number, - const pardes_pdf_request *request, - pardes_pdf_raster_layout *out) -{ - fz_context *ctx; - fz_matrix ctm; - fz_irect bbox; - int width = 0; - int height = 0; - int stride = 0; - size_t samples_len = 0; - - if (out == NULL) - return PARDES_PDF_ERROR; - memset(out, 0, sizeof(*out)); - if (document == NULL || page_number < 0 || - page_number >= document->page_count || !pardes_pdf_request_ok(request)) - return PARDES_PDF_ERROR; - - ctx = document->ctx; - fz_try(ctx) - { - pardes_pdf_render_geometry(document, page_number, request, &ctm, &bbox); - width = fz_irect_width(bbox); - height = fz_irect_height(bbox); - if (width > INT_MAX / 4) - fz_throw(ctx, FZ_ERROR_LIMIT, "PDF raster row is too large"); - stride = width * 4; - if ((size_t)height > SIZE_MAX / (size_t)stride) - fz_throw(ctx, FZ_ERROR_LIMIT, "PDF raster is too large"); - samples_len = (size_t)stride * (size_t)height; - } - fz_catch(ctx) - { - fz_report_error(ctx); - memset(out, 0, sizeof(*out)); - return PARDES_PDF_ERROR; - } - - out->width = width; - out->height = height; - out->stride = stride; - out->samples_len = samples_len; - return PARDES_PDF_OK; -} - -/* The highlight pass of a render: fills over whatever the pixmap holds. */ -static void -pardes_pdf_fill_highlights(fz_context *ctx, pardes_pdf_document *document, - fz_device *device, const pardes_pdf_highlight *highlights, size_t highlight_count) -{ - fz_path *path = NULL; - size_t i; - - fz_var(path); - fz_try(ctx) - { - for (i = 0; i < highlight_count; ++i) { - fz_quad quad; - float color[3]; - float alpha; - - if (!pardes_pdf_valid_quad(highlights[i].quad)) - fz_throw(ctx, FZ_ERROR_ARGUMENT, - "PDF highlight contains a non-finite point"); - if (highlights[i].rgba[3] == 0) - continue; - - /* Kind is semantic metadata; caller-supplied RGBA is final. */ - (void)highlights[i].kind; - quad = pardes_pdf_quad_to_page(document, highlights[i].quad); - color[0] = highlights[i].rgba[0] / 255.0f; - color[1] = highlights[i].rgba[1] / 255.0f; - color[2] = highlights[i].rgba[2] / 255.0f; - alpha = highlights[i].rgba[3] / 255.0f; - - path = fz_new_path(ctx); - fz_moveto(ctx, path, quad.ul.x, quad.ul.y); - fz_lineto(ctx, path, quad.ur.x, quad.ur.y); - fz_lineto(ctx, path, quad.lr.x, quad.lr.y); - fz_lineto(ctx, path, quad.ll.x, quad.ll.y); - fz_closepath(ctx, path); - fz_fill_path(ctx, device, path, 0, fz_identity, - fz_device_rgb(ctx), color, alpha, - fz_default_color_params); - fz_drop_path(ctx, path); - path = NULL; - } - } - fz_always(ctx) - fz_drop_path(ctx, path); - fz_catch(ctx) - fz_rethrow(ctx); -} - -int -pardes_pdf_render_into( - pardes_pdf_document *document, - int page_number, - const pardes_pdf_request *request, - const pardes_pdf_highlight *highlights, - size_t highlight_count, - unsigned char *samples, - size_t samples_len, - int width, - int height, - int stride, - int band_y, - int band_height, - int transparent_paper) -{ - fz_context *ctx; - fz_pixmap *pixmap = NULL; - fz_device *device = NULL; - fz_matrix ctm; - fz_irect bbox; - - if (document == NULL || page_number < 0 || - page_number >= document->page_count || !pardes_pdf_request_ok(request) || - (highlight_count != 0 && highlights == NULL) || - highlight_count > PARDES_PDF_MAX_RESULT_QUADS || samples == NULL || - width < 1 || height < 1 || stride < 1 || width > INT_MAX / 4 || - stride != width * 4 || band_y < 0 || band_height < 1 || - band_y > height - band_height || - (size_t)band_height > SIZE_MAX / (size_t)stride || - samples_len != (size_t)stride * (size_t)band_height) - return PARDES_PDF_ERROR; - - ctx = document->ctx; - fz_var(pixmap); - fz_var(device); - fz_try(ctx) - { - pardes_pdf_render_geometry(document, page_number, request, &ctm, &bbox); - if (fz_irect_width(bbox) != width || - fz_irect_height(bbox) != height) - fz_throw(ctx, FZ_ERROR_ARGUMENT, - "PDF raster layout changed between measure and render"); - /* - * The BAND: rows [band_y, band_y + band_height) of the page raster, - * and nothing else. A pixmap's bbox IS the draw device's clip, so the - * page runs under the same CTM it would for a full raster and MuPDF - * discards everything outside these rows. The rows are NOT always - * bit-identical to the full page's: rows at the band's edges, and a - * resampled image anywhere in it, can differ (measured on - * docs/registry.pdf and docs/design.pdf), and an edge crossing the - * clip is stepped from a different start along its whole length, - * a level or two off. Good enough for a band shown while flinging, - * and for the chunks of a page too tall to render whole (pdf_view.zig - * renders those past their edges and keeps the middle); never use a - * band to patch rows into a whole-page raster -- - * `pardes_pdf_paint_highlights` exists for that. - */ - bbox.y0 += band_y; - bbox.y1 = bbox.y0 + band_height; - - /* External samples are never marked FZ_PIXMAP_FLAG_FREE_SAMPLES. */ - pixmap = fz_new_pixmap_with_bbox_and_data( - ctx, fz_device_rgb(ctx), bbox, NULL, 1, samples); - if (fz_pixmap_samples(ctx, pixmap) != samples || - fz_pixmap_width(ctx, pixmap) != width || - fz_pixmap_height(ctx, pixmap) != band_height || - fz_pixmap_stride(ctx, pixmap) != stride || - fz_pixmap_components(ctx, pixmap) != 4) - fz_throw(ctx, FZ_ERROR_FORMAT, - "MuPDF wrapped an unexpected RGBA layout"); - /* - * ponytail: this memset is ~9% of a fast scroll's profile and it has - * twice measured as unremovable. Filling with 32-byte vector stores - * instead (a memset of a multi-megabyte raster goes out through - * non-temporal stores, 7.4 GB/s against 41.7 for a store loop) changed - * a fling's median frame by nothing at all, and skipping the fill - * ENTIRELY changed it by 1-2%: the cache misses it is blamed for are - * paid either way by the glyph spans and the tint pass that walk the - * same buffer immediately afterwards. Leave it alone. - */ - if (transparent_paper) fz_clear_pixmap(ctx, pixmap); - else fz_clear_pixmap_with_value(ctx, pixmap, 0xFF); - - if (document->cached_display_list != NULL || - document->display_list_candidate_page_number == page_number) { - /* - * Only the nodes that reach the band: a band of a tall page - * skips the rest of the page instead of handing every node to - * the draw device to clip away. The scissor is in page space - * (the list runs untransformed under the device's CTM), a pixel - * wider than the band all round. Culling never changes a pixel: - * a node outside it draws nothing here. - */ - fz_rect scissor = fz_rect_from_irect(bbox); - scissor.x0 -= 1; scissor.y0 -= 1; scissor.x1 += 1; scissor.y1 += 1; - scissor = fz_transform_rect(scissor, fz_invert_matrix(ctm)); - pardes_pdf_cache_display_list(document); - device = fz_new_draw_device(ctx, ctm, pixmap); - fz_run_display_list(ctx, document->cached_display_list, device, - fz_identity, scissor, document->cookie); - } else { - device = fz_new_draw_device(ctx, ctm, pixmap); - fz_run_page(ctx, document->cached_page, device, fz_identity, document->cookie); - } - fz_close_device(ctx, device); - fz_drop_device(ctx, device); - device = NULL; - - if (highlight_count != 0) { - device = fz_new_draw_device(ctx, ctm, pixmap); - pardes_pdf_fill_highlights(ctx, document, device, highlights, highlight_count); - fz_close_device(ctx, device); - } - } - fz_always(ctx) - { - fz_drop_device(ctx, device); - /* Drops only the wrapper: caller-owned samples remain untouched. */ - fz_drop_pixmap(ctx, pixmap); - } - fz_catch(ctx) - { - fz_report_error(ctx); - return PARDES_PDF_ERROR; - } - /* An aborted run returns as if done, over half a page: say so. */ - if (document->cookie != NULL && document->cookie->abort) - return PARDES_PDF_ABORTED; - - /* MuPDF draws premultiplied samples. The public RGBA contract and tint - * pass use straight alpha; preserve coverage and undo premultiplication. */ - if (transparent_paper) { - size_t pixel; - for (pixel = 0; pixel < samples_len; pixel += 4) { - unsigned int a = samples[pixel + 3]; - int channel; - if (a == 0 || a == 255) continue; - for (channel = 0; channel < 3; ++channel) { - unsigned int straight = (samples[pixel + channel] * 255u + a / 2) / a; - samples[pixel + channel] = (unsigned char)(straight > 255 ? 255 : straight); - } - } - } - - if (document->cached_display_list == NULL) - document->display_list_candidate_page_number = page_number; - - return PARDES_PDF_OK; -} - -int -pardes_pdf_paint_highlights( - pardes_pdf_document *document, - int page_number, - const pardes_pdf_request *request, - const pardes_pdf_highlight *highlights, - size_t highlight_count, - unsigned char *samples, - size_t samples_len, - int width, - int height, - int stride, - int band_y, - int band_height) -{ - fz_context *ctx; - fz_pixmap *pixmap = NULL; - fz_device *device = NULL; - fz_matrix ctm; - fz_irect bbox; - - if (document == NULL || page_number < 0 || - page_number >= document->page_count || !pardes_pdf_request_ok(request) || - (highlight_count != 0 && highlights == NULL) || - highlight_count > PARDES_PDF_MAX_RESULT_QUADS || samples == NULL || - width < 1 || height < 1 || width > INT_MAX / 4 || stride != width * 4 || - band_y < 0 || band_height < 1 || band_y > height - band_height || - (size_t)band_height > SIZE_MAX / (size_t)stride || - samples_len != (size_t)stride * (size_t)band_height) - return PARDES_PDF_ERROR; - if (highlight_count == 0) - return PARDES_PDF_OK; - - ctx = document->ctx; - fz_var(pixmap); - fz_var(device); - fz_try(ctx) - { - pardes_pdf_render_geometry(document, page_number, request, &ctm, &bbox); - if (fz_irect_width(bbox) != width || fz_irect_height(bbox) != height) - fz_throw(ctx, FZ_ERROR_ARGUMENT, - "PDF raster layout changed between measure and paint"); - bbox.y0 += band_y; - bbox.y1 = bbox.y0 + band_height; - pixmap = fz_new_pixmap_with_bbox_and_data( - ctx, fz_device_rgb(ctx), bbox, NULL, 1, samples); - device = fz_new_draw_device(ctx, ctm, pixmap); - pardes_pdf_fill_highlights(ctx, document, device, highlights, highlight_count); - fz_close_device(ctx, device); - } - fz_always(ctx) - { - fz_drop_device(ctx, device); - fz_drop_pixmap(ctx, pixmap); - } - fz_catch(ctx) - { - fz_report_error(ctx); - return PARDES_PDF_ERROR; - } - return PARDES_PDF_OK; -} - -int -pardes_pdf_highlight_rows( - pardes_pdf_document *document, - int page_number, - const pardes_pdf_request *request, - const pardes_pdf_highlight *highlights, - size_t highlight_count, - int *row_start, - int *row_end) -{ - fz_context *ctx; - fz_matrix ctm; - fz_irect bbox; - float y0 = 0, y1 = 0; - int any = 0; - size_t i; - - if (row_start == NULL || row_end == NULL) - return PARDES_PDF_ERROR; - *row_start = *row_end = 0; - if (document == NULL || page_number < 0 || - page_number >= document->page_count || !pardes_pdf_request_ok(request) || - (highlight_count != 0 && highlights == NULL)) - return PARDES_PDF_ERROR; - - ctx = document->ctx; - fz_try(ctx) - { - pardes_pdf_render_geometry(document, page_number, request, &ctm, &bbox); - for (i = 0; i < highlight_count; ++i) { - fz_rect r; - if (highlights[i].rgba[3] == 0 || - !pardes_pdf_valid_quad(highlights[i].quad)) - continue; - r = fz_rect_from_quad(fz_transform_quad( - pardes_pdf_quad_to_page(document, highlights[i].quad), ctm)); - if (!any || r.y0 < y0) y0 = r.y0; - if (!any || r.y1 > y1) y1 = r.y1; - any = 1; - } - } - fz_catch(ctx) - { - fz_report_error(ctx); - return PARDES_PDF_ERROR; - } - if (any) { - /* - * Antialiasing covers the pixel a fractional edge falls in, and the - * rasterizer paints row floor(y1) even for a zero-height quad. - */ - int lo = (int)floorf(y0) - bbox.y0; - int hi = (int)floorf(y1) + 1 - bbox.y0; - int h = fz_irect_height(bbox); - *row_start = lo < 0 ? 0 : (lo > h ? h : lo); - *row_end = hi < *row_start ? *row_start : (hi > h ? h : hi); - } - return PARDES_PDF_OK; -} - -/* A page's text, a line of it a line of the result: MuPDF's own buffer - * joins a block's lines with spaces, which ran a heading into the - * paragraph under it. Structure blocks are walked into. */ -static void -pardes_append_stext_blocks(fz_context *ctx, fz_buffer *buffer, fz_stext_block *block) -{ - for (; block != NULL; block = block->next) - { - if (block->type == FZ_STEXT_BLOCK_STRUCT) - { - if (block->u.s.down != NULL) - pardes_append_stext_blocks(ctx, buffer, block->u.s.down->first_block); - continue; - } - if (block->type != FZ_STEXT_BLOCK_TEXT) - continue; - for (fz_stext_line *line = block->u.t.first_line; line != NULL; line = line->next) - { - for (fz_stext_char *ch = line->first_char; ch != NULL; ch = ch->next) - fz_append_rune(ctx, buffer, ch->c); - fz_append_byte(ctx, buffer, '\n'); - } - } -} - -int -pardes_pdf_page_text( - pardes_pdf_document *document, - int page_number, - pardes_pdf_text *out) -{ - fz_context *ctx; - fz_buffer *buffer = NULL; - unsigned char *data = NULL; - size_t len = 0; - - if (document == NULL || out == NULL || page_number < 0 || - page_number >= document->page_count) - return PARDES_PDF_ERROR; - - memset(out, 0, sizeof(*out)); - ctx = document->ctx; - fz_var(buffer); - fz_try(ctx) - { - pardes_pdf_cache_page(document, page_number, 1); - buffer = fz_new_buffer(ctx, 1024); - pardes_append_stext_blocks(ctx, buffer, document->cached_text->first_block); - len = fz_buffer_storage(ctx, buffer, &data); - } - fz_catch(ctx) - { - fz_report_error(ctx); - fz_drop_buffer(ctx, buffer); - return PARDES_PDF_ERROR; - } - - out->handle = buffer; - out->data = data; - out->len = len; - return PARDES_PDF_OK; -} - -void -pardes_pdf_drop_text(pardes_pdf_document *document, void *buffer) -{ - if (document != NULL && buffer != NULL) - fz_drop_buffer(document->ctx, (fz_buffer *)buffer); -} - -int -pardes_pdf_search_page( - pardes_pdf_document *document, - int page_number, - const char *needle, - pardes_pdf_search_result *out) -{ - fz_context *ctx; - fz_search *search = NULL; - pardes_pdf_search_quad *items = NULL; - size_t capacity = 0; - size_t quad_count = 0; - size_t hit_count = 0; - int status = PARDES_PDF_ERROR; - - if (document == NULL || needle == NULL || out == NULL || page_number < 0 || - page_number >= document->page_count) - return PARDES_PDF_ERROR; - - memset(out, 0, sizeof(*out)); - ctx = document->ctx; - fz_var(search); - fz_var(items); - fz_var(status); - fz_try(ctx) - { - pardes_pdf_cache_page(document, page_number, 1); - search = fz_new_search(ctx); - fz_search_set_options( - ctx, search, FZ_SEARCH_IGNORE_CASE, needle); - - /* fz_feed_search takes ownership; retain the document's cache ref. */ - fz_feed_search(ctx, search, - fz_keep_stext_page(ctx, document->cached_text), page_number); - - for (;;) { - fz_search_result result = fz_search_forwards(ctx, search); - if (result.reason == FZ_SEARCH_COMPLETE) - break; - if (result.reason == FZ_SEARCH_MORE_INPUT) { - /* This is deliberately a one-page search. */ - fz_feed_search(ctx, search, NULL, - result.u.more_input.seq_needed); - continue; - } - if (result.reason == FZ_SEARCH_MATCH) { - fz_search_result_details *details = result.u.match.result; - size_t match_quads; - size_t needed; - size_t next_capacity; - size_t i; - - if (details == NULL || details->num_quads < 0 || - (details->num_quads > 0 && details->quads == NULL)) - fz_throw(ctx, FZ_ERROR_FORMAT, - "MuPDF returned malformed search geometry"); - if (hit_count >= PARDES_PDF_MAX_RESULT_QUADS) { - status = PARDES_PDF_LIMIT_EXCEEDED; - fz_throw(ctx, FZ_ERROR_LIMIT, - "PDF search result limit exceeded"); - } - - match_quads = (size_t)details->num_quads; - if (match_quads > PARDES_PDF_MAX_RESULT_QUADS - quad_count) { - status = PARDES_PDF_LIMIT_EXCEEDED; - fz_throw(ctx, FZ_ERROR_LIMIT, - "PDF search quad limit exceeded"); - } - needed = quad_count + match_quads; - if (needed > capacity) { - next_capacity = pardes_pdf_grown_capacity( - capacity, needed, PARDES_PDF_MAX_RESULT_QUADS); - items = fz_realloc_array( - ctx, items, next_capacity, pardes_pdf_search_quad); - capacity = next_capacity; - } - for (i = 0; i < match_quads; ++i) { - items[quad_count + i].quad = pardes_pdf_quad_from_page( - document, details->quads[i].quad); - items[quad_count + i].hit = hit_count; - } - quad_count = needed; - ++hit_count; - continue; - } - fz_throw(ctx, FZ_ERROR_FORMAT, - "MuPDF returned an unknown search state"); - } - status = PARDES_PDF_OK; - } - fz_always(ctx) - { - fz_drop_search(ctx, search); - } - fz_catch(ctx) - { - if (status != PARDES_PDF_LIMIT_EXCEEDED) - fz_report_error(ctx); - fz_free(ctx, items); - return status; - } - - out->handle = items; - out->quads = items; - out->quad_count = quad_count; - out->hit_count = hit_count; - return PARDES_PDF_OK; -} - -void -pardes_pdf_drop_search_result(pardes_pdf_document *document, void *result) -{ - if (document != NULL && result != NULL) - fz_free(document->ctx, result); -} - -int -pardes_pdf_select( - pardes_pdf_document *document, - int page_number, - pardes_pdf_point start, - pardes_pdf_point end, - pardes_pdf_selection *out) -{ - fz_context *ctx; - fz_quad *raw = NULL; - pardes_pdf_quad *items = NULL; - fz_point a; - fz_point b; - int capacity = PARDES_PDF_INITIAL_RESULT_QUADS; - int count = 0; - int status = PARDES_PDF_ERROR; - int i; - - if (document == NULL || out == NULL || page_number < 0 || - page_number >= document->page_count || - !pardes_pdf_valid_point(start) || !pardes_pdf_valid_point(end)) - return PARDES_PDF_ERROR; - - memset(out, 0, sizeof(*out)); - ctx = document->ctx; - fz_var(raw); - fz_var(items); - fz_var(status); - fz_try(ctx) - { - pardes_pdf_cache_page(document, page_number, 1); - a = pardes_pdf_point_to_page(document, start); - b = pardes_pdf_point_to_page(document, end); - (void)fz_snap_selection( - ctx, document->cached_text, &a, &b, FZ_SELECT_WORDS); - - raw = fz_malloc_array(ctx, capacity, fz_quad); - for (;;) { - int next_capacity; - count = fz_highlight_selection( - ctx, document->cached_text, a, b, raw, capacity); - if (count < 0) - fz_throw(ctx, FZ_ERROR_FORMAT, - "MuPDF returned an invalid selection count"); - if (count < capacity) - break; - - /* One extra slot distinguishes exactly-at-limit from truncation. */ - if (capacity >= PARDES_PDF_MAX_RESULT_QUADS + 1) { - status = PARDES_PDF_LIMIT_EXCEEDED; - fz_throw(ctx, FZ_ERROR_LIMIT, - "PDF selection quad limit exceeded"); - } - next_capacity = capacity * 2; - if (next_capacity > PARDES_PDF_MAX_RESULT_QUADS + 1) - next_capacity = PARDES_PDF_MAX_RESULT_QUADS + 1; - raw = fz_realloc_array(ctx, raw, next_capacity, fz_quad); - capacity = next_capacity; - } - if (count > PARDES_PDF_MAX_RESULT_QUADS) { - status = PARDES_PDF_LIMIT_EXCEEDED; - fz_throw(ctx, FZ_ERROR_LIMIT, - "PDF selection quad limit exceeded"); - } - - if (count != 0) - items = fz_malloc_array(ctx, (size_t)count, pardes_pdf_quad); - for (i = 0; i < count; ++i) - items[i] = pardes_pdf_quad_from_page(document, raw[i]); - status = PARDES_PDF_OK; - } - fz_always(ctx) - { - fz_free(ctx, raw); - } - fz_catch(ctx) - { - if (status != PARDES_PDF_LIMIT_EXCEEDED) - fz_report_error(ctx); - fz_free(ctx, items); - return status; - } - - out->handle = items; - out->quads = items; - out->quad_count = (size_t)count; - out->start = pardes_pdf_point_from_page(document, a); - out->end = pardes_pdf_point_from_page(document, b); - return PARDES_PDF_OK; -} - -void -pardes_pdf_drop_selection(pardes_pdf_document *document, void *selection) -{ - if (document != NULL && selection != NULL) - fz_free(document->ctx, selection); -} - -int -pardes_pdf_point_inside_quad(pardes_pdf_point point, pardes_pdf_quad quad) -{ - fz_quad native; - - if (!pardes_pdf_valid_point(point) || !pardes_pdf_valid_quad(quad)) - return 0; - native.ul = fz_make_point(quad.ul.x, quad.ul.y); - native.ur = fz_make_point(quad.ur.x, quad.ur.y); - native.ll = fz_make_point(quad.ll.x, quad.ll.y); - native.lr = fz_make_point(quad.lr.x, quad.lr.y); - return fz_is_point_inside_quad( - fz_make_point(point.x, point.y), native) != 0; -} - -int -pardes_pdf_link_at( - pardes_pdf_document *document, - int page_number, - pardes_pdf_point point, - pardes_pdf_link *out) -{ - fz_context *ctx; - - if (out == NULL) - return PARDES_PDF_ERROR; - memset(out, 0, sizeof(*out)); - out->page = -1; - if (document == NULL || page_number < 0 || - page_number >= document->page_count) - return PARDES_PDF_ERROR; - if (!pardes_pdf_valid_point(point) || point.x < 0 || point.x > 1 || - point.y < 0 || point.y > 1) - return PARDES_PDF_OK; - - ctx = document->ctx; - fz_try(ctx) - { - fz_link *link; - fz_point page_point; - pardes_pdf_cache_page(document, page_number, 0); - if (!document->cached_links_loaded) { - document->cached_links = fz_load_links(ctx, document->cached_page); - document->cached_links_loaded = 1; - } - page_point = pardes_pdf_point_to_page(document, point); - for (link = document->cached_links; link != NULL; link = link->next) { - size_t len; - int destination_kind; - int destination_page = -1; - fz_link_dest destination = fz_make_link_dest_none(); - if (!pardes_pdf_valid_bounds(link->rect) || - !fz_is_point_inside_rect(page_point, link->rect) || - link->uri == NULL || link->uri[0] == 0) - continue; - for (len = 0; len <= PARDES_PDF_MAX_LINK_URI_BYTES && - link->uri[len] != 0; ++len) - ; - if (len > PARDES_PDF_MAX_LINK_URI_BYTES) - continue; - destination_kind = PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL; - if (!fz_is_external_link(ctx, link->uri)) { - destination = fz_resolve_link_dest(ctx, document->doc, link->uri); - if (destination.loc.chapter >= 0 && destination.loc.page >= 0) - destination_page = fz_page_number_from_location( - ctx, document->doc, destination.loc); - if (destination_page >= 0 && destination_page < document->page_count) - destination_kind = PARDES_PDF_OUTLINE_DESTINATION_INTERNAL; - else if (link->uri[0] == '#') - continue; - } - out->quad = pardes_pdf_quad_from_page( - document, fz_quad_from_rect(link->rect)); - out->destination_kind = destination_kind; - if (destination_kind == PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) { - out->page = destination_page; - out->has_x = isfinite(destination.x); - out->has_y = isfinite(destination.y); - if (out->has_x) out->x = destination.x; - if (out->has_y) out->y = destination.y; - } - out->uri = (const unsigned char *)link->uri; - out->uri_len = len; - break; - } - } - fz_catch(ctx) - { - memset(out, 0, sizeof(*out)); - return PARDES_PDF_ERROR; - } - return PARDES_PDF_OK; -} - -int -pardes_pdf_copy_selection( - pardes_pdf_document *document, - int page_number, - pardes_pdf_point start, - pardes_pdf_point end, - pardes_pdf_owned_text *out) -{ - fz_context *ctx; - char *text = NULL; - fz_point a; - fz_point b; - - if (document == NULL || out == NULL || page_number < 0 || - page_number >= document->page_count || - !pardes_pdf_valid_point(start) || !pardes_pdf_valid_point(end)) - return PARDES_PDF_ERROR; - - memset(out, 0, sizeof(*out)); - ctx = document->ctx; - fz_var(text); - fz_try(ctx) - { - pardes_pdf_cache_page(document, page_number, 1); - a = pardes_pdf_point_to_page(document, start); - b = pardes_pdf_point_to_page(document, end); - text = fz_copy_selection(ctx, document->cached_text, a, b, 0); - } - fz_catch(ctx) - { - fz_report_error(ctx); - fz_free(ctx, text); - return PARDES_PDF_ERROR; - } - - out->handle = text; - out->data = (const unsigned char *)text; - out->len = text == NULL ? 0 : strlen(text); - return PARDES_PDF_OK; -} - -void -pardes_pdf_drop_owned_text(pardes_pdf_document *document, void *text) -{ - if (document != NULL && text != NULL) - fz_free(document->ctx, text); -} - -int -pardes_pdf_copy_rectangle( - pardes_pdf_document *document, - int page_number, - pardes_pdf_quad quad, - pardes_pdf_owned_text *out) -{ - fz_context *ctx; - char *text = NULL; - fz_quad native; - if (document == NULL || out == NULL || page_number < 0 || - page_number >= document->page_count || !pardes_pdf_valid_quad(quad)) - return PARDES_PDF_ERROR; - memset(out, 0, sizeof(*out)); - ctx = document->ctx; - fz_var(text); - fz_try(ctx) - { - pardes_pdf_cache_page(document, page_number, 1); - native.ul = pardes_pdf_point_to_page(document, quad.ul); - native.ur = pardes_pdf_point_to_page(document, quad.ur); - native.ll = pardes_pdf_point_to_page(document, quad.ll); - native.lr = pardes_pdf_point_to_page(document, quad.lr); - text = fz_copy_rectangle(ctx, document->cached_text, - fz_rect_from_quad(native), 0); - } - fz_catch(ctx) - { - fz_free(ctx, text); - return PARDES_PDF_ERROR; - } - out->handle = text; - out->data = (const unsigned char *)text; - out->len = text == NULL ? 0 : strlen(text); - return PARDES_PDF_OK; -} - -typedef struct pardes_pdf_outline_measurement { - size_t item_count; - size_t bytes_len; - int status; -} pardes_pdf_outline_measurement; - -static int -pardes_pdf_outline_destination(const fz_outline *node, fz_context *ctx) -{ - if (node->page.chapter >= 0 && node->page.page >= 0) - return PARDES_PDF_OUTLINE_DESTINATION_INTERNAL; - if (node->page.chapter >= 0 || node->page.page >= 0) - fz_throw(ctx, FZ_ERROR_FORMAT, - "PDF outline has a partially resolved destination"); - if (node->uri != NULL && fz_is_external_link(ctx, node->uri)) - return PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL; - return PARDES_PDF_OUTLINE_DESTINATION_NONE; -} - -static size_t -pardes_pdf_bounded_outline_string( - fz_context *ctx, - const char *value, - size_t remaining, - int *status) -{ - size_t len; - - if (value == NULL) - return 0; - len = strnlen(value, remaining + 1); - if (len > remaining) { - *status = PARDES_PDF_LIMIT_EXCEEDED; - fz_throw(ctx, FZ_ERROR_LIMIT, - "PDF outline metadata byte limit exceeded"); - } - return len; -} - -static void -pardes_pdf_measure_outline( - fz_context *ctx, - const fz_outline *node, - unsigned int depth, - pardes_pdf_outline_measurement *measurement) -{ - for (; node != NULL; node = node->next) { - size_t remaining; - int destination; - - if (depth >= PARDES_PDF_MAX_OUTLINE_DEPTH || - measurement->item_count >= PARDES_PDF_MAX_OUTLINE_ITEMS) { - measurement->status = PARDES_PDF_LIMIT_EXCEEDED; - fz_throw(ctx, FZ_ERROR_LIMIT, "PDF outline limit exceeded"); - } - ++measurement->item_count; - - remaining = PARDES_PDF_MAX_OUTLINE_BYTES - measurement->bytes_len; - measurement->bytes_len += pardes_pdf_bounded_outline_string( - ctx, node->title, remaining, &measurement->status); - - destination = pardes_pdf_outline_destination(node, ctx); - if (destination == PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL) { - remaining = PARDES_PDF_MAX_OUTLINE_BYTES - - measurement->bytes_len; - measurement->bytes_len += pardes_pdf_bounded_outline_string( - ctx, node->uri, remaining, &measurement->status); - } - - if (node->down != NULL) - pardes_pdf_measure_outline( - ctx, node->down, depth + 1, measurement); - } -} - -static void -pardes_pdf_flatten_outline( - pardes_pdf_document *document, - const fz_outline *node, - unsigned int depth, - pardes_pdf_outline_item *items, - unsigned char *bytes, - size_t item_count, - size_t bytes_len, - size_t *item_at, - size_t *byte_at) -{ - fz_context *ctx = document->ctx; - - for (; node != NULL; node = node->next) { - pardes_pdf_outline_item *item; - int destination; - size_t len; - - if (*item_at >= item_count) - fz_throw(ctx, FZ_ERROR_FORMAT, - "PDF outline changed while flattening"); - item = &items[(*item_at)++]; - memset(item, 0, sizeof(*item)); - item->depth = depth; - item->page = -1; - item->is_open = node->is_open != 0; - item->flags = (unsigned char)node->flags; - item->r = (unsigned char)node->r; - item->g = (unsigned char)node->g; - item->b = (unsigned char)node->b; - - if (node->title != NULL) { - len = strlen(node->title); - if (*byte_at > bytes_len || len > bytes_len - *byte_at) - fz_throw(ctx, FZ_ERROR_FORMAT, - "PDF outline title changed while flattening"); - item->title_present = 1; - item->title_offset = *byte_at; - item->title_len = len; - memcpy(bytes + *byte_at, node->title, len); - *byte_at += len; - } - - destination = pardes_pdf_outline_destination(node, ctx); - item->destination_kind = destination; - if (destination == PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) { - item->page = fz_page_number_from_location( - ctx, document->doc, node->page); - if (item->page < 0 || item->page >= document->page_count) - fz_throw(ctx, FZ_ERROR_FORMAT, - "PDF outline resolved outside the document"); - item->has_x = isfinite(node->x); - item->has_y = isfinite(node->y); - if (item->has_x) - item->x = node->x; - if (item->has_y) - item->y = node->y; - } else if (destination == PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL) { - len = strlen(node->uri); - if (*byte_at > bytes_len || len > bytes_len - *byte_at) - fz_throw(ctx, FZ_ERROR_FORMAT, - "PDF outline URI changed while flattening"); - item->uri_offset = *byte_at; - item->uri_len = len; - memcpy(bytes + *byte_at, node->uri, len); - *byte_at += len; - } - - if (node->down != NULL) - pardes_pdf_flatten_outline(document, node->down, depth + 1, - items, bytes, item_count, bytes_len, item_at, byte_at); - } -} - -static unsigned char -pardes_pdf_outline_color(fz_context *ctx, float value) -{ - if (!isfinite(value) || value < 0.0f || value > 255.0f) - fz_throw(ctx, FZ_ERROR_FORMAT, - "PDF outline has an invalid style color"); - return (unsigned char)(value + 0.5f); -} - -/* - * MuPDF 1.27's generic fz_load_outline adapter does not copy the iterator's - * style fields into fz_outline. Overlay them from a second, allocation-light - * iterator pass while retaining the loaded tree as the destination authority. - */ -static void -pardes_pdf_apply_outline_styles( - fz_context *ctx, - fz_outline_iterator *iterator, - unsigned int depth, - pardes_pdf_outline_item *items, - size_t item_count, - size_t *item_at) -{ - int moved; - - do { - fz_outline_item *style = fz_outline_iterator_item(ctx, iterator); - pardes_pdf_outline_item *item; - - if (style == NULL) - return; - if (*item_at >= item_count || items[*item_at].depth != depth || - style->flags < 0 || style->flags > 127) - fz_throw(ctx, FZ_ERROR_FORMAT, - "PDF outline changed while reading styles"); - item = &items[(*item_at)++]; - item->flags = (unsigned char)style->flags; - item->r = pardes_pdf_outline_color(ctx, style->r); - item->g = pardes_pdf_outline_color(ctx, style->g); - item->b = pardes_pdf_outline_color(ctx, style->b); - - moved = fz_outline_iterator_down(ctx, iterator); - if (moved == FZ_OUTLINE_ITERATOR_AT_ITEM) - pardes_pdf_apply_outline_styles(ctx, iterator, depth + 1, - items, item_count, item_at); - if (moved >= 0) - (void)fz_outline_iterator_up(ctx, iterator); - } while (fz_outline_iterator_next(ctx, iterator) == - FZ_OUTLINE_ITERATOR_AT_ITEM); -} - -int -pardes_pdf_load_outline( - pardes_pdf_document *document, - pardes_pdf_outline_result *out) -{ - fz_context *ctx; - fz_outline *outline = NULL; - fz_outline_iterator *iterator = NULL; - unsigned char *block = NULL; - pardes_pdf_outline_measurement measurement = {0}; - size_t item_bytes; - size_t total_bytes; - size_t item_at = 0; - size_t byte_at = 0; - size_t style_at = 0; - int status = PARDES_PDF_ERROR; - - if (document == NULL || out == NULL) - return PARDES_PDF_ERROR; - memset(out, 0, sizeof(*out)); - ctx = document->ctx; - measurement.status = PARDES_PDF_ERROR; - - fz_var(outline); - fz_var(iterator); - fz_var(block); - fz_var(measurement); - fz_var(status); - fz_try(ctx) - { - outline = fz_load_outline(ctx, document->doc); - pardes_pdf_measure_outline(ctx, outline, 0, &measurement); - if (measurement.item_count > - SIZE_MAX / sizeof(pardes_pdf_outline_item) || - measurement.bytes_len > SIZE_MAX - measurement.item_count * - sizeof(pardes_pdf_outline_item)) { - measurement.status = PARDES_PDF_LIMIT_EXCEEDED; - fz_throw(ctx, FZ_ERROR_LIMIT, - "PDF outline allocation size overflow"); - } - item_bytes = measurement.item_count * - sizeof(pardes_pdf_outline_item); - total_bytes = item_bytes + measurement.bytes_len; - if (total_bytes != 0) { - block = fz_malloc(ctx, total_bytes); - pardes_pdf_flatten_outline(document, outline, 0, - (pardes_pdf_outline_item *)block, block + item_bytes, - measurement.item_count, measurement.bytes_len, - &item_at, &byte_at); - if (item_at != measurement.item_count || - byte_at != measurement.bytes_len) - fz_throw(ctx, FZ_ERROR_FORMAT, - "PDF outline changed while flattening"); - iterator = fz_new_outline_iterator(ctx, document->doc); - if (iterator != NULL) { - pardes_pdf_apply_outline_styles(ctx, iterator, 0, - (pardes_pdf_outline_item *)block, - measurement.item_count, &style_at); - if (style_at != measurement.item_count) - fz_throw(ctx, FZ_ERROR_FORMAT, - "PDF outline changed while reading styles"); - } - } - status = PARDES_PDF_OK; - } - fz_always(ctx) - { - fz_drop_outline_iterator(ctx, iterator); - fz_drop_outline(ctx, outline); - } - fz_catch(ctx) - { - if (measurement.status != PARDES_PDF_LIMIT_EXCEEDED) - fz_report_error(ctx); - fz_free(ctx, block); - memset(out, 0, sizeof(*out)); - return measurement.status == PARDES_PDF_LIMIT_EXCEEDED ? - PARDES_PDF_LIMIT_EXCEEDED : PARDES_PDF_ERROR; - } - - out->handle = block; - out->items = (const pardes_pdf_outline_item *)block; - out->item_count = measurement.item_count; - out->bytes = block == NULL ? NULL : block + item_bytes; - out->bytes_len = measurement.bytes_len; - return status; -} - -void -pardes_pdf_drop_outline_result( - pardes_pdf_document *document, - void *outline) -{ - if (document != NULL && outline != NULL) - fz_free(document->ctx, outline); -} diff --git a/src/pdf_bridge.h b/src/pdf_bridge.h deleted file mode 100644 index 69678556..00000000 --- a/src/pdf_bridge.h +++ /dev/null @@ -1,399 +0,0 @@ -#ifndef PARDES_PDF_BRIDGE_H -#define PARDES_PDF_BRIDGE_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * MuPDF reports failures with setjmp/longjmp through fz_try/fz_catch. Those - * jumps must never cross Zig frames, so every operation that can throw lives - * behind this deliberately small C boundary. - */ -typedef struct pardes_pdf_document pardes_pdf_document; - -typedef void *(*pardes_pdf_alloc_fn)(void *user, size_t size); -typedef void *(*pardes_pdf_realloc_fn)( - void *user, - void *pointer, - size_t size -); -typedef void (*pardes_pdf_free_fn)(void *user, void *pointer); - -typedef struct pardes_pdf_allocator { - void *user; - pardes_pdf_alloc_fn alloc; - pardes_pdf_realloc_fn realloc; - pardes_pdf_free_fn free; -} pardes_pdf_allocator; - -/* - * Install one process-global allocator, or restore libc/default MuPDF - * allocation by passing NULL. Changing it while a document is live fails. - */ -int pardes_pdf_set_allocator(const pardes_pdf_allocator *allocator); - -typedef struct pardes_pdf_raster_layout { - int width; - int height; - int stride; - size_t samples_len; -} pardes_pdf_raster_layout; - -/* - * One raster request (pdf.zig's RenderRequest, bounded): every function - * that rasterizes a page, paints over it or measures it takes the same one - * and computes the same raster from it (see pardes_pdf_measure_render). - * Zero minimum or display sizes are none. - */ -typedef struct pardes_pdf_request { - int dpi; - int minimum_width; - int minimum_height; - int max_dimension; - int display_width; - int display_height; -} pardes_pdf_request; - -typedef struct pardes_pdf_page_size { - float width; - float height; -} pardes_pdf_page_size; - -typedef struct pardes_pdf_text { - void *handle; - const unsigned char *data; - size_t len; -} pardes_pdf_text; - -/* - * All geometry crossing this boundary is normalized to the cached page's - * bounds. (0,0) is the page's top-left and (1,1) its bottom-right, regardless - * of the DPI used for a particular render. Corner names retain MuPDF's quad - * orientation; callers must not collapse them to an axis-aligned rectangle. - */ -typedef struct pardes_pdf_point { - float x; - float y; -} pardes_pdf_point; - -typedef struct pardes_pdf_quad { - pardes_pdf_point ul; - pardes_pdf_point ur; - pardes_pdf_point ll; - pardes_pdf_point lr; -} pardes_pdf_quad; - -typedef enum pardes_pdf_highlight_kind { - PARDES_PDF_HIGHLIGHT_CUSTOM = 0, - PARDES_PDF_HIGHLIGHT_SEARCH = 1, - PARDES_PDF_HIGHLIGHT_SELECTION = 2 -} pardes_pdf_highlight_kind; - -typedef struct pardes_pdf_highlight { - pardes_pdf_quad quad; - unsigned char rgba[4]; - int kind; -} pardes_pdf_highlight; - -typedef struct pardes_pdf_search_quad { - pardes_pdf_quad quad; - size_t hit; -} pardes_pdf_search_quad; - -typedef struct pardes_pdf_search_result { - void *handle; - const pardes_pdf_search_quad *quads; - size_t quad_count; - size_t hit_count; -} pardes_pdf_search_result; - -typedef struct pardes_pdf_selection { - void *handle; - const pardes_pdf_quad *quads; - size_t quad_count; - pardes_pdf_point start; - pardes_pdf_point end; -} pardes_pdf_selection; - -typedef struct pardes_pdf_owned_text { - void *handle; - const unsigned char *data; - size_t len; -} pardes_pdf_owned_text; - -typedef enum pardes_pdf_outline_destination_kind { - PARDES_PDF_OUTLINE_DESTINATION_NONE = 0, - PARDES_PDF_OUTLINE_DESTINATION_INTERNAL = 1, - PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL = 2 -} pardes_pdf_outline_destination_kind; - -/* - * One pre-order depth-first row. Offsets address the result's byte arena; - * title_present distinguishes a missing title from a present empty title. - * Internal page numbers are zero-based. has_x/has_y preserve MuPDF's NAN - * sentinel for viewing coordinates that the outline destination omits. - */ -typedef struct pardes_pdf_outline_item { - size_t title_offset; - size_t title_len; - size_t uri_offset; - size_t uri_len; - unsigned int depth; - int page; - float x; - float y; - unsigned char title_present; - unsigned char has_x; - unsigned char has_y; - unsigned char is_open; - unsigned char flags; - unsigned char r; - unsigned char g; - unsigned char b; - int destination_kind; -} pardes_pdf_outline_item; - -typedef struct pardes_pdf_outline_result { - void *handle; - const pardes_pdf_outline_item *items; - size_t item_count; - const unsigned char *bytes; - size_t bytes_len; -} pardes_pdf_outline_result; - -/* URI borrows the current page's lazily loaded link list. Copy it before any - * other document operation. A NULL URI means the point has no usable link. */ -typedef struct pardes_pdf_link { - const unsigned char *uri; - size_t uri_len; - pardes_pdf_quad quad; - int destination_kind; - int page; - float x; - float y; - unsigned char has_x; - unsigned char has_y; -} pardes_pdf_link; - -enum { - PARDES_PDF_OK = 0, - PARDES_PDF_ERROR = -1, - PARDES_PDF_LIMIT_EXCEEDED = -2, - /* A render stopped early through its cookie (pardes_pdf_set_cookie). */ - PARDES_PDF_ABORTED = -3, - - /* Per-document MuPDF eviction cache; render buffers are separate. */ - PARDES_PDF_STORE_LIMIT_BYTES = 64 * 1024 * 1024, - - /* - * Search grows geometrically up to this aggregate count and then fails - * atomically with PARDES_PDF_LIMIT_EXCEEDED; it never returns a silently - * truncated result. Selection uses one extra private probe slot so an - * exact-at-the-limit result remains distinguishable from truncation. - */ - PARDES_PDF_MAX_RESULT_QUADS = 65536, - - /* Outline conversion is atomic: crossing any bound returns no rows. */ - PARDES_PDF_MAX_OUTLINE_ITEMS = 8192, - PARDES_PDF_MAX_OUTLINE_DEPTH = 64, - PARDES_PDF_MAX_OUTLINE_BYTES = 4 * 1024 * 1024, - PARDES_PDF_MAX_LINK_URI_BYTES = 64 * 1024, - - /* No page raster is taller than this, whatever it is shown at. */ - PARDES_PDF_MAX_RASTER_ROWS = 1 << 20 -}; - -pardes_pdf_document *pardes_pdf_open_memory(const unsigned char *bytes, size_t length, int *page_count); -void pardes_pdf_close(pardes_pdf_document *document); - -/* - * A render lane: a context cloned from `base`'s (fz_clone_context: the store, - * the allocator and the locks shared) and a document of its OWN, opened from - * the bytes `base` holds (the fz_buffer shared, read only). MuPDF allows one - * thread at a time in a context and in a document; a lane is used by one - * thread at a time and never shares either with `base` or another lane, so - * lanes render while `base` serves the UI thread. Clone on the thread that - * owns `base` (the clone reads its context); `pardes_pdf_lane_open` then runs - * on the lane's thread. Close every lane before `base`. NULL: no lane (out of - * memory). - */ -pardes_pdf_document *pardes_pdf_lane_clone(pardes_pdf_document *base); -int pardes_pdf_lane_open(pardes_pdf_document *lane); - -/* Mirrors fz_cookie (checked in the bridge): set `abort` nonzero from any - * thread and a render running under it stops at its next operator. */ -typedef struct pardes_pdf_cookie { - int abort; - int progress; - size_t progress_max; - int errors; - int incomplete; -} pardes_pdf_cookie; - -/* The cookie the document's renders run under (NULL: none), until set again. */ -void pardes_pdf_set_cookie(pardes_pdf_document *document, pardes_pdf_cookie *cookie); - -/* Page dimensions in PDF points after crop/rotation, without rasterizing. */ -int pardes_pdf_get_page_size( - pardes_pdf_document *document, - int page, - pardes_pdf_page_size *out -); - -/* - * Start at dpi, raise the uniform scale until both optional minimum pixel - * dimensions are met, then clamp the page's width to max_dimension, and its - * height too unless that would draw it smaller than the optional display size - * (the width or height it is shown at): a tall page is then as tall as it is - * shown, and its owner renders it in bands. Every function below takes the - * same request and computes the same raster from it. - * Measuring may populate the page cache, but never advances adaptive display - * list promotion; only a successful render_into does that. - */ -int pardes_pdf_measure_render( - pardes_pdf_document *document, - int page, - const pardes_pdf_request *request, - pardes_pdf_raster_layout *out -); - -/* - * Rasterize one horizontal BAND of a page — rows [band_y, band_y+band_height) - * of the raster `pardes_pdf_measure_render` describes — directly into an - * exactly-sized caller-owned packed RGBA buffer, `stride * band_height` bytes. - * A full page is the band `(0, height)`. - * - * MuPDF wraps but never owns or frees samples. Every successful pixel is - * opaque unless transparent_paper is nonzero. That mode preserves content - * coverage and returns straight-alpha RGBA over an unpainted page. - * The CTM does not depend on the band, so a band is a clip of the same - * rendering -- but not a bit-exact one: its edge rows and resampled images can - * differ from the whole page's (see pardes_pdf_render_into). - */ -int pardes_pdf_render_into( - pardes_pdf_document *document, - int page, - const pardes_pdf_request *request, - const pardes_pdf_highlight *highlights, - size_t highlight_count, - unsigned char *samples, - size_t samples_len, - int width, - int height, - int stride, - int band_y, - int band_height, - int transparent_paper -); - -/* - * The highlight pass of `pardes_pdf_render_into` alone, over caller-supplied - * rows of that page's opaque raster: render_into(h) == paint(render_into({}), h) - * row for row, because a render draws its highlights over the finished page. - */ -int pardes_pdf_paint_highlights( - pardes_pdf_document *document, - int page, - const pardes_pdf_request *request, - const pardes_pdf_highlight *highlights, - size_t highlight_count, - unsigned char *samples, - size_t samples_len, - int width, - int height, - int stride, - int band_y, - int band_height -); - -/* - * The raster rows [*row_start, *row_end) that painting `highlights` can touch - * under the same request, in the coordinates `pardes_pdf_render_into` bands - * use. An empty set (or only transparent ones) yields start == end == 0. - */ -int pardes_pdf_highlight_rows( - pardes_pdf_document *document, - int page, - const pardes_pdf_request *request, - const pardes_pdf_highlight *highlights, - size_t highlight_count, - int *row_start, - int *row_end -); - -int pardes_pdf_page_text( - pardes_pdf_document *document, - int page, - pardes_pdf_text *out -); -void pardes_pdf_drop_text(pardes_pdf_document *document, void *buffer); - -/* Case-insensitive, single-page search using MuPDF 1.27's iterative API. */ -int pardes_pdf_search_page( - pardes_pdf_document *document, - int page, - const char *needle, - pardes_pdf_search_result *out -); -void pardes_pdf_drop_search_result(pardes_pdf_document *document, void *result); - -/* Word-snap two normalized points and return oriented highlight quads. */ -int pardes_pdf_select( - pardes_pdf_document *document, - int page, - pardes_pdf_point start, - pardes_pdf_point end, - pardes_pdf_selection *out -); -void pardes_pdf_drop_selection(pardes_pdf_document *document, void *selection); - -/* Pure/no-throw oriented-quad hit test in normalized page space. */ -int pardes_pdf_point_inside_quad( - pardes_pdf_point point, - pardes_pdf_quad quad -); - -/* The input endpoints are normally the snapped points returned above. */ -int pardes_pdf_copy_selection( - pardes_pdf_document *document, - int page, - pardes_pdf_point start, - pardes_pdf_point end, - pardes_pdf_owned_text *out -); -void pardes_pdf_drop_owned_text(pardes_pdf_document *document, void *text); - -/* - * Flatten fz_load_outline's tree in stable document-order DFS. The borrowed - * table and byte arena remain valid until drop_outline_result. - */ -int pardes_pdf_load_outline( - pardes_pdf_document *document, - pardes_pdf_outline_result *out -); -void pardes_pdf_drop_outline_result( - pardes_pdf_document *document, - void *outline -); - -int pardes_pdf_link_at( - pardes_pdf_document *document, - int page_number, - pardes_pdf_point point, - pardes_pdf_link *out -); -int pardes_pdf_copy_rectangle( - pardes_pdf_document *document, - int page_number, - pardes_pdf_quad quad, - pardes_pdf_owned_text *out -); - -#ifdef __cplusplus -} -#endif - -#endif -- cgit v1.3