diff options
| -rw-r--r-- | addons/pdf/pdf.zig | 977 | ||||
| -rw-r--r-- | src/Kind.zig | 12 | ||||
| -rw-r--r-- | src/dump.zig | 5 | ||||
| -rw-r--r-- | test/behaviour/addons_pdf.zig | 3 | ||||
| -rw-r--r-- | test/panes.zig | 48 | ||||
| -rw-r--r-- | test/session.zig | 15 |
6 files changed, 675 insertions, 385 deletions
diff --git a/addons/pdf/pdf.zig b/addons/pdf/pdf.zig index d7125de5..c9a49b7c 100644 --- a/addons/pdf/pdf.zig +++ b/addons/pdf/pdf.zig @@ -2,27 +2,33 @@ //! (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 from the line -//! the place names. 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 wheel's whole notches glide there over four ticks; 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. +//! A pane's state is one plain block (`Pdf`, PA_PLAIN: a client runs the +//! kind as its session does): one place, a page and how far down it (what +//! `where` says and `address` takes), shown by each of its views its own +//! way; its fit, tint, search, selection, pointer and glide. Everything +//! else is each process's own (`Own`, found by the block's address): the +//! document, its pages' sizes, what the state jobs answered, the pictures. +//! 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); each process paints the pages it shows from +//! rasters it asks of its own lanes as it paints (draws, never on the +//! tape); a view of glyphs (a terminal without graphics) shows the page's +//! text layer from the line the place names. 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 +//! the session's jobs, their answers on the tape. A key, the mouse and a +//! tick read no picture: where a page's raster lies is MuPDF's measure of +//! it. 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 as the view is painted 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 wheel's whole notches glide there on the ticks' clock +//! (half at once, all within 48 ms); a fling (a window's travel or more in +//! 16 ms) 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"); @@ -102,7 +108,7 @@ fn tint(px: []u8, mode: Tint, ink: u32, paper: u32) void { /// `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(&.{}) }; +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 + slots_n]m.pardes_pdf_cookie = std.mem.zeroes([jobs_n + slots_n]m.pardes_pdf_cookie), unclaimed: [24][]u8 = @splat(&.{}) }; var docs_lock: std.atomic.Mutex = .unlocked; var docs: [64]?*Doc = @splat(null); @@ -152,87 +158,70 @@ fn claim(d: *Doc, p: []const u8) void { docs_lock.unlock(); } -// ---- a pane ---- +// ---- a pane: its record (the block, PA_PLAIN) ---- -/// 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.* = .{}; - } -}; +const none = std.math.maxInt(u32); +const no_button: u8 = 255; +/// The pages' sizes the strip is laid with: the first's for all while a +/// lane measures them (`asking`), measured, or the first's for good (the +/// lane could not). +const Sizes = enum(u8) { asking, measured, assumed }; /// 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 }; +/// `vw` x `vh` pixels (`fit`, height): its height and its pixel at the +/// window's top, laid at the place's `rev`. Each page's top and height on +/// it are each process's own (`Strip`), made from these and the sizes. +const Layout = extern struct { top: f64 = 0, height: u64 = 0, v: addon.View = std.mem.zeroes(addon.View), vw: u32 = 0, vh: u32 = 0, rev: u32 = 0, laid: bool = false, fit: bool = false, _: [2]u8 = @splat(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 }; +const Job = extern 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 pane's whole state: one block, the same in every process that shows +/// it (a client runs the kind as the session does), changed only by the +/// kind's calls, from what they are handed. Its pictures, its document and +/// what the state jobs answered are each process's own (`Own`). No padding +/// (`plainBlock`): its bytes are hashed. +pub const Pdf = extern struct { /// 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, + /// for the pane whatever views show it; `rev` moves at each change; + /// `active` the view of the last input (an id), else the first told, + /// whose window's top the place follows. 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, + /// A wheel's glide and a fling, on the ticks' clock: `glide` pixels + /// still to go in view `glide_view`, of `glide0` when it started at + /// `glide_at` (0: at the next tick); the strip's travel in the 16 ms + /// window from `window_at`, a window's height of it a fling. + go: extern struct { since_tick: f64 = 0, travel: f64 = 0, glide: f64 = 0, glide0: f64 = 0, window_at: u64 = 0, glide_at: u64 = 0, fling: bool = false, landed: bool = false, glide_view: u8 = 0, _: [5]u8 = @splat(0) } = .{}, + /// The pointer's word or link where it rests: `wait` 1 moved, 2 + /// resting until `at`. + hover: extern struct { at: u64 = 0, quad: Quad = std.mem.zeroes(Quad), page: u32 = none, col: u16 = 0, row: u16 = 0, link: bool = false, wait: u8 = 0, view: u8 = 0, _: u8 = 0, _2: u32 = 0 } = .{}, + /// The state jobs out (sizes, a page's text and hits, the search). 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 } } = .{}, + /// The search: its pattern, the page whose hits are in (`hits` of + /// them), the one gone to, and whether each page's count has come. + find: extern struct { query: [256]u8 = @splat(0), len: u32 = 0, hits_page: u32 = none, hit: u32 = 0, hits: u32 = 0, due: bool = false, reveal: bool = false, counted: bool = false, _: u8 = 0 } = .{}, + /// The selection: `anchor` to `tip` as the button moves, and the one + /// made (`page`, from `from` to `to`, `n` quads; none: no selection). + sel: extern struct { anchor: Point = .{ .x = 0, .y = 0 }, tip: Point = .{ .x = 0, .y = 0 }, from: Point = .{ .x = 0, .y = 0 }, to: Point = .{ .x = 0, .y = 0 }, page: u32 = none, n: u32 = 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. A glide: a wheel's - /// pixels still to go in a view, half each frame, all by its 4th tick. - go: struct { since_tick: f64 = 0, travel: f64 = 0, framed: bool = false, landed: bool = false, fling: bool = false, glide: f64 = 0, glide_n: u8 = 0, glide_view: u8 = 0 } = .{}, + press: extern struct { page: u32 = none, col: u16 = 0, row: u16 = 0, button: u8 = no_button, chorded: bool = false, look: bool = false, _: u8 = 0 } = .{}, + /// The page whose text is in, and its lines. + text: extern struct { page: u32 = none, lines: u32 = 0 } = .{}, + pages: u32 = 0, + page: u32 = 0, + rev: u32 = 1, count: u32 = 0, // a key's count, typed before it + tint: Tint = .filtered, + pan: u16 = 0, // fit height: how far across, 0..65535 + active: u8 = 0, + fit_height: bool = false, + sizes: Sizes = .asking, g: bool = false, + _: [6]u8 = @splat(0), - pub const head: addon.Head = .{ .name = "pdf", .version = 1, .exts = ".pdf", .pictures = true, .words = &.{ + pub const head: addon.Head = .{ .name = "pdf", .version = 1, .exts = ".pdf", .pictures = true, .plain = 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)" }, @@ -256,7 +245,11 @@ pub const Pdf = struct { } 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 o = for (&owns) |*o| { + if (o.of == null) break o; + } else return addon.say("too many PDFs open", .err); + o.* = .{ .of = st }; + if (path) |p| o.name = heap.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; @@ -271,53 +264,57 @@ pub const Pdf = struct { 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) { + o.size = if (d.id != 0) heap.alloc(m.pardes_pdf_page_size, @intCast(pages)) catch &.{} else &.{}; + if (o.size.len == 0 or m.pardes_pdf_get_page_size(d.base, 0, &o.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; + o.d = d; + st.pages = @intCast(pages); // every page the first's size until a lane measures them - @memset(st.size[1..], st.size[0]); - st.sizes_assumed = st.pages > 1; + o.measured = st.pages == 1; + st.sizes = if (st.pages > 1) .asking else .measured; } pub fn close(st: *Pdf) void { - for (&st.s) |*s| s.clear(); + const o = ownOf(st); + for (&o.s) |*s| { + abortDraw(o, 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; + for ([_][]const u8{ o.name, std.mem.sliceAsBytes(o.size), o.text.bytes, o.read.bytes, std.mem.sliceAsBytes(o.counts), std.mem.sliceAsBytes(o.hits), std.mem.sliceAsBytes(o.sel_quads), o.sel_text }) |p| heap.free(p); + for (&o.strips) |*sp| sp.free(); + if (o.d) |d| docDrop(d, true); + o.* = .{}; } - pub fn tick(st: *Pdf, now: u64, flags: addon.Flags) u64 { - if (st.d == null) return 0; + pub fn tick(st: *Pdf, now: u64, _: addon.Flags) u64 { + if (st.pages == 0) return 0; const go = &st.go; + // A glide on the ticks' clock: half at once, then half a frame, + // all of it from its 4th tick (48 ms) on. if (go.glide != 0) if (pixels(st, go.glide_view)) |l| { - go.glide_n += 1; - const step = if (go.glide_n >= 4) go.glide else if (flags.framed) go.glide / 2 else 0; - go.glide -= step; + if (go.glide_at == 0) go.glide_at, go.glide0 = .{ now, go.glide }; + const t = now -| go.glide_at; + const left = if (t >= 3 * frame_ns) 0 else go.glide0 * std.math.pow(f64, 0.5, 1 + f64Of(t) / f64Of(frame_ns)); + const step = go.glide - left; + go.glide = left; scrollBy(st, l, step); } else { go.glide = 0; }; - // 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; + // A fling is a window's travel or more in 16 ms of the ticks' + // clock; a tick a state job's answer made (no turn since) neither + // starts nor ends one. if (!(go.landed and go.since_tick == 0)) { - if (go.framed) go.travel = 0; - go.framed = false; + if (now -| go.window_at >= frame_ns) go.travel, go.window_at = .{ 0, now }; 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 }; + for (&st.views, 0..) |*l, k| layout(st, l, k); const hv = &st.hover; if (hv.wait == 1) hv.wait, hv.at = .{ 2, now + hover_ns }; if (hv.wait == 2 and now >= hv.at) { @@ -330,15 +327,15 @@ pub const Pdf = struct { 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. + // text and hits, the search. Its pictures each process asks for as + // it paints them. const query = f.query[0..f.len]; - if (st.sizes_assumed and jobsOut(st, .sizes) == 0) _ = ask(st, .{ .op = .sizes, .page = st.pages }, "", ""); + if (st.sizes == .asking 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)); + if (f.due and ask(st, .{ .op = .search, .page = st.pages, .n = f.len }, query, ownOf(st).name) != 0) f.due = false; var next: u64 = if (hv.wait == 2) hv.at else 0; if (go.glide != 0) next = now + frame_ns; // flinging: a tick when it rests, for the whole pages @@ -347,7 +344,7 @@ pub const Pdf = struct { } 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 }); + if (st.pages != 0) 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 @@ -356,8 +353,9 @@ pub const Pdf = struct { 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); + const o = ownOf(st); + for (&o.s) |*s| if (s.view == v.id) { + abortDraw(o, s); s.clear(); }; st.views[v.id - 1].laid = false; @@ -368,15 +366,18 @@ pub const Pdf = struct { } else 0; } + /// The view's pictures made so (asked of the lanes as draws, the + /// highlights painted again), then placed; a glyph view's page text. 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 o = ownOf(st); + if (st.pages == 0 or o.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; + out.pointer = if (st.hover.page != none and st.hover.link) c.PA_POINTER_LINK else c.PA_POINTER_DEFAULT; if (win.glyphs) { // the page's text layer, from the place's line (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; + const t = pageText(o, st.page); var at: usize = 0; for (0..lineOf(st)) |_| at = if (std.mem.indexOfScalarPos(u8, t, at, '\n')) |nl| nl + 1 else t.len; for (0..win.rows) |row| { @@ -398,20 +399,25 @@ pub const Pdf = struct { } const l = &st.views[win.view - 1]; if (!l.laid) return; + const sp = stripOf(st, o, win.view - 1); + // white tinted is the theme's paper + const paper: u32 = if (st.tint == .disabled) 0xffffff else if (pixels(st, st.active)) |a| @backingInt(a.v.bg) else 0xffffff; + o.blank = .{ @truncate(paper >> 16), @truncate(paper >> 8), @truncate(paper), 255 }; + reconcile(st, o, l, sp, win.view); const vh = @min(@as(u32, win.rows) * win.cell_h, l.vh); - const first, const count = visible(st, l); + const first, const count = visible(st, l, sp); for (first..first + count) |p| { const k = @as(u64, p) << 32; - const s = if (landed(st, win.view, p)) |at| at[0] else null; + const s = if (landed(o, win.view, p)) |sl| sl 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 wh: [2]u32 = if (s) |sl| .{ sl.is.w, sl.is.h } else .{ @intFromFloat(@max(1, @round(sizeOf(st, o, p).width * 8))), @intFromFloat(@max(1, @round(sizeOf(st, o, p).height * 8))) }; + const r = pageRows(st, l, sp, @intCast(p), wh[0], wh[1], vh) orelse continue; + const paper_pl = std.mem.zeroInit(c.pa_placement, .{ .rgba = &o.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); + into.place(paper_pl); continue; }; - var pl = paper; + var pl = paper_pl; 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 }; @@ -421,7 +427,7 @@ pub const Pdf = struct { } // 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); + into.place(paper_pl); 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; @@ -437,7 +443,7 @@ pub const Pdf = struct { } pub fn key(st: *Pdf, k: addon.Key) bool { - if (st.d == null) return false; + if (st.pages == 0) 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); @@ -497,7 +503,7 @@ pub const Pdf = struct { } pub fn mouse(st: *Pdf, ev: addon.Mouse) bool { - if (st.d == null) return false; + if (st.pages == 0) 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; @@ -509,7 +515,7 @@ pub const Pdf = struct { const cell: f64 = if (l.v.cell_h != 0) f64Of(l.v.cell_h) else 16; if (l.v.glyphs) move(st, l, dir, 0, @intFromFloat(@max(1, @round(notches))), true) else if (notches != @floor(notches)) scrollBy(st, l, dir * notches * cell) else { st.go.glide += dir * notches * cell; - st.go.glide_n, st.go.glide_view = .{ 0, id }; + st.go.glide_at, st.go.glide_view = .{ 0, id }; } return true; }, @@ -521,21 +527,21 @@ pub const Pdf = struct { } 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 }; + const here = ev.col == st.hover.col and ev.row == st.hover.row and (st.hover.wait != 0 or st.hover.page != none); + if (ev.col == 0xffff) st.hover = .{} else if (pr.button == no_button 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 + if (pr.button != no_button) { // 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"); + if (ev.button == .middle and st.sel.n > 0) addon.exec("ClipYank"); return true; } - pr.* = .{ .button = ev.button, .look = ev.button == .right, .col = ev.col, .row = ev.row }; + pr.* = .{ .button = @backingInt(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; + pr.button = no_button; return true; }; pr.page = at.page; @@ -544,7 +550,7 @@ pub const Pdf = struct { return true; } if (ev.action == .drag) { - if (pr.button == null or pr.chorded) return true; + if (pr.button == no_button or pr.chorded) return true; if (pr.look) { if (ev.col == pr.col and ev.row == pr.row) return true; pr.look = false; @@ -552,11 +558,13 @@ pub const Pdf = struct { 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 (pr.page == none) return true; + const at = pointAt(st, id, ev.col, ev.row, pr.page) 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 (pr.button == no_button) return true; + const was: Button = @fromBackingInt(pr.button); if (ev.action != .release) return true; const held = pr.*; pr.* = .{}; @@ -567,9 +575,10 @@ pub const Pdf = struct { 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) { + } else if (st.sel.page != none) { // the selection, looked at (B3) or run (B2) - if (was == .right) addon.look(st.sel.text) else addon.exec(st.sel.text); + const text = selOf(st, ownOf(st)).text; + if (text.len > 0) if (was == .right) addon.look(text) else addon.exec(text); } return true; } @@ -577,43 +586,35 @@ pub const Pdf = struct { /// 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; + if (st.pages == 0) return ""; + return pageText(ownOf(st), st.page); } /// `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; + if (st.pages == 0) 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 page = std.fmt.parseInt(u32, t[0..colon], 10) catch return noText(); 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(); + const f = std.fmt.parseFloat(f64, rest) catch return noText(); 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; + const second = if (colon < t.len) std.fmt.parseInt(u32, rest, 10) catch return noText() 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 })); + if (second > 0 and (f.len == 0 or !f.counted or countsOf(st, ownOf(st))[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 }; @@ -624,15 +625,15 @@ pub const Pdf = struct { /// (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; + if (st.pages == 0) 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 shown: f64 = if (pixels(st, st.active)) |l| f64Of(l.vh) / f64Of(@max(stripOf(st, ownOf(st), st.active - 1).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; + if (st.pages == 0) 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")) { @@ -663,12 +664,12 @@ pub const Pdf = struct { /// 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 (st.pages == 0 or pat.len == 0 or pat.len > 255) return; if (!std.mem.eql(u8, f.query[0..f.len], pat)) { + @memset(&f.query, 0); @memcpy(f.query[0..pat.len], pat); f.len = @intCast(pat.len); - dropHits(st); - @memset(f.counts, 0); + f.hits_page, f.counted = .{ none, false }; f.hit, f.reveal = .{ 0, true }; } // (a page's job asked its hits of the pattern before) @@ -680,22 +681,26 @@ pub const Pdf = struct { f.due = true; } - // ---- the record: its fit, tint and place ---- + // ---- the record a dump keeps: 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; + if (st.pages == 0 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. + /// on disk): its fit, tint and place, from its record or its block (a + /// session's dump keeps a plain kind's block). 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 (st.pages == 0) return false; + const r: Record = if (bytes.len == @sizeOf(Pdf)) r: { + const b = std.mem.bytesToValue(Pdf, bytes[0..@sizeOf(Pdf)]); + break :r .{ .version = record_version, .fit = @intFromBool(b.fit_height), .tint = @min(@backingInt(b.tint), 3), .page = b.page, .frac = b.frac }; + } else if (bytes.len >= @sizeOf(Record)) std.mem.bytesToValue(Record, bytes[0..@sizeOf(Record)]) else return false; 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); @@ -728,7 +733,7 @@ pub const Pdf = struct { 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]; + const cookie = &d.cookie[in.cookie % d.cookie.len]; if (m.pardes_pdf_lane_open(ld) != ok) return answer(gpa, res, tail); switch (in.op) { .render => { @@ -777,76 +782,327 @@ pub const Pdf = struct { return answer(gpa, res, tail); } + /// A state job's answer, on every process alike (it is on the tape), + /// or a draw's (`addon.drawn`), this process's pictures alone. pub fn jobDone(st: *Pdf, token: u32, bytes: []const u8) void { - const d = st.d orelse return; + const o = ownOf(st); + const d = o.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 ours = res.doc == d.id; - const px: [2][]u8 = .{ if (res.rgba) |p| (if (ours) p[0..len] else &.{}) else &.{}, if (res.clean) |p| (if (ours) p[0..len] else &.{}) 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); + o.warm = true; + if (token & addon.drawn != 0) return drawn(o, d, token, res); 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 }; + st.go.landed = true; const f = &st.find; // (a busy lane's refusal is asked again) - if (res.ok == 0 and j.op != .render) { + if (res.ok == 0) { if (res.busy != 0 and j.op == .search) f.due = true; - if (res.busy == 0 and j.op == .sizes) st.sizes_assumed = false; + if (res.busy == 0 and j.op == .sizes) st.sizes = .assumed; return; } switch (j.op) { .render => {}, .sizes => { - st.sizes_assumed = false; + st.sizes = .measured; 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; + if (res.n != st.pages or sizes.len != st.pages) return; + for (o.size, sizes) |*to, from| to.* = from; + o.measured = true; + // laid again where a page is not the first's size + for (o.size) |s| if (!std.meta.eql(s, o.size[0])) { + 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); + heap.free(o.text.bytes); + o.text = .{ .bytes = heap.dupe(u8, extra[0..res.n]) catch &.{}, .page = j.page }; + st.text = .{ .page = j.page, .lines = @intCast(std.mem.count(u8, extra[0..res.n], "\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; + heap.free(o.hits); + o.hits = heap.alloc(m.pardes_pdf_search_quad, (extra.len - res.n) / @sizeOf(m.pardes_pdf_search_quad)) catch &.{}; + @memcpy(std.mem.sliceAsBytes(o.hits), extra[res.n..][0 .. o.hits.len * @sizeOf(m.pardes_pdf_search_quad)]); + o.hits_of = .{ .page = j.page, .query = f.query }; + f.hits_page, f.hit, f.hits = .{ j.page, @min(f.hit, res.hits -| 1), res.hits }; }, .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 (o.counts.len != st.pages) { + heap.free(o.counts); + o.counts = heap.alloc(u32, st.pages) catch &.{}; + } + if (o.counts.len != st.pages) return; + @memcpy(std.mem.sliceAsBytes(o.counts), extra[0 .. st.pages * 4]); + o.counts_of = f.query; + f.counted = true; 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)); + goPage(st, @intCast(std.mem.indexOfNone(u32, o.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 or !ours) 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 }; } }; +/// The block has no padding: every byte of it is a field's, so two +/// processes that set the same fields hash the same bytes. +fn plainBlock(comptime T: type) void { + var sum: usize = 0; + for (@typeInfo(T).@"struct".field_types) |F| { + sum += @sizeOf(F); + switch (@typeInfo(F)) { + .@"struct" => plainBlock(F), + .array => |a| if (@typeInfo(a.child) == .@"struct") plainBlock(a.child), + else => {}, + } + } + if (sum != @sizeOf(T)) @compileError(std.fmt.comptimePrint("{s} has {d} bytes of padding", .{ @typeName(T), @sizeOf(T) - sum })); +} +comptime { + plainBlock(Pdf); +} + +// ---- each process's own: its document, its pictures, what jobs answered ---- + +/// 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 draw +/// 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's strip as laid at its record's pixels: each page's top (`y`) +/// and height (`ph`), made again when the record's layout is not the one +/// it was made for. +const Strip = struct { + y: []u64 = &.{}, + ph: []u32 = &.{}, + vw: u32 = 0, + vh: u32 = 0, + fit: bool = false, + sizes: Sizes = .asking, + height: u64 = 0, + + fn free(sp: *Strip) void { + heap.free(sp.y); + heap.free(sp.ph); + sp.* = .{}; + } +}; + +/// What a pane's process holds beside its block, found by the block's +/// address: functions of the file and the block, never read by a key, the +/// mouse or a tick but through these (`stripOf`, `rasterOf`, `pageText`, +/// `hitsOf`, `countsOf`, `selOf`), which make what they lack again (a +/// client joined late has none of what the state jobs answered before). +const Own = struct { + of: ?*const Pdf = null, + d: ?*Doc = null, + name: []u8 = &.{}, // the file's, in the rows a pane lists + /// Every page's size: the first's measured at the open, all of them + /// once `measured`. + size: []m.pardes_pdf_page_size = &.{}, + measured: bool = false, + strips: [views_n]Strip = @splat(.{}), + s: [slots_n]Slot = @splat(.{}), + revs: u32 = 0, + 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 read's own, made here. + text: Text = .{}, + read: Text = .{}, + /// Each page's count of hits of `counts_of`; the quads of the hits of + /// `hits_of` on its page. + counts: []u32 = &.{}, + counts_of: [256]u8 = @splat(0), + hits: []m.pardes_pdf_search_quad = &.{}, + hits_of: struct { page: u32 = none, query: [256]u8 = @splat(0) } = .{}, + /// The selection made: its quads and text, of `sel_of`. + sel_quads: []Quad = &.{}, + sel_text: []u8 = &.{}, + sel_of: struct { page: u32 = none, from: Point = .{ .x = 0, .y = 0 }, to: Point = .{ .x = 0, .y = 0 } } = .{}, + /// The raster a page renders to under a request (MuPDF's measure). + raster: struct { page: u32 = none, q: Request = std.mem.zeroes(Request), wh: [2]u32 = .{ 0, 0 } } = .{}, +}; + +/// A page's text, and its lines. +const Text = struct { bytes: []u8 = &.{}, page: u32 = none }; + +var owns: [64]Own = @splat(.{}); +var spare: Own = .{}; + +fn ownOf(st: *const Pdf) *Own { + for (&owns) |*o| if (o.of == st) return o; + spare = .{}; + return &spare; +} + +/// Page `p`'s size as the strip is laid with it. +fn sizeOf(st: *const Pdf, o: *Own, p: usize) m.pardes_pdf_page_size { + if (st.sizes != .measured) return o.size[0]; + // A client joined after the lane measured them: measured here. + if (!o.measured) { + for (o.size, 0..) |*s, i| _ = m.pardes_pdf_get_page_size(o.d.?.base, @intCast(i), s); + o.measured = true; + } + return o.size[p]; +} + +fn stripOf(st: *const Pdf, o: *Own, k: usize) *Strip { + const l = &st.views[k]; + const sp = &o.strips[k]; + if (sp.y.len == st.pages and sp.vw == l.vw and sp.vh == l.vh and sp.fit == l.fit and sp.sizes == st.sizes) return sp; + if (sp.y.len != st.pages) { + sp.free(); + sp.y = heap.alloc(u64, st.pages) catch return sp; + sp.ph = heap.alloc(u32, st.pages) catch { + sp.free(); + return sp; + }; + } + sp.vw, sp.vh, sp.fit, sp.sizes = .{ l.vw, l.vh, l.fit, st.sizes }; + var at: u64 = 0; + for (sp.y, sp.ph, 0..) |*y, *ph, p| { + y.*, ph.* = .{ at, pageHeight(st, o, l, p) }; + at += ph.* + @as(u64, if (p + 1 < st.pages) gap_px else 0); + } + sp.height = at; + return sp; +} + +/// Page `p`'s raster under view `l`'s request, as MuPDF measures it (the +/// size its pixels land at): what a key's pan and a click read. +fn rasterWH(st: *const Pdf, o: *Own, l: *const Layout, p: u32) ?[2]u32 { + const q = requestOf(st, l); + if (o.raster.page == p and std.meta.eql(o.raster.q, q)) return o.raster.wh; + var L: m.pardes_pdf_raster_layout = undefined; + if (m.pardes_pdf_measure_render((o.d orelse return null).base, @intCast(p), &q, &L) != ok) return null; + o.raster = .{ .page = p, .q = q, .wh = .{ @intCast(L.width), @intCast(L.height) } }; + return o.raster.wh; +} + +/// Page `page`'s text: the job's, else read here. +fn pageText(o: *Own, page: u32) []const u8 { + if (o.text.page == page) return o.text.bytes; + if (o.read.page == page) return o.read.bytes; + heap.free(o.read.bytes); + o.read = .{ .page = page }; + const d = o.d orelse return ""; + var t: m.pardes_pdf_text = undefined; + if (m.pardes_pdf_page_text(d.base, @intCast(page), &t) != ok) return ""; + defer m.pardes_pdf_drop_text(d.base, t.handle); + o.read.bytes = heap.dupe(u8, t.data[0..t.len]) catch &.{}; + return o.read.bytes; +} + +/// The search's hits on its page (`find.hits_page`): the job's quads, else +/// found here. +fn hitsOf(st: *const Pdf, o: *Own) []const m.pardes_pdf_search_quad { + const f = &st.find; + if (f.hits_page == none) return &.{}; + if (o.hits_of.page == f.hits_page and std.mem.eql(u8, &o.hits_of.query, &f.query)) return o.hits; + heap.free(o.hits); + o.hits = &.{}; + o.hits_of = .{ .page = f.hits_page, .query = f.query }; + const d = o.d orelse return &.{}; + var q: [257]u8 = @splat(0); + @memcpy(q[0..f.len], f.query[0..f.len]); + var r: m.pardes_pdf_search_result = undefined; + if (m.pardes_pdf_search_page(d.base, @intCast(f.hits_page), &q, &r) != ok) return &.{}; + defer m.pardes_pdf_drop_search_result(d.base, r.handle); + o.hits = heap.dupe(m.pardes_pdf_search_quad, r.quads[0..r.quad_count]) catch &.{}; + return o.hits; +} + +/// Each page's count of the search's hits: the job's, else counted here. +fn countsOf(st: *const Pdf, o: *Own) []const u32 { + const f = &st.find; + if (o.counts.len == st.pages and std.mem.eql(u8, &o.counts_of, &f.query)) return o.counts; + heap.free(o.counts); + o.counts = heap.alloc(u32, st.pages) catch &.{}; + @memset(o.counts, 0); + o.counts_of = f.query; + const d = o.d orelse return o.counts; + var q: [257]u8 = @splat(0); + @memcpy(q[0..f.len], f.query[0..f.len]); + for (o.counts, 0..) |*n, p| { + var r: m.pardes_pdf_search_result = undefined; + if (m.pardes_pdf_search_page(d.base, @intCast(p), &q, &r) != ok) continue; + n.* = @intCast(r.hit_count); + m.pardes_pdf_drop_search_result(d.base, r.handle); + } + return o.counts; +} + +/// The selection made: its quads and text, MuPDF's from the block's. +fn selOf(st: *const Pdf, o: *Own) struct { quads: []const Quad, text: []const u8 } { + const s = &st.sel; + if (s.page == none) return .{ .quads = &.{}, .text = "" }; + if (o.sel_of.page != s.page or !std.meta.eql(o.sel_of.from, s.from) or !std.meta.eql(o.sel_of.to, s.to)) { + heap.free(o.sel_quads); + heap.free(o.sel_text); + o.sel_quads, o.sel_text = .{ &.{}, &.{} }; + o.sel_of = .{ .page = s.page, .from = s.from, .to = s.to }; + _ = selectHere(o, s.page, s.from, s.to); + } + return .{ .quads = o.sel_quads, .text = o.sel_text }; +} + +/// MuPDF's selection from `from` to `to` on `page`, word-snapped, into +/// `o`: its quads, or null. +fn selectHere(o: *Own, page: u32, from: Point, to: Point) ?usize { + const base = (o.d orelse return null).base; + var sel: m.pardes_pdf_selection = undefined; + if (m.pardes_pdf_select(base, @intCast(page), from, to, &sel) != ok) return null; + 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 null; + defer m.pardes_pdf_drop_owned_text(base, t.handle); + o.sel_quads = heap.dupe(Quad, sel.quads[0..sel.quad_count]) catch &.{}; + o.sel_text = heap.dupe(u8, t.data[0..t.len]) catch &.{}; + return sel.quad_count; +} + +/// A draw's answer: a page's pixels for its slot. +fn drawn(o: *Own, d: *Doc, token: u32, res: Pdf.Out) void { + const len = @as(usize, res.w) * 4 * res.band_h; + const ours = res.doc == d.id; + const px: [2][]u8 = .{ if (res.rgba) |p| (if (ours) p[0..len] else &.{}) else &.{}, if (res.clean) |p| (if (ours) p[0..len] else &.{}) 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 s = for (&o.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 or !ours) return; + for ([_][]const u8{ s.rgba, s.clean, std.mem.sliceAsBytes(s.shown) }) |p| heap.free(p); + const v = o.of.?.views[s.view - 1].v; + o.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 = o.of.?.tint, .ink = @backingInt(v.fg), .paper = @backingInt(v.bg), .rev = o.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; @@ -902,22 +1158,23 @@ fn render(d: *Doc, ld: ?*m.pardes_pdf_document, in: *const Pdf.In, marks: []cons // ---- the strip ---- -fn pageHeight(st: *const Pdf, l: *const Layout, p: usize) u32 { +fn pageHeight(st: *const Pdf, o: *Own, 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); + const size = sizeOf(st, o, p); + const h = @round(f64Of(l.vw) * size.height / size.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 { +fn pageAt(st: *const Pdf, l: *const Layout, sp: *const Strip, 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 (sp.y[mid] <= at) lo = mid else hi = mid; } - if (at >= l.y[lo] + l.ph[lo] and lo + 1 < st.pages) lo += 1; + if (at >= sp.y[lo] + sp.ph[lo] and lo + 1 < st.pages) lo += 1; return @intCast(lo); } @@ -928,6 +1185,11 @@ fn pixels(st: anytype, id: u8) ?@TypeOf(&st.views[0]) { return if (l.v.cols != 0 and !l.v.glyphs and l.laid) l else null; } +/// View `l`'s strip, this process's. +fn stripFor(st: *const Pdf, l: *const Layout) *Strip { + return stripOf(st, ownOf(st), (@intFromPtr(l) - @intFromPtr(&st.views)) / @sizeOf(Layout)); +} + /// 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 { @@ -937,25 +1199,17 @@ fn take(st: *Pdf, id: u8) u8 { /// 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 { +fn layout(st: *Pdf, l: *Layout, k: usize) 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; + l.height = stripOf(st, ownOf(st), k).height; } 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])); + const sp = stripOf(st, ownOf(st), k); + l.top = @round(f64Of(sp.y[st.page]) + std.math.clamp(st.frac, 0, 1) * f64Of(sp.ph[st.page])); l.rev = st.rev; } l.top = std.math.clamp(l.top, 0, f64Of(l.height -| l.vh)); @@ -965,8 +1219,9 @@ fn layout(st: *Pdf, l: *Layout) void { /// 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)); + const sp = stripFor(st, l); + const p = pageAt(st, l, sp, l.top); + const frac = (l.top - f64Of(sp.y[p])) / f64Of(@max(sp.ph[p], 1)); if (p == st.page and frac == st.frac and l.rev == st.rev) return; toPage(st, p); st.frac = frac; @@ -977,7 +1232,7 @@ fn placeFrom(st: *Pdf, l: *Layout) void { /// 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]); + layout(st, &st.views[st.active - 1], st.active - 1); if (pixels(st, st.active)) |l| placeFrom(st, l); } @@ -997,7 +1252,7 @@ fn scrollBy(st: *Pdf, l: *Layout, px: f64) void { fn toPage(st: *Pdf, p: u32) void { if (p == st.page) return; st.page = p; - dropHits(st); + st.find.hits_page = none; st.find.hit, st.find.reveal = .{ 0, st.find.len > 0 }; } @@ -1032,12 +1287,12 @@ fn move(st: *Pdf, l: *Layout, dir: f64, px: f64, n: u32, line: bool) void { goTo(st, st.page, f64Of(std.math.clamp(at + @as(i64, @intFromFloat(dir)) * n, 0, @max(last, 0))) / f64Of(st.text.lines)); } -fn visible(st: *const Pdf, l: *const Layout) struct { usize, usize } { +fn visible(st: *const Pdf, l: *const Layout, sp: *const Strip) 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 p: usize = pageAt(st, l, sp, l.top); + if (p > 0 and f64Of(sp.y[p - 1] + sp.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; + while (p + n < st.pages and f64Of(sp.y[p + n]) < l.top + f64Of(l.vh)) n += 1; return .{ p, n }; } @@ -1070,10 +1325,10 @@ fn fitGeo(iw: u32, ih: u32, bw: u32, bh: u32, by_height: bool, pan: u16) ?Geo { /// 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; +fn pageRows(st: *const Pdf, l: *const Layout, sp: *const Strip, p: u32, iw: u32, ih: u32, vh: u32) ?Rows { + const g = fitGeo(iw, ih, l.vw, sp.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 full_y = @as(i64, @intCast(sp.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; @@ -1084,11 +1339,24 @@ fn pageRows(st: *const Pdf, l: *const Layout, p: u32, iw: u32, ih: u32, vh: u32) return if (y1 > y0) .{ .g = g, .y0 = y0, .y1 = y1, .at_y = @intCast(vy), .at_h = @intCast(vb - vy) } else null; } +/// What view `l` asks a page's raster at. +fn requestOf(st: *const Pdf, l: *const Layout) Request { + return .{ + .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, + }; +} + /// 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; +fn rasterOf(st: *const Pdf, o: *Own, p: usize, q: Request) [2]u32 { + const size = sizeOf(st, o, p); + const pw = size.width; + const ph = size.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; @@ -1101,7 +1369,7 @@ fn rasterOf(st: *const Pdf, p: usize, q: Request) [2]u32 { /// 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 { +fn marksOf(st: *const Pdf, o: *Own, 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 }; @@ -1112,14 +1380,20 @@ fn marksOf(st: *const Pdf, l: *const Layout, p: u32, out: []Mark) []Mark { 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; - }; + if (st.find.hits_page == p) { + const hits = hitsOf(st, o); + for (hits[0..@min(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) { + const quads = selOf(st, o).quads; + for (quads[0..@min(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]; } @@ -1130,7 +1404,7 @@ fn keepMarks(to: *[]Mark, now: []const Mark) bool { return true; } -// ---- jobs ---- +// ---- jobs and draws ---- /// Jobs out, or of `op` alone. fn jobsOut(st: *const Pdf, op: ?Op) usize { @@ -1141,16 +1415,17 @@ fn jobsOut(st: *const Pdf, op: ?Op) usize { 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. +/// A state 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 { + const d = ownOf(st).d orelse return 0; 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); + in.doc, in.cookie = .{ d.id, @intCast(at) }; + @atomicStore(c_int, &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 {}; @@ -1160,17 +1435,42 @@ fn ask(st: *Pdf, in_: Pdf.In, extra: []const u8, more: []const u8) u32 { return token; } -fn abortJob(st: *Pdf, token: u32) void { - const d = st.d orelse return; +fn abortJob(st: *const Pdf, token: u32) void { + const d = ownOf(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); } +/// Slot `s`'s page rendered on a draw (`in`, `extra` after it): its +/// token, 0 when refused. +fn drawAsk(o: *Own, s: *const Slot, in_: Pdf.In, extra: []const u8) u32 { + const d = o.d orelse return 0; + const at = jobs_n + (@intFromPtr(s) - @intFromPtr(&o.s)) / @sizeOf(Slot); + var in = in_; + in.doc, in.cookie = .{ d.id, @intCast(at) }; + @atomicStore(c_int, &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 {}; + return addon.draw(w.buffered()); +} + +fn abortDraw(o: *Own, s: *const Slot) void { + const d = o.d orelse return; + if (s.job.token != 0) @atomicStore(c_int, &d.cookie[jobs_n + (@intFromPtr(s) - @intFromPtr(&o.s)) / @sizeOf(Slot)].abort, 1, .monotonic); +} + +fn drawsOut(o: *const Own) usize { + var n: usize = 0; + for (o.s) |s| n += @intFromBool(s.job.token != 0); + return n; +} + /// 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 { +fn bandOf(st: *const Pdf, l: *const Layout, sp: *const Strip, 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); + const r = pageRows(st, l, sp, 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 }; @@ -1189,7 +1489,7 @@ fn bandOf(st: *const Pdf, l: *const Layout, p: u32, w: u32, h: u32) [2]u32 { /// 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 { +fn repaint(o: *Own, 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 @@ -1198,7 +1498,7 @@ fn repaint(st: *Pdf, s: *Slot, now: []const Mark) bool { @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; + const base = o.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); @@ -1212,29 +1512,23 @@ fn repaint(st: *Pdf, s: *Slot, now: []const Mark) bool { 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 }; + o.revs += 1; + s.is.from, s.is.rev, s.is.dirty_y, s.is.dirty_h = .{ s.is.rev, o.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); +/// What view `id`'s window shows (and the page past it) made so, as it is +/// painted: pages gone dropped, highlights moved repainted, the rest asked +/// of the lanes as draws. +fn reconcile(st: *const Pdf, o: *Own, l: *const Layout, sp: *const Strip, id: u8) void { + const first, var n = visible(st, l, sp); 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); + for (&o.s) |*s| if (s.view == id and (s.page < first or s.page >= first + n)) { + abortDraw(o, s); 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 q = requestOf(st, l); const now = struct { var at: [marks_n]Mark = undefined; // the loop's alone fn eq(a: []const Mark, b: []const Mark) bool { @@ -1243,74 +1537,79 @@ fn reconcile(st: *Pdf, l: *const Layout, id: u8) void { }; for (first..first + n) |pi| { const p: u32 = @intCast(pi); - const s = for (&st.s) |*s| { + const s = for (&o.s) |*s| { if (s.view == id and s.page == p) break s; - } else for (&st.s) |*s| { + } else for (&o.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); + const wh = if (same) [2]u32{ s.is.w, s.is.h } else rasterOf(st, o, p, q); + const y, const bh = bandOf(st, l, sp, p, wh[0], wh[1]); + const marks = marksOf(st, o, 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 (now.eq(s.shown, marks) or repaint(o, 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); + abortDraw(o, s); 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 (drawsOut(o) >= @as(usize, if (o.warm) lanes else 1) or !keepMarks(&s.asked, marks)) continue; + const token = drawAsk(o, s, .{ .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| { + const o = ownOf(st); + const q = for (hitsOf(st, o)) |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; + const sp = stripFor(st, l); + if (!st.fit_height) return setTop(st, l, f64Of(sp.y[st.page]) + cy * f64Of(sp.ph[st.page]) - f64Of(l.vh) / 2); + const wh = rasterWH(st, o, l, st.page) orelse return; + const g = fitGeo(wh[0], wh[1], l.vw, sp.ph[st.page], st.fit_height, st.pan) orelse return; + const at: u32 = @intFromFloat(cx * f64Of(wh[0])); + const over = wh[0] - 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 }; +/// Page `p`'s pixels in view `id`, landed (a paint's). +fn landed(o: *const Own, id: u8, p: usize) ?*const Slot { + for (&o.s) |*s| if (s.view == id and s.page == p and s.rgba.len > 0) return s; return null; } +/// The active view's page as its raster lies in its box: what a pan +/// moves (MuPDF's measure of the raster, never a picture landed). +fn panGeo(st: *Pdf) ?struct { w: u32, g: Geo } { + const l = pixels(st, st.active) orelse return null; + const wh = rasterWH(st, ownOf(st), l, st.page) orelse return null; + return .{ .w = wh[0], .g = fitGeo(wh[0], wh[1], l.vw, stripFor(st, l).ph[st.page], st.fit_height, st.pan) orelse 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; + const pg = panGeo(st) orelse return; + const g = pg.g; + const over = pg.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)); @@ -1318,67 +1617,65 @@ fn panBy(st: *Pdf, dir: i32, px: f64) void { } 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; + const pg = panGeo(st) orelse return; + if (pg.w > pg.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; + const had = st.sel.n > 0 or st.find.len > 0; dropSel(st); - st.find.len, st.find.reveal, st.find.due = .{ 0, false, false }; - dropHits(st); + st.find.len, st.find.reveal, st.find.due, st.find.hits_page = .{ 0, false, false, none }; return had; } fn dropSel(st: *Pdf) void { - const had = st.sel.quads.len > 0; - heap.free(st.sel.quads); - heap.free(st.sel.text); + const had = st.sel.n > 0; 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. +/// in its raster as MuPDF measures it; 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 o = ownOf(st); + const sp = stripOf(st, o, id - 1); 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 p = on orelse pageAt(st, l, sp, l.top + py); + const wh = rasterWH(st, o, l, p) orelse return null; + const g = fitGeo(wh[0], wh[1], l.vw, sp.ph[p], st.fit_height, st.pan) orelse return null; const left = f64Of(g.dx); - const top = f64Of(l.y[p]) - @floor(l.top) + f64Of(g.dy); + const top = f64Of(sp.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)) } }; + const ix: u32 = @min(@as(u32, @intFromFloat(f64Of(g.sx) + (x - left) * f64Of(g.sw) / f64Of(g.dw))), wh[0] - 1); + const iy: u32 = @min(@as(u32, @intFromFloat(f64Of(g.sy) + (y - top) * f64Of(g.sh) / f64Of(g.dh))), wh[1] - 1); + return .{ .page = p, .pt = .{ .x = @floatCast((f64Of(ix) + 0.5) / f64Of(wh[0])), .y = @floatCast((f64Of(iy) + 0.5) / f64Of(wh[1])) } }; } /// 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]); + const o = ownOf(st); + heap.free(o.sel_quads); + heap.free(o.sel_text); + o.sel_quads, o.sel_text = .{ &.{}, &.{} }; + o.sel_of = .{ .page = page, .from = st.sel.anchor, .to = to }; + const n = selectHere(o, page, st.sel.anchor, to) orelse { + o.sel_of = .{}; + return false; + }; + st.sel.page, st.sel.from, st.sel.to, st.sel.n, st.sel.tip = .{ page, st.sel.anchor, to, @intCast(n), to }; + addon.select(o.sel_text); 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; + for (selOf(st, ownOf(st)).quads) |q| if (m.pardes_pdf_point_inside_quad(pt, q) != 0) return true; return false; } @@ -1386,7 +1683,7 @@ fn selContains(st: *const Pdf, page: u32, pt: Point) bool { /// (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; + const base = (ownOf(st).d orelse return null).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) { @@ -1436,7 +1733,7 @@ fn follow(st: *Pdf, link: m.pardes_pdf_link, text: []const u8) void { /// 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]; + const size = sizeOf(st, ownOf(st), 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); @@ -1470,7 +1767,7 @@ fn resolve(o: *const m.pardes_pdf_outline_result, i: usize) ?usize { } fn sections(st: *Pdf) void { - const base = st.d.?.base; + const base = (ownOf(st).d orelse return).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); @@ -1479,7 +1776,7 @@ fn sections(st: *Pdf) void { 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 {}; + if (to.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) w.print("{s}:{d}:{d} ", .{ ownOf(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 @@ -1509,17 +1806,17 @@ fn sections(st: *Pdf) void { /// 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; + const base = (ownOf(st).d orelse return false).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 }))]; + const to = o.items[r orelse return miss(std.fmt.bufPrint(&said, "PdfSections: {s} has no section {d}", .{ ownOf(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 })); + if (to.page + 1 != page) return miss(std.fmt.bufPrint(&said, "PdfSections: section {d} of {s} is on page {d}, not {d}", .{ ord, ownOf(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; @@ -1531,6 +1828,6 @@ fn miss(said: anyerror![]const u8) bool { return false; } -fn none() bool { +fn noText() bool { return miss("has no text to address; its address is a page, :N"); } diff --git a/src/Kind.zig b/src/Kind.zig index a3d20f30..233365c7 100644 --- a/src/Kind.zig +++ b/src/Kind.zig @@ -400,6 +400,7 @@ pub fn close(p: *Pardes, pane: *Pane) void { while (i < ready.items.len) if (ready.items[i].draw == p and ready.items[i].serial == pane.serial) ready.orderedRemove(i).drop() else { i += 1; }; + if (ready.items.len == 0) ready.clearAndFree(heap); } if (s.ops) |ops| if (ops.close) |f| if (!kept) { var cl: Call = .{ .p = null, .id = 0, .slot = s, .quiet = true }; @@ -438,9 +439,15 @@ pub fn draw(p: *Pardes, s: *surface.Surface, arena: std.mem.Allocator, pane: *Pa const text = if (p.kinds.byName(slot.nameOf()) != null) why else std.fmt.bufPrint(&line, "addon {s} {d} is not loaded: {s}", .{ slot.nameOf(), slot.version, why }) catch &line; _ = s.print(x, y, cols, text, .{ .fg = fg, .bg = bg }); return; - } else { + } else for (0..8) |_| { if (ready.items.len > 0) deliver(p, slot, pane, id); frame.cells = (paint(p, slot, id, arena, cols, rows, &frame) orelse return); + // No workers here (a test's, a bench's core): a draw that paint + // asked was done at once, and is this frame's, painted again. + if (drawer != null) break; + for (ready.items) |j| { + if (j.draw == p and j.pane == id) break; + } else break; } if (frame.gpu.len != 0) s.gpu_frames[id] = .{ .bytes = frame.gpu, .serial = pane.serial, .dst = .{ .x = x, .y = y, .w = cols, .h = rows } }; for (0..@min(rows, frame.rows)) |r| for (0..@min(cols, frame.cols)) |col| { @@ -1216,7 +1223,10 @@ pub const api: c.pa_api = .{ j.* = .{ .gpa = heap, .pane = @intCast(cl.id), .serial = pane.serial, .token = token, .gen = cl.slot.gen, .ops = ops, .in = copy, .arena = .init(heap), .draw = p }; Addon.holdJob(ops, true); if (drawer) |d| if (d.go(d.ctx, j)) return token; + // Here, as a worker would run it: its time is not the call's. + const t0 = if (checked) @import("FrameStats.zig").nowNs(); j.run(); + if (checked) cl.began += @import("FrameStats.zig").nowNs() -| t0; ready.append(heap, j) catch j.drop(); return token; } diff --git a/src/dump.zig b/src/dump.zig index 742a9574..102b10d0 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -901,7 +901,8 @@ pub fn plainHere(p: *Pardes, id: usize, old: *Kind.Slot, ops: *const Kind.Ops) ! } s.path = try p.gpa.dupe(u8, old.path); s.selection = try p.gpa.dupe(u8, old.selection); - const kept = .{ old.next_tick, old.views, old.focused, old.state }; + // (and its place: the open's own `where` is of a block not yet the session's) + const kept = .{ old.next_tick, old.views, old.focused, old.state, old.where_text }; if (!Kind.reopen(p, id, s, old.file)) return error.KindRefused; // Its block the session's, byte for byte (its record), never through // the kind's load, which may tidy it. @@ -909,7 +910,7 @@ pub fn plainHere(p: *Pardes, id: usize, old: *Kind.Slot, ops: *const Kind.Ops) ! const record = old.record orelse return error.KindRefused; if (block.len != record.len) return error.KindRefused; @memcpy(block, record); - s.next_tick, s.views, s.focused, s.state = kept; + s.next_tick, s.views, s.focused, s.state, s.where_text = kept; const gpa = old.gpa; old.free(); gpa.destroy(old); diff --git a/test/behaviour/addons_pdf.zig b/test/behaviour/addons_pdf.zig index af194a5b..cf5c8009 100644 --- a/test/behaviour/addons_pdf.zig +++ b/test/behaviour/addons_pdf.zig @@ -273,8 +273,9 @@ test "addons: a PDF whose file changes on disk while a page of it renders: the p try std.testing.expect((try shown(&s, n)).len >= 1); // A page drawn again (another tint), its render done on a worker but // not yet answered as the file changes and the pane opens it again. - s.hold_jobs = true; + s.holdJobs(); try s.write(s.at("/pane/{d}/ctl", .{n}), "PdfTint full\n"); + _ = try shown(&s, n); s.runJobs(); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "doc.pdf", .data = outline }); try std.testing.expect(try s.filesChanged()); diff --git a/test/panes.zig b/test/panes.zig index d47136a5..fb8adc36 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -3783,15 +3783,12 @@ const PdfAddon = struct { }.f, }; - test "a client without the pdf addon shows a PDF pane as the session's frames of it, its pages by key, and its wheel goes to the session" { + test "a client without the pdf addon shows its PDF pane as a line, its page in its tag, and its wheel goes to the session" { if (!addons.has_pdf) return error.SkipZigTest; const R = pardes.replica; const gpa = std.testing.allocator; const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, .{ .vtable = &host_vtable }, false); defer a.deinit(); - var screens: R.Screens = .init(gpa); - defer screens.deinit(a.core); - const peer = try screens.addPeer(); const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false); defer r.deinit(); const Land = struct { @@ -3802,61 +3799,30 @@ const PdfAddon = struct { } }; const land: Land = .{ .a = a, .r = r }; - var words: [64]pardes.Kind.LoadedWord = undefined; - var why: pardes.Kind.Buf(160) = .{}; - const lib = pardes.Addon.readLoaded(pdf_lib, &words, &why); - try land.step(.{ .addon = .{ .op = .load, .pane = 0, .kind = &lib } }); // A frontend with pictures (a terminal without them is shown the // page's text layer). try land.step(.{ .frontend = .{ .windowed = false, .native_images = true } }); + const id = try opened(a, land); try std.testing.expect(r.core().kinds.ops[r.core().kinds.n - 1] == null); - var buf: [4096]u8 = undefined; - const real = try std.Io.Dir.cwd().realPathFile(std.testing.io, "docs/design.pdf", &buf); - var line: [4200]u8 = undefined; - try land.step(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{buf[0..real]}) }); - for (0..3) |_| { - try land.step(.tick); - try jobs(a.core, land); - } - // Its frame crosses: the replica draws the pane as the session - // painted it, its pages placed by key, its page in its tag. var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); - const deliver = struct { - fn f(au: *R.Authority, sc: *R.Screens, pe: u16, re: *R.Replica) !void { - var msgs: std.ArrayListUnmanaged([]u8) = .empty; - defer { - for (msgs.items) |m| std.testing.allocator.free(m); - msgs.deinit(std.testing.allocator); - } - try sc.flush(au.core, pe, re.view, &msgs); - for (msgs.items) |m| if (re.screen(m)) |reply| { - _ = try sc.take(au.core, pe, reply); - }; - } - }.f; _ = try a.core.render(arena.allocator()); - // (A kind's prefix is its last frame's, and the tag a step's: a - // Shadow's is the authority's last step's.) try land.step(.tick); - try deliver(a, &screens, peer, r); - const id = for (r.core().panes, 0..) |slot, i| { - if (slot) |pane| if (pane.addon != null) break i; - } else return error.NoPdfPane; + // No picture crosses: the client shows the line saying the addon + // does not run here, and the session's page in its tag. const shown = try r.core().render(arena.allocator()); var placed: usize = 0; for (shown.placements.items) |pl| placed += @intFromBool(pl.pane == id); - try std.testing.expect(placed >= 1); + try std.testing.expectEqual(@as(usize, 0), placed); try std.testing.expect(std.mem.startsWith(u8, try pardes.tagline.tagPrefix(r.core(), r.core().panes[id].?), "[1/16]")); - // A wheel at the replica: the session's kind takes it, and the - // replica shows where the session's strip went. + // A wheel at the replica: the session's kind takes it. const before = a.core.panes[id].?.addon.?.thumb_at; const rect = r.core().view().rects[id]; for (0..20) |_| r.confirm(try a.take(try r.input(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = rect.x + rect.w / 2, .row = rect.y + rect.h / 2 } }))); + for (0..4) |_| try land.step(.tick); try jobs(a.core, land); _ = try a.core.render(arena.allocator()); try std.testing.expect(a.core.panes[id].?.addon.?.thumb_at > before); - try deliver(a, &screens, peer, r); r.settle(); try std.testing.expect(r.diverged == null); } diff --git a/test/session.zig b/test/session.zig index 06cd3a32..cd04ecb8 100644 --- a/test/session.zig +++ b/test/session.zig @@ -107,6 +107,7 @@ pub const Session = struct { pub fn deinit(s: *Session) void { s.held.deinit(pardesOf(s).gpa); + if (s.hold_jobs) pardes.Kind.drawer = null; if (s.watch_fd >= 0) { pardes.file_watch.unwatchAll(s.watch_fd, &s.watches); _ = std.c.close(s.watch_fd); @@ -310,6 +311,19 @@ pub const Session = struct { return true; } + /// Kinds' jobs and draws held from now on (`hold_jobs`), until + /// `releaseJobs`. + pub fn holdJobs(s: *Session) void { + s.hold_jobs = true; + pardes.Kind.drawer = .{ .ctx = s, .go = struct { + fn go(ctx: ?*anyopaque, j: *pardes.host_io.KindJob) bool { + const ss: *Session = @ptrCast(@alignCast(ctx)); + ss.held.append(pardesOf(ss).gpa, j) catch return false; + return true; + } + }.go }; + } + /// The jobs held run now, as a worker runs them, their answers held /// still: what a test does next happens while they are under way. pub fn runJobs(s: *Session) void { @@ -320,6 +334,7 @@ pub const Session = struct { /// The jobs held, run now and answered as the host's workers would. pub fn releaseJobs(s: *Session) void { s.hold_jobs = false; + pardes.Kind.drawer = null; for (s.held.items, 0..) |j, i| { if (i >= s.ran) j.run(); j.land(pardesOf(s)); |
