diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-06 21:34:19 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-06 21:36:55 -0300 |
| commit | 5a42ad8d8033c589231e81afdc6f9cb1279b5c22 (patch) | |
| tree | a0e345b55031e07d02bd6fa19dd5f05e67d36028 | |
| parent | 9589f6878ffd2501b4ce5a034ead58119d38749c (diff) | |
| download | pardes-5a42ad8d8033c589231e81afdc6f9cb1279b5c22.tar.gz pardes-5a42ad8d8033c589231e81afdc6f9cb1279b5c22.zip | |
kinds #43, the PDF kind in Zig: addons/pdf/pdf.zig replaces pdf.c over the same pdf_bridge.c (its header translated by build.zig, Zig 0.17 having no @cImport), one place a pane (a page and how far down it, which where says and address takes) laid out by each view its own way (a view with pictures its own strip, rasters and thumb by its id, a view of glyphs the page's text layer), the view of the last input the one whose window's top the place follows; the pages' sizes, the page's text and its hits, and the search over every page on the lanes as jobs (rows streamed through found, a stale search cancelled, its first hit gone to as a Look of its first row went), the tick asking and laying out only, open's one parse and close kept on the loop (0.4 and 0.8 ms; a truncated file stays a refused Look); a band at most PA_RASTER_MAX; the static build reads the module's pardes_addon, exported only from the library
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge
| -rw-r--r-- | addons/pdf/pdf.c | 1712 | ||||
| -rw-r--r-- | addons/pdf/pdf.zig | 1505 | ||||
| -rw-r--r-- | build.zig | 40 | ||||
| -rw-r--r-- | src/Addon.zig | 3 | ||||
| -rw-r--r-- | test/behaviour/addons_pdf.zig | 2 | ||||
| -rw-r--r-- | test/panes.zig | 2 | ||||
| -rw-r--r-- | test/session.zig | 2 |
7 files changed, 1526 insertions, 1740 deletions
diff --git a/addons/pdf/pdf.c b/addons/pdf/pdf.c deleted file mode 100644 index 088f954c..00000000 --- a/addons/pdf/pdf.c +++ /dev/null @@ -1,1712 +0,0 @@ -/* 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 its fit, tint and place. The strip is laid out for one view - * at a time: the one its last key or click came from, else the first told. */ -#include <math.h> -#include <pthread.h> -#include <stdatomic.h> -#include <stdio.h> -#include <stdlib.h> /* strtod; no malloc: memory is pardes's */ -#include <string.h> - -#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 FLING_NS 100000000ull /* a fling's end: this long with no turn */ -#define FLING_GRAIN 64u /* a fling's band starts and ends on these rows */ -#define MARKS 1024 /* highlights on a page */ -#define RECORD_VERSION 1u -#define VIEWS 8 /* views a pane is told of, by id */ - -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) { - 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, views[VIEWS]; /* the one laid out for, and each told */ - 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; - /* A fling: the strip's travel since the last tick and since the last - * frame drawn; a window or more of it a frame renders only the rows each - * page shows, the whole page once it rests (as pdf_view.zig did). */ - double since_tick, travel; - int framed, landed, fling; - 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; - /* flinging: the rows shown alone, on the grain */ - if (st->fling && page_rows(st, p, w, h, st->vh, &r)) { - uint32_t y0 = r.y0 / FLING_GRAIN * FLING_GRAIN, y1 = (r.y1 + FLING_GRAIN - 1) / FLING_GRAIN * FLING_GRAIN; - *y = y0, *bh = (y1 < h ? y1 : h) - y0; - } - 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 && !st->fling) n++; /* the page ahead, at rest */ - 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; - st->landed = 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) return; - double was = st->top; - set_top(st, st->top + px); - st->since_tick += fabs(st->top - was); -} - -/* A terminal without graphics: the page's text layer, a page a step. */ -static int text_mode(const pdf *st) { return st->view.glyphs != 0; } - -/* Some view told shows it as text: the page's text is read for it. */ -static int any_text(const pdf *st) { - for (int i = 0; i < VIEWS; i++) - if (st->views[i].cols && st->views[i].glyphs) return 1; - return text_mode(st); -} - -/* Down (dir 1) or up `n` steps of `px` pixels, or of a page as text. */ -static void move(pdf *st, int dir, double px, uint32_t n) { - if (text_mode(st)) go_page(st, st->page + dir * (int)n); - else scroll_by(st, dir * px * n); -} - -/* 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 void tick(void *v, pa_tick *t) { - pdf *st = v; - uint64_t now = t->now; - uint32_t flags = t->flags; - if (!st || !st->d) return; - /* A fling is a window's travel or more between frames; a tick a page's - * landing made (no turn since) neither starts nor ends one. */ - if (flags & PA_FRAMED) st->framed = 1; - if (!(st->landed && st->since_tick == 0)) { - if (st->framed) st->travel = 0, st->framed = 0; - st->travel += st->since_tick; - st->fling = st->vh && st->travel >= st->vh; - } - st->landed = 0, st->since_tick = 0; - 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); - uint32_t len; - if (any_text(st)) page_text(st, &len); - if (!text_mode(st)) reconcile(st); - uint64_t next = st->hover_wait == 2 ? st->hover_at : 0; - /* flinging: a tick when it rests, for the whole pages */ - if (st->fling && (!next || now + FLING_NS < next)) next = now + FLING_NS; - t->next = next; - int n = snprintf(t->prefix, sizeof t->prefix, "[%d/%d]", st->page + 1, st->pages); - t->prefix_len = n > 0 ? (uint32_t)n : 0; -} - -/* A view told: kept by its id, laid out for when it is the one, or none - * is, or the one is glyph art and this shows pictures (until an input's - * view is taken: one layout, not one a view, until the Zig port). */ -static void view(void *v, const pa_view *pv) { - pdf *st = v; - if (!st || pv->id < 1 || pv->id > VIEWS) return; - st->views[pv->id - 1] = *pv; - if (pv->id == st->view.id || !st->view.cols || (st->view.glyphs && pv->cols && !pv->glyphs)) st->view = *pv; - for (int i = 0; i < VIEWS && !st->view.cols; i++) - if (st->views[i].cols) st->view = st->views[i]; -} - -/* An input from view `id`: the strip is laid out for it from now on. */ -static void adopt(pdf *st, uint8_t id) { - if (id >= 1 && id <= VIEWS && st->views[id - 1].cols) st->view = st->views[id - 1]; -} - -static void paint(void *v, const pa_window *win, pa_paint *out) { - const pdf *st = v; - if (!st || !st->laid) return; - out->pointer = st->hover_page >= 0 && st->hover_link ? PA_POINTER_LINK : PA_POINTER_DEFAULT; - if (win->glyphs) { /* the page's text layer, its lines from the top */ - /* (read on the tick: paint changes nothing) */ - uint32_t len = st->text_page == st->page ? st->text_len : 0, at = 0; - const char *t = st->text; - for (unsigned row = 0; row < win->rows && at < len; row++) { - unsigned col = 0; - while (at < len && t[at] != '\n') { - unsigned n = 1; - while (n < 7 && at + n < len && ((unsigned char)t[at + n] & 0xc0) == 0x80) n++; - pa_cell *c = pa_at(win, row, col); - if (c && (unsigned char)t[at] >= 0x20) { - memcpy(c->text, t + at, n), c->len = (uint8_t)n; - c->fg = c->bg = PA_DEFAULT, c->flags = PA_PAINTED; - } - col += (unsigned char)t[at] >= 0x20, at += n; - } - at++; - } - 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)) continue; - uint32_t b0 = s->band_y, b1 = s->band_y + s->band_h; - if (r.y0 >= b0 && r.y1 <= b1) { - *pl = (pa_placement){.rgba = s->rgba, .w = s->w, .h = s->band_h, .src = {r.g.sx, r.y0 - b0, 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}; - out->n++; - continue; - } - /* Its rows not all landed (a fling's band moved on): its paper, - * and over it what the band has of them. */ - *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++; - uint32_t i0 = r.y0 > b0 ? r.y0 : b0, i1 = r.y1 < b1 ? r.y1 : b1, span = r.y1 - r.y0; - if (i1 <= i0 || out->n >= out->cap) continue; - uint32_t ay = r.at_y + (uint32_t)((uint64_t)(i0 - r.y0) * r.at_h / span), ah = (uint32_t)((uint64_t)(i1 - i0) * r.at_h / span); - if (!ah) continue; - out->placements[out->n++] = (pa_placement){.rgba = s->rgba, .w = s->w, .h = s->band_h, .src = {r.g.sx, i0 - b0, r.g.sw, i1 - i0}, - .dst = {0, 0, win->cols, win->rows}, .at = {r.g.dx, ay, r.g.dw, ah}, .key = (uint64_t)p << 32 | s->rev}; - continue; - } 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 */ - 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; - adopt(st, k->view); - 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': move(st, 1, half, n); return 1; - case 'u': move(st, -1, half, n); return 1; - case 'f': move(st, 1, st->vh, n); return 1; - case 'b': move(st, -1, st->vh, n); return 1; - case 'e': move(st, 1, cell, 1); return 1; - case 'y': move(st, -1, cell, 1); 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; - 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') move(st, 1, cell, n ? n : 1); - else if (cp == 'k') move(st, -1, cell, n ? n : 1); - 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: move(st, 1, cell, counted(st)); return 1; - case 'k': case PA_KEY_UP: move(st, -1, cell, counted(st)); return 1; - case PA_KEY_PAGE_DOWN: move(st, 1, st->vh, counted(st)); return 1; - case PA_KEY_PAGE_UP: move(st, -1, 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; - adopt(st, m->view); - uint32_t cell = st->view.cell_h ? st->view.cell_h : 16; - if (m->button == PA_WHEEL_UP || m->button == PA_WHEEL_DOWN) { - /* a notch a row, a touchpad's fraction of one its fraction; as text a - * page a turn */ - double notches = m->amount > 0 ? m->amount : 1; - if (text_mode(st)) move(st, m->button == PA_WHEEL_UP ? -1 : 1, 0, 1); - else scroll_by(st, (m->button == PA_WHEEL_UP ? -1 : 1) * notches * 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 ---- */ - -/* The page's text: what a tick read for a view's paint, else MuPDF's, - * not kept (a read changes nothing a frame shows). */ -static uint32_t body(void *v, uint64_t off, char *buf, uint32_t n) { - pdf *st = v; - if (!st || !st->d) return 0; - if (st->text_page == st->page) return buf ? pa_copy(st->text, st->text_len, off, buf, n) : st->text_len; - pardes_pdf_text t; - if (pardes_pdf_page_text(st->d->base, st->page, &t) != PARDES_PDF_OK) return 0; - uint32_t k = buf ? pa_copy(t.data, t.len, off, buf, n) : (uint32_t)t.len; - pardes_pdf_drop_text(st->d->base, t.handle); - return k; -} - -static uint64_t body_len(void *v) { return body(v, 0, 0, 0); } - -/* `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, found - * at once (on the loop: 7c moves it to a job). */ -static void search(void *v, const char *pat, uint32_t n) { - pdf *st = v; - if (!st || !st->d || n == 0 || n > 255) return; - 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, cap = MAX_HITS * 512; - while (shown > 0 && shown < n && ((unsigned char)pat[shown] & 0xc0) == 0x80) shown--; - char *buf = heap(cap); - if (!buf) return; - 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) len += (uint32_t)k; - } - } - api->found(buf, len); - unheap(buf); -} - -/* ---- 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 ---- */ - -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 || n < sizeof(record)) return 0; - 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); - return sizeof r; -} - -/* On a state open made from its file as it is (a Restore's, a change on - * disk): its fit, tint and place. A record of before 3 has the file's - * bytes after them, unread. */ -static int load(void *v, const uint8_t *buf, uint32_t n, uint32_t version) { - pdf *st = v; - record r; - (void)version; - if (!st || !st->d || n < sizeof r) return 1; - memcpy(&r, buf, sizeof r); - if (r.version != RECORD_VERSION || r.fit > 1 || r.tint > 2) 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, PA_PICTURES, ".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, .view = view, -}; diff --git a/addons/pdf/pdf.zig b/addons/pdf/pdf.zig new file mode 100644 index 00000000..d10407e0 --- /dev/null +++ b/addons/pdf/pdf.zig @@ -0,0 +1,1505 @@ +//! pdf.zig: PDFs as a pardes addon, in Zig over MuPDF through pdf_bridge.c +//! (C, so MuPDF's throws stay in C; build.zig translates its header for +//! this file as `pdf_bridge`). +//! +//! A pane is one place, a page and how far down it (what `where` says and +//! `address` takes), shown by each of its views its own way. A view with +//! pictures lays out a strip of the pages at its pixels, each fitted to its +//! width or height (PdfFit), a gap between two, tinted to the theme or not +//! (PdfTint), and asks for the rasters it shows; a view of glyphs (a +//! terminal without graphics) shows the page's text layer. 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. The pages' sizes, the page's text and its search hits, and the +//! search over every page are jobs on the lanes too; a selection and the +//! pointer's word are MuPDF's on the loop. 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. A fling (a window's travel or more between frames) +//! renders only the rows each page shows until it rests. The record in a dump is its fit, tint +//! and place. +const std = @import("std"); +const addon = @import("addon"); +const m = @import("pdf_bridge"); +const c = addon.c; + +pub const pardes_addon = addon.ops(Pdf); +// A library's one export; a static pardes reads the declaration (Addon.zig). +comptime { + if (@import("builtin").output_mode == .Lib) @export(&pardes_addon, .{ .name = "pardes_addon" }); +} + +const gap_px = 8; // between two pages of the strip +const slots_n = 16; // pages' pixels a pane holds at once, all its views' +const lanes = 2; // jobs a document runs at once +const jobs_n = 8; +const views_n = 4; // views a pane is told of, by id +const max_hits = 512; // rows a search lists +const band_rows = 8192; +const chunk = 512; // a tall page's bands start on these +const overlap = 32; // rows rendered past a band's edges +const hover_ns = 32 * std.time.ns_per_ms; // the pointer's rest before its word shows +const fling_ns = 100 * std.time.ns_per_ms; // a fling's end: this long with no turn +const grain = 64; // a fling's band starts and ends on these rows +const marks_n = 1024; // highlights on a page +const record_version = 1; + +const heap = addon.heap; +const ok = m.PARDES_PDF_OK; +const Quad = m.pardes_pdf_quad; +const Mark = m.pardes_pdf_highlight; +const Point = m.pardes_pdf_point; +const Request = m.pardes_pdf_request; +const Button = @FieldType(addon.Mouse, "button"); + +fn f64Of(x: anytype) f64 { + return @floatFromInt(x); +} + +// ---- the tint: a page's ink and paper to the theme's ---- + +const Tint = enum(u32) { 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. +fn tint(px: []u8, mode: Tint, ink: u32, paper: u32) void { + if (mode == .disabled) return; + var target: [256][3]u8 = undefined; + for (&target, 0..) |*t, l| for (t, 0..) |*v, ch| { + const f = (ink >> @intCast(16 - 8 * ch)) & 0xff; + const b = (paper >> @intCast(16 - 8 * ch)) & 0xff; + v.* = @intCast((f * (255 - @as(u32, @intCast(l))) + b * @as(u32, @intCast(l)) + 127) / 255); + }; + var last: ?[2][4]u8 = null; + var i: usize = 0; + while (i + 4 <= px.len) : (i += 4) { + const p = px[i..][0..4]; + if (last) |was| if (std.mem.eql(u8, p, &was[0])) { + p.* = was[1]; + continue; + }; + const in = p.*; + const lum = (@as(i32, p[0]) * 77 + @as(i32, p[1]) * 150 + @as(i32, p[2]) * 29 + 128) >> 8; + for (p[0..3], target[@intCast(lum)]) |*v, t| { + const d = if (mode == .filtered) @divTrunc((@as(i32, v.*) - lum) * 3, 4) else 0; + v.* = @intCast(std.math.clamp(@as(i32, t) + d, 0, 255)); + } + last = .{ in, p.* }; + } +} + +// ---- 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. +const Doc = struct { id: u64 = 0, refs: u32 = 1, closed: bool = false, base: ?*m.pardes_pdf_document = null, lane: [lanes]?*m.pardes_pdf_document = @splat(null), busy: [lanes]bool = @splat(false), cookie: [jobs_n]m.pardes_pdf_cookie = std.mem.zeroes([jobs_n]m.pardes_pdf_cookie), unclaimed: [24][]u8 = @splat(&.{}) }; + +var docs_lock: std.atomic.Mutex = .unlocked; +var docs: [64]?*Doc = @splat(null); +var doc_ids: u64 = 0; + +fn lock() void { + while (!docs_lock.tryLock()) std.atomic.spinLoopHint(); +} + +fn docFree(d: *Doc) void { + for (d.unclaimed) |p| heap.free(p); + for (d.lane) |l| m.pardes_pdf_close(l); + m.pardes_pdf_close(d.base); + heap.destroy(d); +} + +/// One more reference to the open document `id`, or null. +fn docTake(id: u64) ?*Doc { + lock(); + defer docs_lock.unlock(); + for (docs) |slot| if (slot) |d| if (d.id == id and !d.closed) { + d.refs += 1; + return d; + }; + return null; +} + +fn docDrop(d: *Doc, closing: bool) void { + lock(); + d.closed = d.closed or closing; + d.refs -= 1; + const last = d.refs == 0; + if (last) if (std.mem.indexOfScalar(?*Doc, &docs, d)) |i| { + docs[i] = null; + }; + docs_lock.unlock(); + if (last) docFree(d); +} + +/// A job's pixels the pane's now. +fn claim(d: *Doc, p: []const u8) void { + if (p.len == 0) return; + lock(); + for (&d.unclaimed) |*u| if (u.ptr == p.ptr) { + u.* = &.{}; + }; + docs_lock.unlock(); +} + +// ---- a pane ---- + +/// Page `page`'s pixels for view `view` (0: none): `band_h` rows from +/// `band_y` of its `w` x `h` raster, as `req`, the tint and `shown` made +/// them (`clean` before highlights and tint, kept once highlighted), its +/// key `rev`, and `from` the key it is of but rows `dirty_*`; and the job +/// it waits for (`token`), asked as `want` and `asked`. +const Slot = struct { + view: u8 = 0, + page: u32 = 0, + rgba: []u8 = &.{}, + clean: []u8 = &.{}, + shown: []Mark = &.{}, + asked: []Mark = &.{}, + is: struct { w: u32 = 0, h: u32 = 0, band_y: u32 = 0, band_h: u32 = 0, rev: u32 = 0, from: u32 = 0, dirty_y: u32 = 0, dirty_h: u32 = 0, req: Request = std.mem.zeroes(Request), tint: Tint = .disabled, ink: u32 = 0, paper: u32 = 0 } = .{}, + job: struct { token: u32 = 0, want: Request = std.mem.zeroes(Request), y: u32 = 0, h: u32 = 0, failed: bool = false } = .{}, + + fn clear(s: *Slot) void { + for ([_][]const u8{ s.rgba, s.clean, std.mem.sliceAsBytes(s.shown), std.mem.sliceAsBytes(s.asked) }) |p| heap.free(p); + s.* = .{}; + } +}; + +/// A view as told (`v`) and, with pictures, the strip laid out at its +/// `vw` x `vh` pixels (`fit`, height): each page's top (`y`) and height +/// (`ph`) on it, and the strip's pixel at its window's top, laid at the +/// place's `rev`. +const Layout = struct { v: addon.View = std.mem.zeroes(addon.View), y: []u64 = &.{}, ph: []u32 = &.{}, height: u64 = 0, vw: u32 = 0, vh: u32 = 0, fit: bool = false, laid: bool = false, top: f64 = 0, rev: u32 = 0 }; + +/// A page's text, and its lines. +const Text = struct { bytes: []u8 = &.{}, page: ?u32 = null, lines: u32 = 0 }; +const Op = enum(u32) { render, sizes, page, search }; +const Job = struct { token: u32 = 0, op: Op = .render, page: u32 = 0 }; + +pub const Pdf = struct { + d: ?*Doc = null, + name: []const u8 = "", // the file's, in the rows a pane lists + pages: u32 = 0, + size: []m.pardes_pdf_page_size = &.{}, + sizes_assumed: bool = false, + /// The place: the page at the window's top and how far down it, one + /// for the pane whatever views show it; `rev` moves at each change. + page: u32 = 0, + frac: f64 = 0, + rev: u32 = 1, + pan: u16 = 0, // fit height: how far across, 0..65535 + fit_height: bool = false, + tint: Tint = .filtered, + views: [views_n]Layout = @splat(.{}), + /// The view of the last input (an id), else the first told: whose + /// window's top the place follows. + active: u8 = 0, + s: [slots_n]Slot = @splat(.{}), + revs: u32 = 0, + jobs: [jobs_n]Job = @splat(.{}), + warm: bool = false, + blank: [4]u8 = .{ 255, 255, 255, 255 }, // the paper a page shows until its pixels land + /// The text of the page shown, a job's; a body read's own, which no + /// frame shows. + text: Text = .{}, + read: Text = .{}, + /// The search: its pattern, each page's hits (its job's, `counts`), + /// and the page shown's quads (`hits`, `hits_page`'s). + find: struct { query: [256]u8 = undefined, len: u32 = 0, due: bool = false, counts: []u32 = &.{}, hits: []m.pardes_pdf_search_quad = &.{}, hits_page: ?u32 = null, hit: u32 = 0, reveal: bool = false } = .{}, + /// The selection: its quads and text on its page, from `anchor` to `tip`. + sel: struct { quads: []Quad = &.{}, text: []u8 = &.{}, page: ?u32 = null, anchor: Point = .{ .x = 0, .y = 0 }, tip: Point = .{ .x = 0, .y = 0 } } = .{}, + /// A button held (a right one's Look waits for a drag off its cell), + /// and whether another came while it was (a chord). + press: struct { button: ?Button = null, chorded: bool = false, look: bool = false, col: u16 = 0, row: u16 = 0, page: ?u32 = null } = .{}, + /// The pointer's word or link where it rests: `wait` 1 moved, 2 resting + /// until `at`. + hover: struct { quad: Quad = std.mem.zeroes(Quad), page: ?u32 = null, link: bool = false, wait: u2 = 0, col: u16 = 0, row: u16 = 0, view: u8 = 0, at: u64 = 0 } = .{}, + /// A fling: the strip's travel since the last tick and since the last + /// frame drawn, a window or more of it a frame renders only the rows + /// each page shows, the whole page once it rests. + go: struct { since_tick: f64 = 0, travel: f64 = 0, framed: bool = false, landed: bool = false, fling: bool = false } = .{}, + count: u32 = 0, // a key's count, typed before it + g: bool = false, + + pub const head: addon.Head = .{ .name = "pdf", .version = 1, .exts = ".pdf", .pictures = true, .words = &.{ + .{ .name = "PdfSections", .leader = "ts", .doc = "list the PDF's sections in a pane, each a place to go" }, + .{ .name = "PdfTint", .leader = "ti", .arg = .optional, .doc = "tint the PDF to the theme or show it as printed (disabled|filtered|full)" }, + .{ .name = "PdfFit", .leader = "tz", .arg = .optional, .doc = "fit the PDF's pages to the pane's width or height (width|height)" }, + } }; + + /// MuPDF's memory is pardes's heap. + pub fn init() bool { + const H = struct { + fn alloc(_: ?*anyopaque, n: usize) callconv(.c) ?*anyopaque { + return addon.api.heap.?(null, @max(n, 1)); + } + fn realloc(_: ?*anyopaque, p: ?*anyopaque, n: usize) callconv(.c) ?*anyopaque { + return addon.api.heap.?(p, @max(n, 1)); + } + fn free(_: ?*anyopaque, p: ?*anyopaque) callconv(.c) void { + if (p != null) _ = addon.api.heap.?(p, 0); + } + const hooks: m.pardes_pdf_allocator = .{ .user = null, .alloc = alloc, .realloc = realloc, .free = free }; + }; + return m.pardes_pdf_set_allocator(&H.hooks) == ok; + } + + pub fn open(st: *Pdf, path: ?[]const u8, bytes: ?[]const u8) void { + if (path) |p| st.name = addon.arena.dupe(u8, std.fs.path.basename(p)) catch ""; + const b = bytes orelse return; + var pages: c_int = 0; + const d = heap.create(Doc) catch return; + d.* = .{ .base = m.pardes_pdf_open_memory(b.ptr, b.len, &pages) }; + if (d.base) |base| for (&d.lane) |*l| { + l.* = m.pardes_pdf_lane_clone(base); + }; + lock(); + if (d.base != null) if (std.mem.indexOfScalar(?*Doc, &docs, null)) |at| { + doc_ids += 1; + d.id = doc_ids; + docs[at] = d; + }; + docs_lock.unlock(); + st.pages = @intCast(pages); + st.size = if (d.id != 0) addon.arena.alloc(m.pardes_pdf_page_size, st.pages) catch &.{} else &.{}; + if (st.size.len == 0 or m.pardes_pdf_get_page_size(d.base, 0, &st.size[0]) != ok) { + if (d.id != 0) docDrop(d, true) else docFree(d); + return addon.say("not a PDF pardes can read", .err); + } + st.d = d; + // every page the first's size until a lane measures them + @memset(st.size[1..], st.size[0]); + st.sizes_assumed = st.pages > 1; + } + + pub fn close(st: *Pdf) void { + for (&st.s) |*s| s.clear(); + for (st.jobs) |j| abortJob(st, j.token); + for ([_][]const u8{ st.text.bytes, st.read.bytes, std.mem.sliceAsBytes(st.find.hits) }) |p| heap.free(p); + dropSel(st); + if (st.d) |d| docDrop(d, true); + st.d = null; + } + + pub fn tick(st: *Pdf, now: u64, flags: addon.Flags) u64 { + if (st.d == null) return 0; + const go = &st.go; + // A fling is a window's travel or more between frames; a tick a + // page's landing made (no turn since) neither starts nor ends one. + go.framed = go.framed or flags.framed; + if (!(go.landed and go.since_tick == 0)) { + if (go.framed) go.travel = 0; + go.framed = false; + go.travel += go.since_tick; + go.fling = if (pixels(st, st.active)) |l| go.travel >= f64Of(l.vh) else false; + } + go.landed, go.since_tick = .{ false, 0 }; + settle(st); + for (&st.views) |*l| layout(st, l); + // white tinted is the theme's paper + const paper: u32 = if (st.tint == .disabled) 0xffffff else if (pixels(st, st.active)) |l| @backingInt(l.v.bg) else 0xffffff; + st.blank = .{ @truncate(paper >> 16), @truncate(paper >> 8), @truncate(paper), 255 }; + const hv = &st.hover; + if (hv.wait == 1) hv.wait, hv.at = .{ 2, now + hover_ns }; + if (hv.wait == 2 and now >= hv.at) { + hv.wait = 0; + if (probeAt(st, hv.view, hv.col, hv.row)) |pr| { + hv.quad, hv.page, hv.link = .{ pr.quad, pr.page, pr.link != null }; + heap.free(pr.text); + } + } + const f = &st.find; + if (f.reveal and f.hits_page == st.page) revealHit(st); + // What the place asks of the lanes: the pages' sizes, the page's + // text and hits, the search, then each view's pages. + const query = f.query[0..f.len]; + if (st.sizes_assumed and jobsOut(st, .sizes) == 0) _ = ask(st, .{ .op = .sizes, .page = st.pages }, "", ""); + const glyphs = for (st.views) |l| { + if (l.v.cols != 0 and l.v.glyphs) break true; + } else false; + if (((glyphs and st.text.page != st.page) or (query.len > 0 and f.hits_page != st.page)) and jobsOut(st, .page) == 0) _ = ask(st, .{ .op = .page, .page = st.page, .n = f.len }, query, ""); + if (f.due and ask(st, .{ .op = .search, .page = st.pages, .n = f.len }, query, st.name) != 0) f.due = false; + for (&st.views, 1..) |*l, id| if (l.laid and !l.v.glyphs) reconcile(st, l, @intCast(id)); + var next: u64 = if (hv.wait == 2) hv.at else 0; + // flinging: a tick when it rests, for the whole pages + if (go.fling and (next == 0 or now + fling_ns < next)) next = now + fling_ns; + return next; + } + + pub fn prefix(st: *const Pdf, w: *std.Io.Writer) !void { + if (st.d != null) try w.print("[{d}/{d}]", .{ st.page + 1, st.pages }); + } + + /// A view told: kept by its id; a glyph view's pictures and a stopped + /// one's are dropped. + pub fn view(st: *Pdf, v: addon.View) void { + if (v.id < 1 or v.id > views_n) return; + st.views[v.id - 1].v = v; + if (v.cols == 0 or v.glyphs) { + for (&st.s) |*s| if (s.view == v.id) { + abortJob(st, s.job.token); + s.clear(); + }; + st.views[v.id - 1].laid = false; + } + if (st.active != 0 and st.views[st.active - 1].v.cols != 0) return; + st.active = for (st.views, 1..) |o, id| { + if (o.v.cols != 0) break @intCast(id); + } else 0; + } + + pub fn paint(st: *const Pdf, win: addon.Window, into: addon.Paint) void { + if (st.d == null or win.view < 1 or win.view > views_n) return; + const out = into.out; + out.pointer = if (st.hover.page != null and st.hover.link) c.PA_POINTER_LINK else c.PA_POINTER_DEFAULT; + if (win.glyphs) { // the page's text layer, from its top (read on a tick) + out.at = @floatCast((f64Of(st.page) + std.math.clamp(st.frac, 0, 1)) / f64Of(st.pages)); + out.span = @floatCast(1 / f64Of(st.pages)); + if (st.text.page != st.page) return; + const t = st.text.bytes; + var at: usize = 0; + for (0..win.rows) |row| { + var col: usize = 0; + while (at < t.len and t[at] != '\n') { + var n: usize = 1; + while (n < 7 and at + n < t.len and t[at + n] & 0xc0 == 0x80) n += 1; + if (t[at] >= 0x20 and col < win.cols) { + const cell = &win.cells[row * win.stride + col]; + cell.* = .{ .text = @splat(0), .fg = c.PA_DEFAULT, .bg = c.PA_DEFAULT, .attrs = 0, .len = @intCast(n), .flags = c.PA_PAINTED }; + @memcpy(cell.text[0..n], t[at..][0..n]); + } + col += @intFromBool(t[at] >= 0x20); + at += n; + } + at += 1; + } + return; + } + const l = &st.views[win.view - 1]; + if (!l.laid) return; + const vh = @min(@as(u32, win.rows) * win.cell_h, l.vh); + const first, const count = visible(st, l); + for (first..first + count) |p| { + const k = @as(u64, p) << 32; + const s = if (landed(st, win.view, p)) |at| at[0] else null; + // not landed yet: its paper, where it will be + const wh: [2]u32 = if (s) |sl| .{ sl.is.w, sl.is.h } else .{ @intFromFloat(@max(1, @round(st.size[p].width * 8))), @intFromFloat(@max(1, @round(st.size[p].height * 8))) }; + const r = pageRows(st, l, @intCast(p), wh[0], wh[1], vh) orelse continue; + const paper = std.mem.zeroInit(c.pa_placement, .{ .rgba = &st.blank, .w = 1, .h = 1, .src = .{ .x = 0, .y = 0, .w = 1, .h = 1 }, .dst = .{ .x = 0, .y = 0, .w = win.cols, .h = win.rows }, .at = .{ .x = r.g.dx, .y = r.at_y, .w = r.g.dw, .h = r.at_h }, .key = k }); + const sl = s orelse { + into.place(paper); + continue; + }; + var pl = paper; + pl.rgba, pl.w, pl.h, pl.key = .{ sl.rgba.ptr, sl.is.w, sl.is.band_h, k | sl.is.rev }; + if (r.y0 >= sl.is.band_y and r.y1 <= sl.is.band_y + sl.is.band_h) { + pl.src = .{ .x = r.g.sx, .y = r.y0 - sl.is.band_y, .w = r.g.sw, .h = r.y1 - r.y0 }; + pl.from, pl.dirty_y, pl.dirty_h = .{ if (sl.is.from != 0) k | sl.is.from else 0, sl.is.dirty_y, sl.is.dirty_h }; + into.place(pl); + continue; + } + // Its rows not all landed (a fling's band moved on): its + // paper, and over it what the band has of them. + into.place(paper); + const c0 = @max(r.y0, sl.is.band_y); + const c1 = @min(r.y1, sl.is.band_y + sl.is.band_h); + if (c1 <= c0) continue; + pl.src = .{ .x = r.g.sx, .y = c0 - sl.is.band_y, .w = r.g.sw, .h = c1 - c0 }; + pl.at.y = r.at_y + @as(u32, @intCast(@as(u64, c0 - r.y0) * r.at_h / (r.y1 - r.y0))); + pl.at.h = @intCast(@as(u64, c1 - c0) * r.at_h / (r.y1 - r.y0)); + if (pl.at.h > 0) into.place(pl); + } + if (l.height != 0) { // the rail's thumb + out.at = @floatCast(l.top / f64Of(l.height)); + out.span = @floatCast(f64Of(l.vh) / f64Of(l.height)); + } + } + + pub fn key(st: *Pdf, k: addon.Key) bool { + if (st.d == null) return false; + const l = &st.views[take(st, k.view) -| 1]; + const cell: f64 = if (l.v.cell_h != 0) f64Of(l.v.cell_h) else 16; + const vh = f64Of(l.vh); + var cp: u32 = @backingInt(k.code); + if (cp == 0x1b) return !k.shift and cancel(st); // Shift-Esc: the editor's, leaving at once + const ctrl = k.ctrl or (cp > 0 and cp < 0x20 and cp != '\r' and cp != '\t'); // ^D as Ctrl-d + if (ctrl and cp < 0x20) cp += 0x60; + if (ctrl) { + const n = counted(st); + switch (cp) { + 'd', 'u' => move(st, l, if (cp == 'd') 1 else -1, @max(1, @floor(vh / 2)), n), + 'f', 'b' => move(st, l, if (cp == 'f') 1 else -1, vh, n), + 'e', 'y' => move(st, l, if (cp == 'e') 1 else -1, cell, 1), + else => return false, // the editor's: windows, jumps + } + return true; + } + if (k.alt) return false; + if (st.g) { + const n = st.count; + st.g, st.count = .{ false, 0 }; + switch (cp) { + 'g' => goPage(st, n -| 1), + 'e' => goPage(st, st.pages - 1), + 'j', 'k' => move(st, l, if (cp == 'j') 1 else -1, cell, @max(n, 1)), + 'h', 's', 'l' => edge(st, cp == 'l'), + else => {}, + } + return true; + } + if (cp >= '0' and cp <= '9' and (cp != '0' or st.count > 0)) { + st.count = @min(st.count * 10 + (cp - '0'), 1000000); + return true; + } + const across = f64Of(if (l.v.cell_w != 0) l.v.cell_w else 8); + const K = addon.Code; + switch (cp) { + ':', ' ', '/', 'n', 'N', '\t' => { + st.count = 0; + return false; // the editor's + }, + 'g' => st.g = true, + 'G' => goPage(st, if (st.count > 0) st.count - 1 else st.pages - 1), + 'f' => addon.exec("PdfSections"), + 'j', @backingInt(K.down) => move(st, l, 1, cell, counted(st)), + 'k', @backingInt(K.up) => move(st, l, -1, cell, counted(st)), + @backingInt(K.page_down) => move(st, l, 1, vh, counted(st)), + @backingInt(K.page_up) => move(st, l, -1, vh, counted(st)), + 'h', @backingInt(K.left) => panBy(st, -1, across * f64Of(counted(st))), + 'l', @backingInt(K.right) => panBy(st, 1, across * f64Of(counted(st))), + '0', '^', @backingInt(K.home) => edge(st, false), + '$', @backingInt(K.end) => edge(st, true), + else => {}, // the editing keys: nothing here + } + if (cp != 'g') st.count = 0; + return true; + } + + pub fn mouse(st: *Pdf, ev: addon.Mouse) bool { + if (st.d == null) return false; + const id = take(st, ev.view); + const l = &st.views[id -| 1]; + const dir: f64 = if (ev.button == .wheel_up or ev.button == .wheel_left) -1 else 1; + switch (ev.button) { + .wheel_up, .wheel_down => { + // a notch a row, a touchpad's fraction of one its fraction; + // as text a page a turn + const notches: f64 = if (ev.amount > 0) ev.amount else 1; + const cell: f64 = if (l.v.cell_h != 0) f64Of(l.v.cell_h) else 16; + move(st, l, dir, notches * cell, 1); + return true; + }, + .wheel_left, .wheel_right => { + if (st.fit_height) panBy(st, @intFromFloat(dir), f64Of(l.v.cell_w) * 4); + return true; + }, + else => {}, + } + const pr = &st.press; + if (ev.action == .motion) { + const here = ev.col == st.hover.col and ev.row == st.hover.row and (st.hover.wait != 0 or st.hover.page != null); + if (ev.col == 0xffff) st.hover = .{} else if (pr.button == null and !here) st.hover = .{ .col = ev.col, .row = ev.row, .wait = 1, .view = id }; + return true; + } + if (ev.action == .press) { + st.hover = .{}; + if (pr.button != null) { // a chord: B1 and B2 copies, a PDF being nothing to cut + pr.chorded = true; + if (ev.button == .middle and st.sel.quads.len > 0) addon.exec("ClipYank"); + return true; + } + pr.* = .{ .button = ev.button, .look = ev.button == .right, .col = ev.col, .row = ev.row }; + if (pr.look) return true; + const at = pointAt(st, id, ev.col, ev.row, null) orelse { + pr.button = null; + return true; + }; + pr.page = at.page; + st.sel.anchor, st.sel.tip = .{ at.pt, at.pt }; + if (ev.button == .middle and !selContains(st, at.page, at.pt)) _ = selectTo(st, at.page, at.pt); + return true; + } + if (ev.action == .drag) { + if (pr.button == null or pr.chorded) return true; + if (pr.look) { + if (ev.col == pr.col and ev.row == pr.row) return true; + pr.look = false; + const at = pointAt(st, id, pr.col, pr.row, null) orelse return true; + pr.page = at.page; + st.sel.anchor, st.sel.tip = .{ at.pt, at.pt }; + } + const at = pointAt(st, id, ev.col, ev.row, pr.page orelse return true) orelse return true; + if (at.pt.x != st.sel.tip.x or at.pt.y != st.sel.tip.y) _ = selectTo(st, at.page, at.pt); + return true; + } + const was = pr.button orelse return true; + if (ev.action != .release) return true; + const held = pr.*; + pr.* = .{}; + if (held.chorded) return true; + if (was == .right and held.look) { + const word = probeAt(st, id, held.col, held.row) orelse return true; + defer heap.free(word.text); + if (word.link) |link| follow(st, link, word.text) else addon.look(word.text); + } else if (was == .left) { + if (std.meta.eql(st.sel.anchor, st.sel.tip)) dropSel(st); + } else if (st.sel.text.len > 0) { + // the selection, looked at (B3) or run (B2) + if (was == .right) addon.look(st.sel.text) else addon.exec(st.sel.text); + } + return true; + } + + /// The page's text: a job's, else MuPDF's read here and kept for reads + /// alone (a read changes nothing a frame shows). + pub fn body(st: *Pdf) []const u8 { + const d = st.d orelse return ""; + if (st.text.page == st.page) return st.text.bytes; + if (st.read.page == st.page) return st.read.bytes; + heap.free(st.read.bytes); + st.read = .{ .page = st.page }; + var t: m.pardes_pdf_text = undefined; + if (m.pardes_pdf_page_text(d.base, @intCast(st.page), &t) != ok) return ""; + defer m.pardes_pdf_drop_text(d.base, t.handle); + st.read.bytes = heap.dupe(u8, t.data[0..t.len]) catch &.{}; + return st.read.bytes; + } + + /// `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`; after a space, where's window. + pub fn address(st: *Pdf, text: []const u8) bool { + if (st.d == null) return false; + var t = text; + const sections_row = std.mem.startsWith(u8, t, "+PdfSections "); + if (std.mem.startsWith(u8, t, "+")) t = t[(std.mem.indexOfScalar(u8, t, ' ') orelse t.len - 1) + 1 ..]; + if (std.mem.startsWith(u8, t, ":")) t = t[1..]; + t = t[0 .. std.mem.indexOfScalar(u8, t, ' ') orelse t.len]; + const colon = std.mem.indexOfScalar(u8, t, ':') orelse t.len; + const page = std.fmt.parseInt(u32, t[0..colon], 10) catch return none(); + const rest = t[@min(colon + 1, t.len)..]; + if (std.mem.indexOfScalar(u8, rest, '.') != null) { + const f = std.fmt.parseFloat(f64, rest) catch return none(); + dropSel(st); + goTo(st, @min(page -| 1, st.pages - 1), f); + return true; + } + const second = if (colon < t.len) std.fmt.parseInt(u32, rest, 10) catch return none() else 0; + if (sections_row) return section(st, page, second); + var said: [160]u8 = undefined; + if (page == 0 or page > st.pages) return miss(std.fmt.bufPrint(&said, "has no page {d}", .{page})); + const f = &st.find; + if (second > 0 and (f.len == 0 or f.counts.len != st.pages or f.counts[page - 1] < second)) return miss(std.fmt.bufPrint(&said, "has no search hit {d} on page {d}", .{ second, page })); + dropSel(st); + goPage(st, page - 1); + if (second > 0) f.hit, f.reveal = .{ second - 1, true }; + return true; + } + + /// `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). + pub fn where(st: *const Pdf, w: *std.Io.Writer) !void { + if (st.d == null) return; + const f6: u64 = @intFromFloat(@round(std.math.clamp(st.frac, 0, 1) * 1e6)); + const shown: f64 = if (pixels(st, st.active)) |l| f64Of(l.vh) / f64Of(@max(l.ph[st.page], 1)) else if (st.text.page == st.page) f64Of(st.views[st.active -| 1].v.rows) / f64Of(st.text.lines) else 1; + const w3: u64 = @intFromFloat(@round(@min(shown, 1e6) * 1e3)); + try w.print("{d}:{d}.{d:0>6} {d}.{d:0>3}", .{ st.page + 1, f6 / 1000000, f6 % 1000000, w3 / 1000, w3 % 1000 }); + } + + pub fn ctl(st: *Pdf, line: []const u8, reply: *std.Io.Writer) bool { + if (st.d == null) return false; + const word = line[0 .. std.mem.indexOfAny(u8, line, " \t\n") orelse line.len]; + const arg = std.mem.trim(u8, line[word.len..], " \t\n"); + if (std.mem.eql(u8, word, "PdfSections")) { + sections(st); + } else if (std.mem.eql(u8, word, "PdfFit")) { + const fit = if (arg.len == 0) !st.fit_height else if (std.mem.eql(u8, arg, "height")) true else if (std.mem.eql(u8, arg, "width")) false else { + reply.print("invalid argument: PdfFit takes width or height, not \"{s}\"", .{arg[0..@min(arg.len, 32)]}) catch {}; + return false; + }; + if (fit == st.fit_height) return true; + st.fit_height, st.pan = .{ fit, 0 }; + goPage(st, st.page); + st.find.reveal = st.find.len > 0; + } else if (std.mem.eql(u8, word, "PdfTint")) { + st.tint = if (arg.len == 0) @fromBackingInt((@backingInt(st.tint) + 1) % 3) else std.meta.stringToEnum(Tint, arg) orelse { + reply.print("invalid argument: PdfTint takes disabled, filtered or full, not \"{s}\"", .{arg[0..@min(arg.len, 32)]}) catch {}; + return false; + }; + } else return false; + return true; + } + + pub fn ctlRead(st: *const Pdf, w: *std.Io.Writer) !void { + try w.print("fit:{s} tint:{t}", .{ if (st.fit_height) "height" else "width", st.tint }); + } + + /// `/`: every hit, `file.pdf:P:H pattern` a row, at most max_hits, + /// found on a job (a stale one's dropped), and the first gone to. + pub fn search(st: *Pdf, pat: []const u8) void { + const f = &st.find; + if (st.d == null or pat.len == 0 or pat.len > 255) return; + if (!std.mem.eql(u8, f.query[0..f.len], pat)) { + @memcpy(f.query[0..pat.len], pat); + f.len = @intCast(pat.len); + dropHits(st); + @memset(f.counts, 0); + f.hit, f.reveal = .{ 0, true }; + } + // (a page's job asked its hits of the pattern before) + for (&st.jobs) |*j| if (j.token != 0 and (j.op == .search or j.op == .page)) { + abortJob(st, j.token); + addon.cancel(j.token); + j.* = .{}; + }; + f.due = true; + } + + // ---- the record: its fit, tint and place ---- + + const Record = extern struct { version: u32, fit: u32, tint: u32, page: u32, frac: f64 }; + + pub fn dump(st: *const Pdf, buf: []u8) usize { + if (st.d == null or buf.len < @sizeOf(Record)) return 0; + const r: Record = .{ .version = record_version, .fit = @intFromBool(st.fit_height), .tint = @backingInt(st.tint), .page = st.page, .frac = st.frac }; + @memcpy(buf[0..@sizeOf(Record)], std.mem.asBytes(&r)); + return @sizeOf(Record); + } + + /// On a state open made from its file as it is (a Restore's, a change + /// on disk): its fit, tint and place. + pub fn load(st: *Pdf, bytes: []const u8, _: u32) bool { + if (st.d == null or bytes.len < @sizeOf(Record)) return false; + const r = std.mem.bytesToValue(Record, bytes[0..@sizeOf(Record)]); + if (r.version != record_version or r.fit > 1 or r.tint > 2) return false; + st.fit_height, st.tint = .{ r.fit == 1, @fromBackingInt(r.tint) }; + goTo(st, @min(r.page, st.pages - 1), r.frac); + return true; + } + + // ---- jobs ---- + + /// A job's input: `n` highlights after it (render), or the pattern's + /// `n` bytes (hits, search) and the file's name (search). + const In = extern struct { op: Op, cookie: u32 = 0, doc: u64 = 0, page: u32 = 0, tint: Tint = .disabled, req: Request = std.mem.zeroes(Request), band_y: u32 = 0, band_h: u32 = 0, ink: u32 = 0, paper: u32 = 0, keep_clean: u32 = 0, n: u32 = 0 }; + /// A job's answer, and after it the sizes (sizes), the text (text), the + /// quads (hits), or each page's count of hits and the rows (search). + const Out = extern struct { ok: u32 = 0, busy: u32 = 0, w: u32 = 0, h: u32 = 0, band_y: u32 = 0, band_h: u32 = 0, n: u32 = 0, hits: u32 = 0, rgba: ?[*]u8 = null, clean: ?[*]u8 = null }; + + /// On a worker: the job on a free lane of its document. + pub fn jobRun(bytes: []const u8, gpa: std.mem.Allocator) ?[]u8 { + if (bytes.len < @sizeOf(In)) return null; + const in = std.mem.bytesToValue(In, bytes[0..@sizeOf(In)]); + const extra = bytes[@sizeOf(In)..]; + var res: Out = .{}; + var tail: []const u8 = ""; + const d = docTake(in.doc) orelse return answer(gpa, res, tail); + defer docDrop(d, false); + const lane = for (&d.busy, d.lane, 0..) |*b, ld, i| { + if (ld != null and @cmpxchgStrong(bool, b, false, true, .acquire, .monotonic) == null) break i; + } else null; + res.busy = @intFromBool(lane == null); + const ld = d.lane[lane orelse return answer(gpa, res, tail)]; + defer @atomicStore(bool, &d.busy[lane.?], false, .release); + const cookie = &d.cookie[in.cookie % jobs_n]; + if (m.pardes_pdf_lane_open(ld) != ok) return answer(gpa, res, tail); + switch (in.op) { + .render => { + const marks = gpa.alloc(Mark, in.n) catch return null; + @memcpy(std.mem.sliceAsBytes(marks), extra[0 .. in.n * @sizeOf(Mark)]); + m.pardes_pdf_set_cookie(ld, cookie); + render(d, ld, &in, marks, &res); + m.pardes_pdf_set_cookie(ld, null); + }, + .sizes => { + const sizes = gpa.alloc(m.pardes_pdf_page_size, in.page) catch return null; + for (sizes, 0..) |*s, p| if ((p % 64 == 0 and @atomicLoad(c_int, &cookie.abort, .monotonic) != 0) or m.pardes_pdf_get_page_size(ld, @intCast(p), s) != ok) return answer(gpa, res, tail); + res.ok, res.n, tail = .{ 1, in.page, std.mem.sliceAsBytes(sizes) }; + }, + .page, .search => { + var q: [257]u8 = @splat(0); + @memcpy(q[0..in.n], extra[0..in.n]); + var t: m.pardes_pdf_text = undefined; + var r: m.pardes_pdf_search_result = undefined; + if (in.op == .page) { // its text, and the pattern's hits' quads on it + if (m.pardes_pdf_page_text(ld, @intCast(in.page), &t) != ok) return answer(gpa, res, tail); + defer m.pardes_pdf_drop_text(ld, t.handle); + const found = in.n > 0 and m.pardes_pdf_search_page(ld, @intCast(in.page), &q, &r) == ok; + defer if (found) m.pardes_pdf_drop_search_result(ld, r.handle); + res.ok, res.n, res.hits = .{ 1, @intCast(t.len), if (found) @intCast(r.hit_count) else 0 }; + return answer(gpa, res, std.mem.concat(gpa, u8, &.{ t.data[0..t.len], if (found) std.mem.sliceAsBytes(r.quads[0..r.quad_count]) else "" }) catch return null); + } + // each page's count of hits, then the rows + var shown = @min(in.n, 200); + while (shown > 0 and shown < in.n and q[shown] & 0xc0 == 0x80) shown -= 1; + const counts = gpa.alloc(u32, in.page) catch return null; + var rows: std.ArrayList(u8) = .empty; + for (counts, 0..) |*count, p| { + if (@atomicLoad(c_int, &cookie.abort, .monotonic) != 0) return answer(gpa, .{}, ""); + count.* = 0; + if (m.pardes_pdf_search_page(ld, @intCast(p), &q, &r) != ok) continue; + defer m.pardes_pdf_drop_search_result(ld, r.handle); + count.* = @intCast(r.hit_count); + for (0..@min(r.hit_count, max_hits - res.hits)) |h| rows.print(gpa, "{s}:{d}:{d} {s}\n", .{ extra[in.n..], p + 1, h + 1, q[0..shown] }) catch return null; + res.hits += @intCast(@min(r.hit_count, max_hits - res.hits)); + } + res.ok, res.n = .{ 1, in.page }; + tail = std.mem.concat(gpa, u8, &.{ std.mem.sliceAsBytes(counts), rows.items }) catch return null; + }, + } + return answer(gpa, res, tail); + } + + pub fn jobDone(st: *Pdf, token: u32, bytes: []const u8) void { + const d = st.d orelse return; + const res = if (bytes.len >= @sizeOf(Out)) std.mem.bytesToValue(Out, bytes[0..@sizeOf(Out)]) else Out{}; + const extra = bytes[@min(bytes.len, @sizeOf(Out))..]; + const len = @as(usize, res.w) * 4 * res.band_h; + const px: [2][]u8 = .{ if (res.rgba) |p| p[0..len] else &.{}, if (res.clean) |p| p[0..len] else &.{} }; + for (px) |p| claim(d, p); + var kept = false; // (the pixels, a page's slot's) + defer if (!kept) for (px) |p| heap.free(p); + const at = for (st.jobs, 0..) |j, i| { + if (j.token == token) break i; + } else return; + const j = st.jobs[at]; + st.jobs[at] = .{}; + st.warm, st.go.landed = .{ true, true }; + const f = &st.find; + // (a busy lane's refusal is asked again) + if (res.ok == 0 and j.op != .render) { + if (res.busy != 0 and j.op == .search) f.due = true; + if (res.busy == 0 and j.op == .sizes) st.sizes_assumed = false; + return; + } + switch (j.op) { + .render => {}, + .sizes => { + st.sizes_assumed = false; + const sizes = std.mem.bytesAsSlice(m.pardes_pdf_page_size, extra[0..@min(extra.len, st.pages * @sizeOf(m.pardes_pdf_page_size))]); + if (res.n != st.pages or sizes.len != st.pages or std.mem.eql(u8, std.mem.sliceAsBytes(sizes), std.mem.sliceAsBytes(st.size))) return; + for (st.size, sizes) |*to, from| to.* = from; + for (&st.views) |*l| l.laid = false; + return; + }, + .page => { + if (extra.len < res.n) return; + heap.free(st.text.bytes); + st.text = .{ .bytes = heap.dupe(u8, extra[0..res.n]) catch &.{}, .page = j.page }; + st.text.lines = @intCast(std.mem.count(u8, st.text.bytes, "\n") + 1); + if (j.page != st.page or f.len == 0) return; + dropHits(st); + f.hits = heap.alloc(m.pardes_pdf_search_quad, (extra.len - res.n) / @sizeOf(m.pardes_pdf_search_quad)) catch return; + @memcpy(std.mem.sliceAsBytes(f.hits), extra[res.n..][0 .. f.hits.len * @sizeOf(m.pardes_pdf_search_quad)]); + f.hits_page, f.hit = .{ j.page, @min(f.hit, res.hits -| 1) }; + return; + }, + .search => { + if (res.n != st.pages or extra.len < st.pages * 4) return; + if (f.counts.len != st.pages) f.counts = addon.arena.alloc(u32, st.pages) catch return; + @memcpy(std.mem.sliceAsBytes(f.counts), extra[0 .. st.pages * 4]); + if (extra.len == st.pages * 4) return; + addon.found(extra[st.pages * 4 ..]); + // at its first hit, as a Look of its first row goes + goPage(st, @intCast(std.mem.indexOfNone(u32, f.counts, &.{0}) orelse 0)); + f.hit, f.reveal = .{ 0, true }; + return; + }, + } + const s = for (&st.s) |*s| { + if (s.job.token == token and s.view != 0) break s; + } else return; + s.job.token, s.job.failed = .{ 0, res.ok == 0 and res.busy == 0 }; + if (res.ok == 0) return; + for ([_][]const u8{ s.rgba, s.clean, std.mem.sliceAsBytes(s.shown) }) |p| heap.free(p); + const v = st.views[s.view - 1].v; + st.revs += 1; + s.rgba, s.clean, s.shown, s.asked, kept = .{ px[0], px[1], s.asked, &.{}, true }; + s.is = .{ .w = res.w, .h = res.h, .band_y = res.band_y, .band_h = res.band_h, .req = s.job.want, .tint = st.tint, .ink = @backingInt(v.fg), .paper = @backingInt(v.bg), .rev = st.revs }; + } +}; + +/// A job's answer: `res`, then `tail`, the last it allocates. +fn answer(gpa: std.mem.Allocator, res: Pdf.Out, tail: []const u8) ?[]u8 { + const a = gpa.alloc(u8, @sizeOf(Pdf.Out) + tail.len) catch return null; + @memcpy(a[0..@sizeOf(Pdf.Out)], std.mem.asBytes(&res)); + @memcpy(a[@sizeOf(Pdf.Out)..], tail); + return a; +} + +/// A page's band rendered on lane `ld`: its pixels the document's until its +/// pane takes them (`unclaimed`), or freed when its pane is gone. +fn render(d: *Doc, ld: ?*m.pardes_pdf_document, in: *const Pdf.In, marks: []const Mark, res: *Pdf.Out) void { + var L: m.pardes_pdf_raster_layout = undefined; + if (m.pardes_pdf_measure_render(ld, @intCast(in.page), &in.req, &L) != ok) return; + const full: u32 = @intCast(L.height); + const by = if (in.band_y < full) in.band_y else 0; + const bh = if (in.band_h != 0 and by + in.band_h <= full) in.band_h else full - by; + // a tall page's chunk renders past its edges, thrown away: a row is the + // same row however its band was cut + const cut = bh < full; + const ry = if (cut) by -| overlap else by; + const rb = if (cut and by + bh + overlap < full) by + bh + overlap else by + bh; + const stride: usize = @intCast(L.stride); + const len = stride * bh; + const px = heap.alloc(u8, @max(stride * (rb - ry), 1)) catch return; + var clean: []u8 = &.{}; + var good = m.pardes_pdf_render_into(ld, @intCast(in.page), &in.req, null, 0, px.ptr, px.len, L.width, L.height, L.stride, @intCast(ry), @intCast(rb - ry), 0) == ok; + if (good and ry != by) std.mem.copyForwards(u8, px[0..len], px[(by - ry) * stride ..][0..len]); + if (good and in.keep_clean != 0) { + clean = heap.dupe(u8, px[0..len]) catch &.{}; + good = clean.len == len; + } + if (good and marks.len > 0) good = m.pardes_pdf_paint_highlights(ld, @intCast(in.page), &in.req, marks.ptr, marks.len, px.ptr, len, L.width, L.height, L.stride, @intCast(by), @intCast(bh)) == ok; + if (good) tint(px[0..len], in.tint, in.ink, in.paper); + // kept for the pane, unless its document closed meanwhile + lock(); + var kept = good and !d.closed; + for ([_][]u8{ px, clean }) |p| if (kept and p.len > 0) { + const at = for (d.unclaimed, 0..) |u, i| { + if (u.len == 0) break i; + } else null; + if (at) |i| d.unclaimed[i] = p else kept = false; + }; + docs_lock.unlock(); + if (kept) { + res.* = .{ .ok = 1, .w = @intCast(L.width), .h = full, .band_y = by, .band_h = bh, .rgba = px.ptr, .clean = if (clean.len > 0) clean.ptr else null }; + return; + } + for ([_][]u8{ px, clean }) |p| { + claim(d, p); + heap.free(p); + } +} + +// ---- the strip ---- + +fn pageHeight(st: *const Pdf, l: *const Layout, p: usize) u32 { + if (st.fit_height) return l.vh; + const h = @round(f64Of(l.vw) * st.size[p].height / st.size[p].width); + return if (h < 1) 1 else if (h > 4e9) 4000000000 else @intFromFloat(h); +} + +fn pageAt(st: *const Pdf, l: *const Layout, y: f64) u32 { + if (st.pages == 0 or !l.laid) return st.page; + const at: u64 = @intFromFloat(std.math.clamp(@floor(y), 0, f64Of(l.height -| 1))); + var lo: usize = 0; + var hi: usize = st.pages; + while (lo + 1 < hi) { + const mid = lo + (hi - lo) / 2; + if (l.y[mid] <= at) lo = mid else hi = mid; + } + if (at >= l.y[lo] + l.ph[lo] and lo + 1 < st.pages) lo += 1; + return @intCast(lo); +} + +/// View `id`'s layout when it shows pictures and is laid out. +fn pixels(st: anytype, id: u8) ?@TypeOf(&st.views[0]) { + if (id < 1 or id > views_n) return null; + const l = &st.views[id - 1]; + return if (l.v.cols != 0 and !l.v.glyphs and l.laid) l else null; +} + +/// An input from view `id`: the view the place follows from now on; its +/// id, or the active one's when it was never told. +fn take(st: *Pdf, id: u8) u8 { + if (id >= 1 and id <= views_n and st.views[id - 1].v.cols != 0) st.active = id; + return st.active; +} + +/// The strip laid out for view `l`'s pixels, its top at the place (but in +/// the view the place was last moved in, whose top the place is). +fn layout(st: *Pdf, l: *Layout) void { + const vw = @as(u32, l.v.cols) * l.v.cell_w; + const vh = @as(u32, l.v.rows) * l.v.cell_h; + if (vw == 0 or vh == 0 or st.pages == 0 or l.v.glyphs) return; + if (l.y.len == 0) { + l.y = addon.arena.alloc(u64, st.pages) catch return; + l.ph = addon.arena.alloc(u32, st.pages) catch return; + } + if (!l.laid or vw != l.vw or vh != l.vh or st.fit_height != l.fit) { + l.vw, l.vh, l.fit, l.laid, l.rev = .{ vw, vh, st.fit_height, true, 0 }; + var at: u64 = 0; + for (l.y, l.ph, 0..) |*y, *ph, p| { + y.*, ph.* = .{ at, pageHeight(st, l, p) }; + at += ph.* + @as(u64, if (p + 1 < st.pages) gap_px else 0); + } + l.height = at; + } + if (l.rev != st.rev) { // a pixel's: P:F rounds + l.top = @round(f64Of(l.y[st.page]) + std.math.clamp(st.frac, 0, 1) * f64Of(l.ph[st.page])); + l.rev = st.rev; + } + l.top = std.math.clamp(l.top, 0, f64Of(l.height -| l.vh)); +} + +/// The place where view `l`'s window's top is (a move in it, or the strip's +/// end it stopped at). +fn placeFrom(st: *Pdf, l: *Layout) void { + if (!l.laid) return; + const p = pageAt(st, l, l.top); + const frac = (l.top - f64Of(l.y[p])) / f64Of(@max(l.ph[p], 1)); + if (p == st.page and frac == st.frac and l.rev == st.rev) return; + toPage(st, p); + st.frac = frac; + st.rev += 1; + l.rev = st.rev; +} + +/// The active view laid out at the place, and the place where its top is. +fn settle(st: *Pdf) void { + if (st.active < 1) return; + layout(st, &st.views[st.active - 1]); + if (pixels(st, st.active)) |l| placeFrom(st, l); +} + +fn setTop(st: *Pdf, l: *Layout, top: f64) void { + l.top = std.math.clamp(top, 0, f64Of(l.height -| l.vh)); + placeFrom(st, l); +} + +fn scrollBy(st: *Pdf, l: *Layout, px: f64) void { + if (!l.laid) return; + const was = l.top; + setTop(st, l, l.top + px); + st.go.since_tick += @abs(l.top - was); +} + +/// The page at the window's top is `p` now: what was the old one's goes. +fn toPage(st: *Pdf, p: u32) void { + if (p == st.page) return; + st.page = p; + dropHits(st); + st.find.hit, st.find.reveal = .{ 0, st.find.len > 0 }; +} + +fn goTo(st: *Pdf, p: u32, frac: f64) void { + toPage(st, p); + st.frac = frac; + st.rev += 1; + settle(st); +} + +/// Turn to page `p`, its top at the window's. +fn goPage(st: *Pdf, p: u32) void { + goTo(st, @min(p, st.pages - 1), 0); +} + +/// Down (dir 1) or up `n` steps of `px` pixels in view `l`; as text, a +/// page a step. +fn move(st: *Pdf, l: *Layout, dir: f64, px: f64, n: u32) void { + if (!l.v.glyphs) return scrollBy(st, l, dir * px * f64Of(n)); + goPage(st, @intCast(std.math.clamp(@as(i64, st.page) + @as(i64, @intFromFloat(dir)) * n, 0, st.pages - 1))); +} + +fn visible(st: *const Pdf, l: *const Layout) struct { usize, usize } { + if (!l.laid) return .{ 0, 0 }; + var p: usize = pageAt(st, l, l.top); + if (p > 0 and f64Of(l.y[p - 1] + l.ph[p - 1]) > l.top) p -= 1; + var n: usize = 0; + while (p + n < st.pages and f64Of(l.y[p + n]) < l.top + f64Of(l.vh)) n += 1; + return .{ p, n }; +} + +/// 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). +const Geo = struct { sx: u32, sy: u32, sw: u32, sh: u32, dx: u32, dy: u32, dw: u32, dh: u32 }; + +fn fitGeo(iw: u32, ih: u32, bw: u32, bh: u32, by_height: bool, pan: u16) ?Geo { + if (iw == 0 or ih == 0 or bw == 0 or bh == 0) return null; + // in the fitted axis's terms: its sides, then the other's + const a: [4]u64 = if (by_height) .{ ih, iw, bh, bw } else .{ iw, ih, bw, bh }; + if (a[1] * a[2] <= a[3] * a[0]) { + const full: u32 = @intCast(@max(a[1] * a[2] / a[0], 1)); + const off: u32 = @intCast((a[3] - full) / 2); + return if (by_height) .{ .sx = 0, .sy = 0, .sw = iw, .sh = ih, .dx = off, .dy = 0, .dw = full, .dh = bh } else .{ .sx = 0, .sy = 0, .sw = iw, .sh = ih, .dx = 0, .dy = off, .dw = bw, .dh = full }; + } + const crop = a[3] * a[0] / a[2]; + if (crop == 0) return null; + const cr: u32 = @intCast(@min(crop, a[1])); + const dd: u32 = @intCast(std.math.clamp(@as(u64, cr) * a[2] / a[0], 1, a[3])); + const off: u32 = @intCast((a[3] - dd) / 2); + if (!by_height) return .{ .sx = 0, .sy = 0, .sw = iw, .sh = cr, .dx = 0, .dy = off, .dw = bw, .dh = dd }; + const over = iw - cr; + const x: u32 = if (over == 0 or pan == 0) 0 else if (pan == 65535) over else @intCast((@as(u64, over) * pan + 32767) / 65535); + return .{ .sx = x, .sy = 0, .sw = cr, .sh = ih, .dx = off, .dy = 0, .dw = dd, .dh = bh }; +} + +/// Rows y0..y1 of page `p`'s raster over a window `vh` pixels tall, and +/// where (`at_y`, `at_h`); null when none of it is there. +const Rows = struct { g: Geo, y0: u32, y1: u32, at_y: u32, at_h: u32 }; + +fn pageRows(st: *const Pdf, l: *const Layout, p: u32, iw: u32, ih: u32, vh: u32) ?Rows { + const g = fitGeo(iw, ih, l.vw, l.ph[p], st.fit_height, st.pan) orelse return null; + if (g.dh == 0 or g.sh == 0) return null; + const full_y = @as(i64, @intCast(l.y[p])) - @as(i64, @intFromFloat(@floor(l.top))) + g.dy; + const vy = @max(full_y, 0); + const vb = @min(full_y + g.dh, vh); + if (vb <= vy) return null; + const ry0: u64 = @intCast(vy - full_y); + const ry1: u64 = @intCast(vb - full_y); + const y0 = g.sy + @as(u32, @intCast(ry0 * g.sh / g.dh)); + const y1 = g.sy + @as(u32, @intCast(@min((ry1 * g.sh + g.dh - 1) / g.dh, g.sh))); + return if (y1 > y0) .{ .g = g, .y0 = y0, .y1 = y1, .at_y = @intCast(vy), .at_h = @intCast(vb - vy) } else null; +} + +/// The raster page `p` renders to under `q`, as the bridge's geometry +/// computes it, give or take the rounding of its corners. +fn rasterOf(st: *const Pdf, p: usize, q: Request) [2]u32 { + const pw = st.size[p].width; + const ph = st.size[p].height; + const dpi: f32, const mw: f32, const mh: f32, const most: f32, const dw: f32, const dh: f32 = .{ @floatFromInt(q.dpi), @floatFromInt(q.minimum_width), @floatFromInt(q.minimum_height), @floatFromInt(q.max_dimension), @floatFromInt(q.display_width), @floatFromInt(q.display_height) }; + var scale = @max(dpi / 72, mw / pw, mh / ph); // (none is 0) + if (pw * scale > most) scale = most / pw; + if (ph * scale > most) scale = @min(scale, @max(most / ph, dw / pw, dh / ph)); + if (ph * scale > m.PARDES_PDF_MAX_RASTER_ROWS) scale = m.PARDES_PDF_MAX_RASTER_ROWS / ph; + return .{ @intFromFloat(@max(1, @round(pw * scale))), @intFromFloat(@max(1, @round(ph * scale))) }; +} + +// ---- highlights ---- + +/// Page `p`'s highlights in view `l`, as painted: the pointer's, the +/// search's, the selection's. +fn marksOf(st: *const Pdf, l: *const Layout, p: u32, out: []Mark) []Mark { + const f = struct { + fn mark(q: Quad, rgb: u32, a: u8, kind: c_int) Mark { + return .{ .quad = q, .rgba = .{ @truncate(rgb >> 16), @truncate(rgb >> 8), @truncate(rgb), a }, .kind = kind }; + } + }; + var n: usize = 0; + if (st.hover.page == p) { + out[0] = f.mark(st.hover.quad, @backingInt(if (st.hover.link) l.v.link else l.v.sel), 0x2c, m.PARDES_PDF_HIGHLIGHT_CUSTOM); + n = 1; + } + if (st.find.hits_page == p) for (st.find.hits[0..@min(st.find.hits.len, out.len - n)]) |h| { + out[n] = f.mark(h.quad, 0xffd54f, 0x70, m.PARDES_PDF_HIGHLIGHT_SEARCH); + n += 1; + }; + if (st.sel.page == p) for (st.sel.quads[0..@min(st.sel.quads.len, out.len - n)]) |q| { + out[n] = f.mark(q, @backingInt(l.v.sel), 0x78, m.PARDES_PDF_HIGHLIGHT_SELECTION); + n += 1; + }; + return out[0..n]; +} + +fn keepMarks(to: *[]Mark, now: []const Mark) bool { + const copy = heap.dupe(Mark, now) catch return false; + heap.free(to.*); + to.* = copy; + return true; +} + +// ---- jobs ---- + +/// Jobs out, or of `op` alone. +fn jobsOut(st: *const Pdf, op: ?Op) usize { + var n: usize = 0; + for (st.jobs) |j| n += @intFromBool(j.token != 0 and (op == null or j.op == op.?)); + return n; +} + +var ask_buf: [@sizeOf(Pdf.In) + marks_n * @sizeOf(Mark) + 512]u8 align(8) = undefined; // the loop's alone + +/// A job of `in` (`extra` and `more` after it) asked, when a lane is free: +/// its token, 0 when none could be. +fn ask(st: *Pdf, in_: Pdf.In, extra: []const u8, more: []const u8) u32 { + if (jobsOut(st, null) >= lanes) return 0; + const at = for (st.jobs, 0..) |j, i| { + if (j.token == 0) break i; + } else return 0; + var in = in_; + in.doc, in.cookie = .{ st.d.?.id, @intCast(at) }; + @atomicStore(c_int, &st.d.?.cookie[at].abort, 0, .monotonic); + var w: std.Io.Writer = .fixed(&ask_buf); + w.writeAll(std.mem.asBytes(&in)) catch {}; + w.writeAll(extra) catch {}; + w.writeAll(more) catch {}; + const token = addon.job(w.buffered()); + if (token != 0) st.jobs[at] = .{ .token = token, .op = in.op, .page = in.page }; + return token; +} + +fn abortJob(st: *Pdf, token: u32) void { + const d = st.d orelse return; + for (st.jobs, 0..) |j, i| if (token != 0 and j.token == token) @atomicStore(c_int, &d.cookie[i].abort, 1, .monotonic); +} + +/// 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. +fn bandOf(st: *const Pdf, l: *const Layout, p: u32, w: u32, h: u32) [2]u32 { + const cap = @min(c.PA_RASTER_MAX / (w * 4), band_rows) / chunk * chunk; + const r = pageRows(st, l, p, w, h, l.vh); + if (h <= cap) { + // flinging: the rows shown alone, on the grain + const rs = (if (st.go.fling) r else null) orelse return .{ 0, h }; + const y0 = rs.y0 / grain * grain; + return .{ y0, @min((rs.y1 + grain - 1) / grain * grain, h) - y0 }; + } + const seen = if (r) |rs| rs.y1 - rs.y0 else 0; + var y0 = (if (r) |rs| rs.y0 -| seen else 0) / chunk * chunk; + var y1 = ((if (r) |rs| rs.y1 + seen else chunk) + chunk - 1) / chunk * chunk; + if (y1 - y0 > cap) { + y0 = (if (r) |rs| rs.y0 else 0) / chunk * chunk; + y1 = y0 + cap; + } + return .{ y0, @min(y1, h) - y0 }; +} + +/// Only the highlights moved: their rows painted again from the clean copy +/// on the loop, never the page, and said as those rows. +fn repaint(st: *Pdf, s: *Slot, now: []const Mark) bool { + if (s.clean.len == 0 or s.rgba.len == 0) return false; + const both = struct { + var at: [2 * marks_n]Mark = undefined; // the loop's alone + }; + @memcpy(both.at[0..s.shown.len], s.shown); + @memcpy(both.at[s.shown.len..][0..now.len], now); + var y0: c_int = 0; + var y1: c_int = 0; + const base = st.d.?.base; + if (m.pardes_pdf_highlight_rows(base, @intCast(s.page), &s.is.req, &both.at, s.shown.len + now.len, &y0, &y1) != ok) return false; + const a: u32 = @max(@as(u32, @intCast(y0)), s.is.band_y); + const b: u32 = @min(@as(u32, @intCast(y1)), s.is.band_y + s.is.band_h); + if (b > a) { + const stride = @as(usize, s.is.w) * 4; + const px = s.rgba[(a - s.is.band_y) * stride ..][0 .. (b - a) * stride]; + @memcpy(px, s.clean[(a - s.is.band_y) * stride ..][0..px.len]); + if (m.pardes_pdf_paint_highlights(base, @intCast(s.page), &s.is.req, now.ptr, now.len, px.ptr, px.len, @intCast(s.is.w), @intCast(s.is.h), @intCast(stride), @intCast(a), @intCast(b - a)) != ok) { + heap.free(s.rgba); // half made: rendered again + s.rgba = &.{}; + return false; + } + tint(px, s.is.tint, s.is.ink, s.is.paper); + st.revs += 1; + s.is.from, s.is.rev, s.is.dirty_y, s.is.dirty_h = .{ s.is.rev, st.revs, a - s.is.band_y, b - a }; + } + return keepMarks(&s.shown, now); +} + +/// What view `id`'s window shows (and the page past it) made so: pages gone +/// dropped, highlights moved repainted, the rest asked of the lanes. +fn reconcile(st: *Pdf, l: *const Layout, id: u8) void { + const first, var n = visible(st, l); + if (n > 0 and first + n < st.pages and !st.go.fling) n += 1; // the page ahead, at rest + for (&st.s) |*s| if (s.view == id and (s.page < first or s.page >= first + n)) { + abortJob(st, s.job.token); + s.clear(); + }; + const q: Request = .{ + .dpi = if (l.v.dpi != 0) l.v.dpi else 96, + .minimum_width = if (l.v.fill) @intCast(l.vw) else 0, + .minimum_height = if (l.v.fill) @intCast(l.vh) else 0, + .max_dimension = if (l.v.max_px != 0) l.v.max_px else 1200, + .display_width = if (st.fit_height) 0 else @intCast(l.vw), + .display_height = if (st.fit_height) @intCast(l.vh) else 0, + }; + const now = struct { + var at: [marks_n]Mark = undefined; // the loop's alone + fn eq(a: []const Mark, b: []const Mark) bool { + return std.mem.eql(u8, std.mem.sliceAsBytes(a), std.mem.sliceAsBytes(b)); + } + }; + for (first..first + n) |pi| { + const p: u32 = @intCast(pi); + const s = for (&st.s) |*s| { + if (s.view == id and s.page == p) break s; + } else for (&st.s) |*s| { + if (s.view == 0) break s; + } else break; + s.view, s.page = .{ id, p }; + const same = s.rgba.len > 0 and std.meta.eql(s.is.req, q); + const wh = if (same) [2]u32{ s.is.w, s.is.h } else rasterOf(st, p, q); + const y, const bh = bandOf(st, l, p, wh[0], wh[1]); + const marks = marksOf(st, l, p, &now.at); + if (same and s.is.tint == st.tint and s.is.ink == @backingInt(l.v.fg) and s.is.paper == @backingInt(l.v.bg) and s.is.band_y <= y and s.is.band_y + s.is.band_h >= y + bh) { + if (now.eq(s.shown, marks) or repaint(st, s, marks)) continue; + } + if (s.job.token != 0) { + if (std.meta.eql(s.job.want, q) and s.job.y == y and s.job.h == bh and now.eq(s.asked, marks)) continue; + abortJob(st, s.job.token); + s.job.token = 0; + } + if (s.job.failed and std.meta.eql(s.job.want, q)) continue; + // a lane's first job parses the document and loads its fonts: the + // second starts once the first is warm + if (jobsOut(st, .render) >= @as(usize, if (st.warm) lanes else 1) or !keepMarks(&s.asked, marks)) continue; + const token = ask(st, .{ .op = .render, .page = p, .tint = st.tint, .req = q, .band_y = y, .band_h = bh, .ink = @backingInt(l.v.fg), .paper = @backingInt(l.v.bg), .keep_clean = @intFromBool(marks.len > 0 or s.clean.len > 0), .n = @intCast(marks.len) }, std.mem.sliceAsBytes(marks), ""); + if (token != 0) s.job.token, s.job.want, s.job.y, s.job.h, s.job.failed = .{ token, q, y, bh, false }; + } +} + +// ---- the search, the selection, the pointer ---- + +fn dropHits(st: *Pdf) void { + heap.free(st.find.hits); + st.find.hits, st.find.hits_page = .{ &.{}, null }; +} + +/// The search's hit `hit` in the window: centred (fit width), or panned to +/// (fit height). +fn revealHit(st: *Pdf) void { + st.find.reveal = false; + const l = pixels(st, st.active) orelse return; + const q = for (st.find.hits) |h| { + if (h.hit == st.find.hit) break h.quad; + } else return; + const cx = (q.ul.x + q.ur.x + q.ll.x + q.lr.x) / 4; + const cy = (q.ul.y + q.ur.y + q.ll.y + q.lr.y) / 4; + if (!st.fit_height) return setTop(st, l, f64Of(l.y[st.page]) + cy * f64Of(l.ph[st.page]) - f64Of(l.vh) / 2); + const s, const g = landed(st, st.active, st.page) orelse return; + const at: u32 = @intFromFloat(cx * f64Of(s.is.w)); + const over = s.is.w - g.sw; + if ((at >= g.sx and at < g.sx + g.sw) or over == 0) return; + st.pan = @intCast((@as(u64, @min(at -| g.sw / 2, over)) * 65535 + over / 2) / over); +} + +/// Page `p`'s pixels in view `id`, landed, and where they lie in it. +fn landed(st: *const Pdf, id: u8, p: usize) ?struct { *const Slot, Geo } { + const l = pixels(st, id) orelse return null; + for (&st.s) |*s| if (s.view == id and s.page == p and s.rgba.len > 0) + return .{ s, fitGeo(s.is.w, s.is.h, l.vw, l.ph[p], st.fit_height, st.pan) orelse return null }; + return null; +} + +fn counted(st: *Pdf) u32 { + defer st.count = 0; + return @max(st.count, 1); +} + +fn panBy(st: *Pdf, dir: i32, px: f64) void { + const s, const g = landed(st, st.active, st.page) orelse return; + const over = s.is.w - g.sw; + if (over == 0 or (dir < 0 and g.sx == 0) or (dir > 0 and g.sx >= over)) return; + const step = (@as(u64, @intFromFloat(px)) * g.sw + g.dw - 1) / @max(g.dw, 1); + const norm: i32 = @intCast(std.math.clamp((step * 65535 + over - 1) / over, 1, 65535)); + st.pan = @intCast(std.math.clamp(@as(i32, st.pan) + dir * norm, 0, 65535)); +} + +fn edge(st: *Pdf, end: bool) void { + const s, const g = landed(st, st.active, st.page) orelse return; + if (s.is.w > g.sw) st.pan = if (end) 65535 else 0; +} + +/// Esc: the selection and the search go first; with neither, it leaves. +fn cancel(st: *Pdf) bool { + const had = st.sel.quads.len > 0 or st.find.len > 0; + dropSel(st); + st.find.len, st.find.reveal, st.find.due = .{ 0, false, false }; + dropHits(st); + return had; +} + +fn dropSel(st: *Pdf) void { + const had = st.sel.quads.len > 0; + heap.free(st.sel.quads); + heap.free(st.sel.text); + st.sel = .{}; + if (had) addon.select(""); +} + +/// The page and its point under the middle of cell (col, row) of view `id`, +/// from where its pixels are shown; clamped to page `on` when given. +fn pointAt(st: *Pdf, id: u8, col: u16, row: u16, on: ?u32) ?struct { page: u32, pt: Point } { + const l = pixels(st, id) orelse return null; + const px = f64Of(@as(u32, col) * l.v.cell_w + l.v.cell_w / 2); + const py = f64Of(@as(u32, row) * l.v.cell_h + l.v.cell_h / 2); + const p = on orelse pageAt(st, l, l.top + py); + const s, const g = landed(st, id, p) orelse return null; + const left = f64Of(g.dx); + const top = f64Of(l.y[p]) - @floor(l.top) + f64Of(g.dy); + if (on == null and (px < left or px >= left + f64Of(g.dw) or py < top or py >= top + f64Of(g.dh))) return null; + const x = if (on == null) px else std.math.clamp(px, left, left + f64Of(g.dw) - 1.0 / 1024.0); + const y = if (on == null) py else std.math.clamp(py, top, top + f64Of(g.dh) - 1.0 / 1024.0); + const ix: u32 = @min(@as(u32, @intFromFloat(f64Of(g.sx) + (x - left) * f64Of(g.sw) / f64Of(g.dw))), s.is.w - 1); + const iy: u32 = @min(@as(u32, @intFromFloat(f64Of(g.sy) + (y - top) * f64Of(g.sh) / f64Of(g.dh))), s.is.h - 1); + return .{ .page = p, .pt = .{ .x = @floatCast((f64Of(ix) + 0.5) / f64Of(s.is.w)), .y = @floatCast((f64Of(iy) + 0.5) / f64Of(s.is.h)) } }; +} + +/// The selection from the anchor to `to` on `page`, word-snapped by MuPDF; +/// what it holds handed to pardes. +fn selectTo(st: *Pdf, page: u32, to: Point) bool { + const base = st.d.?.base; + var sel: m.pardes_pdf_selection = undefined; + if (m.pardes_pdf_select(base, @intCast(page), st.sel.anchor, to, &sel) != ok) return false; + defer m.pardes_pdf_drop_selection(base, sel.handle); + var t: m.pardes_pdf_owned_text = undefined; + if (m.pardes_pdf_copy_selection(base, @intCast(page), sel.start, sel.end, &t) != ok) return false; + defer m.pardes_pdf_drop_owned_text(base, t.handle); + heap.free(st.sel.quads); + heap.free(st.sel.text); + st.sel.quads = heap.dupe(Quad, sel.quads[0..sel.quad_count]) catch &.{}; + st.sel.text = heap.dupe(u8, t.data[0..t.len]) catch &.{}; + st.sel.page, st.sel.tip = .{ page, to }; + addon.select(t.data[0..t.len]); + return true; +} + +fn selContains(st: *const Pdf, page: u32, pt: Point) bool { + if (st.sel.page != page) return false; + for (st.sel.quads) |q| if (m.pardes_pdf_point_inside_quad(pt, q) != 0) return true; + return false; +} + +/// The word or link under a cell of view `id`: its quad and its text +/// (heap), and the link when it is one. +fn probeAt(st: *Pdf, id: u8, col: u16, row: u16) ?struct { page: u32, quad: Quad, text: []u8, link: ?m.pardes_pdf_link } { + const at = pointAt(st, id, col, row, null) orelse return null; + const base = st.d.?.base; + var link: m.pardes_pdf_link = undefined; + var t: m.pardes_pdf_owned_text = undefined; + if (m.pardes_pdf_link_at(base, @intCast(at.page), at.pt, &link) == ok and link.uri != null and link.uri_len < 1024 and link.destination_kind != m.PARDES_PDF_OUTLINE_DESTINATION_NONE) { + // (its URI borrowed from the page's links, kept until the next probe) + const uri = struct { + var buf: [1024]u8 = undefined; + }; + @memcpy(uri.buf[0..link.uri_len], link.uri[0..link.uri_len]); + link.uri = &uri.buf; + var text: []u8 = &.{}; + if (m.pardes_pdf_copy_rectangle(base, @intCast(at.page), link.quad, &t) == ok) { + text = heap.dupe(u8, t.data[0..t.len]) catch &.{}; + m.pardes_pdf_drop_owned_text(base, t.handle); + } + return .{ .page = at.page, .quad = link.quad, .text = text, .link = link }; + } + var sel: m.pardes_pdf_selection = undefined; + if (m.pardes_pdf_select(base, @intCast(at.page), at.pt, at.pt, &sel) != ok) return null; + defer m.pardes_pdf_drop_selection(base, sel.handle); + if (sel.quad_count == 0 or m.pardes_pdf_copy_selection(base, @intCast(at.page), sel.start, sel.end, &t) != ok) return null; + defer m.pardes_pdf_drop_owned_text(base, t.handle); + if (t.len == 0) return null; + return .{ .page = at.page, .quad = sel.quads[0], .text = heap.dupe(u8, t.data[0..t.len]) catch return null, .link = null }; +} + +/// 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. +fn follow(st: *Pdf, link: m.pardes_pdf_link, text: []const u8) void { + if (link.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) return goToXY(st, @intCast(link.page), link.has_x != 0, link.x, link.has_y != 0, link.y); + const uri = link.uri[0..link.uri_len]; + var shown: [512]u8 = undefined; + var k: usize = 0; + for (text) |ch| if (ch > ' ' and k < shown.len) { + shown[k] = ch; + k += 1; + }; + var both: [1600]u8 = undefined; + if (k > 0 and std.mem.indexOf(u8, shown[0..k], "://") != null and !std.mem.eql(u8, shown[0..k], uri)) if (std.fmt.bufPrint(&both, "{s}\n{s}\n", .{ shown[0..k], uri })) |rows| { + _ = addon.text("+Links", rows); + return; + } else |_| {}; + addon.look(uri); +} + +/// Page `p` at an outline's or a link's point of it: its height (the +/// window's top there) and, fit height, how far across. +fn goToXY(st: *Pdf, page: u32, has_x: bool, x: f32, has_y: bool, y: f32) void { + const p = @min(page, st.pages - 1); + const size = st.size[p]; + if (has_x and st.fit_height and std.math.isFinite(x)) if (pixels(st, st.active)) |l| { + const shown = f64Of(l.vh) * size.width / size.height; + const over = shown - f64Of(l.vw); + const want = std.math.clamp(x, 0, size.width) / size.width * shown - f64Of(l.vw) / 2; + if (over > 0) st.pan = @intFromFloat(@round(std.math.clamp(want, 0, over) / over * 65535)); + }; + goTo(st, p, if (has_y and std.math.isFinite(y)) std.math.clamp(y, 0, size.height) / size.height else 0); +} + +// ---- the outline ---- + +/// 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. +fn usable(o: *const m.pardes_pdf_outline_result, i: usize) bool { + const it = o.items[i]; + if (it.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) return true; + if (it.destination_kind != m.PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL or it.uri_len == 0 or it.uri_len > 256) return false; + const u = o.bytes[it.uri_offset..][0..it.uri_len]; + return (std.mem.startsWith(u8, u, "http://") or std.mem.startsWith(u8, u, "https://")) and for (u) |ch| { + if (ch <= 0x20 or ch == 0x7f) break false; + } else true; +} + +/// Entry `i`'s place: its own, else the first usable one below it. +fn resolve(o: *const m.pardes_pdf_outline_result, i: usize) ?usize { + if (o.items[i].destination_kind != m.PARDES_PDF_OUTLINE_DESTINATION_NONE) return if (usable(o, i)) i else null; + var k = i + 1; + while (k < o.item_count and o.items[k].depth > o.items[i].depth) : (k += 1) if (usable(o, k)) return k; + return null; +} + +fn sections(st: *Pdf) void { + const base = st.d.?.base; + var o: m.pardes_pdf_outline_result = undefined; + if (m.pardes_pdf_load_outline(base, &o) != ok) return addon.say("PdfSections: this PDF has no outline", .err); + defer m.pardes_pdf_drop_outline_result(base, o.handle); + const rows = heap.alloc(u8, o.item_count * 300 + 1) catch return; + defer heap.free(rows); + var w: std.Io.Writer = .fixed(rows); + for (o.items[0..o.item_count], 0..) |it, i| { + const to = o.items[resolve(&o, i) orelse continue]; + if (to.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) w.print("{s}:{d}:{d} ", .{ st.name, to.page + 1, i + 1 }) catch {} else w.print("{s} ", .{o.bytes[to.uri_offset..][0..to.uri_len]}) catch {}; + w.splatByteAll(' ', 2 * it.depth) catch {}; + // the title on one line: control and invalid characters a space + // between words, none at either end + const t = o.bytes[it.title_offset..][0..it.title_len]; + const start = w.end; + var gap = false; + var i_: usize = 0; + while (it.title_present != 0 and i_ < t.len) { + const k = std.unicode.utf8ByteSequenceLength(t[i_]) catch 0; + if (k > 0 and i_ + k > t.len) break; + defer i_ += @max(k, 1); + const ch = (if (k > 0) std.unicode.utf8Decode(t[i_..][0..k]) catch null else null) orelse 0; + if (ch <= 0x20 or ch == 0x7f or (ch >= 0x80 and ch <= 0x9f) or ch == 0x2028 or ch == 0x2029) { + gap = w.end > start; + } else if (w.end + k + 1 - start <= 255) { + if (gap) w.writeByte(' ') catch {}; + w.writeAll(t[i_..][0..k]) catch {}; + gap = false; + } + } + if (w.end == start) w.writeAll(if (it.title_present != 0) "[empty title]" else "[untitled]") catch {}; + w.writeByte('\n') catch {}; + } + if (w.end == 0) return addon.say("PdfSections: this PDF has no outline", .err); + _ = addon.text("+PdfSections", w.buffered()); +} + +/// A +PdfSections row's place: page P, section S, which must be on it. +fn section(st: *Pdf, page: u32, ord: u32) bool { + const base = st.d.?.base; + var o: m.pardes_pdf_outline_result = std.mem.zeroes(m.pardes_pdf_outline_result); + defer if (o.handle != null) m.pardes_pdf_drop_outline_result(base, o.handle); + var said: [200]u8 = undefined; + const r = if (m.pardes_pdf_load_outline(base, &o) == ok and ord > 0 and ord <= o.item_count) resolve(&o, ord - 1) else null; + const to = o.items[r orelse return miss(std.fmt.bufPrint(&said, "PdfSections: {s} has no section {d}", .{ st.name, ord }))]; + if (to.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL) { + addon.look(o.bytes[to.uri_offset..][0..@min(to.uri_len, 256)]); + return true; + } + if (to.page + 1 != page) return miss(std.fmt.bufPrint(&said, "PdfSections: section {d} of {s} is on page {d}, not {d}", .{ ord, st.name, to.page + 1, page })); + dropSel(st); + goToXY(st, @intCast(to.page), to.has_x != 0, to.x, to.has_y != 0, to.y); + return true; +} + +/// A miss said (an error): no place here. +fn miss(said: anyerror![]const u8) bool { + addon.say(said catch "", .err); + return false; +} + +fn none() bool { + return miss("has no text to address; its address is a page, :N"); +} @@ -469,7 +469,12 @@ 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 + // The kinds' C ABI (src/kinds/pardes_addon.h), translated once: the core's + // records are the header's, never a mirror of it. + const kind_mod = b.addTranslateC(.{ .root_source_file = b.path("src/kinds/pardes_addon.h"), .target = target, .optimize = optimize }).createModule(); + // ...and what an addon in Zig imports over it (src/kinds/addon.zig). + const addon_mod = b.createModule(.{ .root_source_file = b.path("src/kinds/addon.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "pardes_addon", .module = kind_mod }} }); + // The PDF addon (addons/pdf/pdf.zig over MuPDF through pdf_bridge.c), built // and installed as the image addon is: compiled only for a step that // needs it (`pdf`, the tests), though fetched at the first configure, // which Zig runs alike for every step. MuPDF is compiled against the @@ -489,25 +494,19 @@ pub fn build(b: *std.Build) void { .zlib = zlib, .pic = true, }); - 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"} }); + // The bridge's header translated here for pdf.zig (Zig 0.17 has no + // @cImport), as the kinds' header is for the core. + const bridge_mod = b.addTranslateC(.{ .root_source_file = b.path("addons/pdf/pdf_bridge.h"), .target = target, .optimize = c_optimize }).createModule(); + const pdf_mod = b.createModule(.{ .root_source_file = b.path("addons/pdf/pdf.zig"), .target = target, .optimize = c_optimize, .link_libc = true, .imports = &.{ .{ .name = "addon", .module = addon_mod }, .{ .name = "pdf_bridge", .module = bridge_mod } } }); + mupdf.linkTo(pdf_mod); + pdf_mod.addIncludePath(b.path("addons/pdf")); + pdf_mod.addCSourceFile(.{ .file = b.path("addons/pdf/pdf_bridge.c"), .flags = &.{"-std=gnu11"} }); + const lib = b.addLibrary(.{ .name = "pdf", .linkage = .dynamic, .root_module = pdf_mod }); lib.setVersionScript(b.addWriteFiles().add("pdf.map", "{ global: pardes_addon; local: *; };\n")); pdf_addon = lib; - // ...and for a static pardes the same C compiled into it, its - // export renamed: it is one of two in a binary (Addon.zig). - if (static_mod) |m| { - const in = b.addLibrary(.{ .name = "pdf-builtin", .linkage = .static, .root_module = b.createModule(.{ .target = target, .optimize = c_optimize, .link_libc = true }) }); - mupdf.linkTo(in.root_module); - in.root_module.addIncludePath(b.path("src/kinds")); - in.root_module.addIncludePath(b.path("addons/pdf")); - in.root_module.addCSourceFile(.{ .file = b.path("addons/pdf/pdf.c"), .flags = &.{ "-std=gnu11", "-Wall", "-Wextra", "-Werror", "-Dpardes_addon=pardes_addon_pdf" } }); - in.root_module.addCSourceFile(.{ .file = b.path("addons/pdf/pdf_bridge.c"), .flags = &.{"-std=gnu11"} }); - m.linkLibrary(in); - } + // ...and for a static pardes the same module compiled into it, + // which exports nothing there (Addon.zig reads its declaration). + if (static_mod) |m| m.addImport("pdf_addon", pdf_mod); mupdf_check.dependOn(mupdf_build.addProbe(b, mupdf, .{ .target = target, .pdf = b.path("docs/design.pdf"), @@ -831,11 +830,6 @@ pub fn build(b: *std.Build) void { // One call per module instead of one line per module per dependency, and // BEFORE the fold below, which reads what these imports put in the table. - // The kinds' C ABI (src/kinds/pardes_addon.h), translated once: the core's - // records are the header's, never a mirror of it. - const kind_mod = b.addTranslateC(.{ .root_source_file = b.path("src/kinds/pardes_addon.h"), .target = target, .optimize = optimize }).createModule(); - // ...and what an addon in Zig imports over it (src/kinds/addon.zig). - const addon_mod = b.createModule(.{ .root_source_file = b.path("src/kinds/addon.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "pardes_addon", .module = kind_mod }} }); // The image addon (addons/image/image.zig over stb_image, stb.c), // installed by its step and handed by path to every test that opens a // picture. diff --git a/src/Addon.zig b/src/Addon.zig index 030da7d4..04cffcb9 100644 --- a/src/Addon.zig +++ b/src/Addon.zig @@ -178,8 +178,7 @@ var nfound: usize = 0; /// addon's module and the PDF's C, its `pardes_addon` renamed. A static /// binary cannot dlopen, and macOS's loader has no memfd: this is how /// either has image and PDF panes. -const compiled_in: []const *const Kind.Ops = if (@import("builtin_addons").on) &.{ &@import("image_addon").pardes_addon, &pardes_addon_pdf } else &.{}; -extern const pardes_addon_pdf: Kind.Ops; +const compiled_in: []const *const Kind.Ops = if (@import("builtin_addons").on) &.{ &@import("image_addon").pardes_addon, &@import("pdf_addon").pardes_addon } else &.{}; /// The addons compiled in, as if loaded (`builtin` their path); else every /// library of the two directories, in name order each, the user's first. A diff --git a/test/behaviour/addons_pdf.zig b/test/behaviour/addons_pdf.zig index 7b92b84c..48b75806 100644 --- a/test/behaviour/addons_pdf.zig +++ b/test/behaviour/addons_pdf.zig @@ -1,6 +1,6 @@ //! docs/typ/reference.typ, Addons <addons> and the PDF passages of Panes //! <panes> and Look and exec <look-and-exec>: a PDF is a pane of the pdf -//! addon (addons/pdf/pdf.c), driven here as a 9P client drives it. What +//! addon (addons/pdf/pdf.zig), driven here as a 9P client drives it. What //! test/pdf.zig asked of the core's PDF code before it left the core. const std = @import("std"); const Session = @import("session").Session; diff --git a/test/panes.zig b/test/panes.zig index 3e147c95..2da7a313 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -3720,7 +3720,7 @@ test "a terminal keeps its tag and two body rows through a squeeze, a drag and a try std.testing.expect(p.view().rects[term].h >= p.panes[term].?.tag_rows + layout.min_body_rows); } -// ---- a PDF: a pane of the pdf addon (addons/pdf/pdf.c) ---- +// ---- a PDF: a pane of the pdf addon (addons/pdf/pdf.zig) ---- const PdfAddon = struct { const addons = @import("test_addons"); diff --git a/test/session.zig b/test/session.zig index 8c71cfb1..8e03b424 100644 --- a/test/session.zig +++ b/test/session.zig @@ -403,7 +403,7 @@ pub const Session = struct { // pdf: - /// The pdf addon (addons/pdf/pdf.c), as the build makes it; none + /// The pdf addon (addons/pdf/pdf.zig), as the build makes it; none /// before the build has fetched MuPDF. pub const pdf_addon: ?[]const u8 = if (@import("session_options").has_pdf_addon) @import("session_options").pdf_addon else null; |
