import { annotationKey, CONTINUOUS_RENDER_POLICY, isPluginError, PluginError, memo, resolvePageLayers, snapAppearanceScale, toPageRef, toPluginError, toPluginErrorInfo, type BatchResult, type EventOrigin, type PluginContext, type DocCapability, type EngineRenderPolicy, type PageImageHandle, type PageLayerRights, type PageObjectNumber, type PageRef, type PageRenderLayers, type PageRenderViewport, type PluginErrorInfo, } from '@embedpdf/core'; import { intersectRects, type Rect } from '@embedpdf/core-geometry'; import { AppearanceStore, RecentPictures } from './appearance-store'; import type { InvalidateOptions, InvalidateScope, PageLayerOptions, PageRender, PictureStateChangedEvent, RenderFormat, RenderInvalidatedEvent, RenderPageOptions, RenderPagesOptions, RenderSettings, PicturePainter, RenderThumbnailOptions, } from './contract'; import type { AppearancePicture, AppearancesOptions, PaintSettings, RenderCompletedEvent, RenderFailedEvent, RenderHostCapability, RenderSourceOptions, ViewDemand, } from './host-contract'; import { pixelChangeOf } from './invalidation'; import { invalidatePages, layersKeyOf, renderEpochOf, type RenderState } from './model'; import { EMPTY_TILE_PLAN, resolveRenderOptions, type PageViewDemand, type ResolvedRenderOptions, type TilePaintPlan, } from './paint-plan'; import { createPictureReports, PICTURE_STATES } from './pictures'; import { RasterStore } from './raster-store'; import { createSnapshots } from './snapshot'; import { baseAskWidth, resolveStrategy, type ResolvedStrategy } from './strategy'; import { TileManager } from './tile-manager'; const RENDER_SCOPE: DocCapability = 'doc.render'; const THUMBNAIL_SCOPE: DocCapability = 'doc.render.thumbnail'; const FORMS_SCOPE: DocCapability = 'doc.forms.read'; const ANNOTATIONS_SCOPE: DocCapability = 'doc.annotate.read'; /** Every answer `getLayerRights()` gives, one object each, so the same rights are the same object. */ const LAYER_RIGHTS: readonly (readonly PageLayerRights[])[] = [false, true].map((annotations) => [false, true].map((formFields) => Object.freeze({ annotations, formFields })), ); /** An abort reason the engine task accepts (signals carry `unknown`). */ const reasonOf = (signal: AbortSignal): string | undefined => typeof signal.reason === 'string' ? signal.reason : undefined; const DEFAULT_BATCH_CONCURRENCY = 4; /** A view's live demand for one page, as last set through its handle. */ interface PageDemand { demand: PageViewDemand; layers: PageRenderLayers; plan: TilePaintPlan; } /** * The render controller: the one place strategy (config: what the viewer * spends) composes with policy (the engine fact: what the deployment * serves). The engine never snaps and layers never see either; everything * between happens here: conforming demand to the resolved render points, * collapsing same-key asks in the raster store, exposing stable source keys, * and turning a view's demand into a retention-safe tile plan. * * Two doors for rasters: `renderPage` (public, exact size) and * `renderSource` (host, conformed). Both share the raster store, so a * developer's thumbnail and the rail's base plane never render twice. * * Every render it asks for is the picture of a page itself, so it asks the * engine with `priority: 'high'`, naming the view it's for when it knows it: * the engine runs it before anything else about the same place (annotation * appearances, form fields, text geometry, links). * * Two doors for staleness: confirmed document events (see `connect`) and * the `invalidate` verb. Both go through `publishInvalidation`, the one * place the ledger bumps and `onInvalidated` fires. * * The tile manager and the per-view plans live outside state (they hold * live handles and abort controllers); a re-plan wakes readers with * `ctx.notify()`. */ export function createRenderController(ctx: PluginContext) { const settings = ctx.settings(); // The settings as the strategy reads them, resolved again when they change. const resolvedOptions: () => ResolvedRenderOptions = memo( () => [settings.get()] as const, (current) => resolveRenderOptions(current), ); const store = new RasterStore(); const appearances = new AppearanceStore(); const recentAppearances = new RecentPictures(); const invalidated = ctx.events.source(); const renderCompleted = ctx.events.source(); const renderFailed = ctx.events.source(); const pictureStateChanged = ctx.events.source(); const pictures = createPictureReports(ctx, pictureStateChanged.emit); const canRender = (): boolean => ctx.allows(RENDER_SCOPE); const canRenderThumbnail = (): boolean => ctx.allows(THUMBNAIL_SCOPE); // ── another plugin painting the pictures ── // Kept out of state (a painter is behaviour, not data); `notify` tells the // page layers, which read it through the capability. let picturePainter: PicturePainter | null = null; const handOverPictures = (painter: PicturePainter): (() => void) => { if (picturePainter) { throw new PluginError('conflict', 'render', 'another plugin paints the pictures already'); } const held = painter as PicturePainter; picturePainter = held; ctx.notify(); let givenBack = false; return () => { if (givenBack) return; givenBack = true; if (picturePainter !== held) return; picturePainter = null; ctx.notify(); }; }; // ── what a picture draws ── // The engine's rule (`resolvePageLayers`): each option as given, and one // left out draws what the session may read. The doors refuse an explicit // `true` the session may not read, as the engine would; reads (keys, // epochs, plans) never throw, and count such an option as left out. const rights = (): PageLayerRights => LAYER_RIGHTS[ctx.allows('doc.annotate.read') ? 1 : 0]![ctx.allows('doc.forms.read') ? 1 : 0]!; const layersOf = (options: PageLayerOptions): PageRenderLayers => { const may = rights(); return resolvePageLayers( { ...(options.includeAnnotations !== undefined && (may.annotations || !options.includeAnnotations) ? { includeAnnotations: options.includeAnnotations } : {}), ...(options.includeFormFields !== undefined && (may.formFields || !options.includeFormFields) ? { includeFormFields: options.includeFormFields } : {}), }, may, ); }; const pictureLayers = (options: PageLayerOptions, operation: string): PageRenderLayers => { if (options.includeAnnotations === true) ctx.assertAllowed('doc.annotate.read', operation); if (options.includeFormFields === true) ctx.assertAllowed(FORMS_SCOPE, operation); return layersOf(options); }; // One-shot developer hints: misconfigurations, not errors. let warnedFormat = false; const warnDroppedFormat = (strategy: ResolvedStrategy, requested: RenderFormat | undefined) => { if (warnedFormat || requested === undefined || strategy.format === requested) return; warnedFormat = true; console.warn( `[render] format '${requested}' is not in the deployment's formats — using '${strategy.format}'.`, ); }; let warnedBudget = false; const warnPastBudgetNoTiles = (demandWidth: number, supplied: number) => { if (warnedBudget || resolvedOptions().tiles.enabled || demandWidth <= supplied * 2) return; warnedBudget = true; console.warn( `[render] demand is ${(demandWidth / supplied).toFixed(1)}× over the base budget and the ` + `tile plane is disabled (tiles: false) — the page rests blurry. Raise fullPage.maxWidth ` + `or re-enable tiles.`, ); }; // ── strategy ∧ policy ── // The policy is a document fact on the kernel's registry, materialized // before publish. Composed with the strategy once per policy reference. const renderPolicy = (): EngineRenderPolicy => ctx.document()?.renderPolicy ?? CONTINUOUS_RENDER_POLICY; const currentStrategy = memo( () => [renderPolicy(), resolvedOptions()] as const, (policy, options) => { const strategy = resolveStrategy(policy, options); warnDroppedFormat(strategy, options.format); return strategy; }, ); // ── pages ── const pageWidthOf = (page: PageRef): number => { const info = ctx.getPage(page); if (!info) ctx.assertPageRef(page); // throws not-found return info!.size.width; }; const allPageObjectNumbers = (): PageObjectNumber[] => (ctx.document()?.pages ?? []).map((info) => info.ref.objectNumber); /** * A page a change on its way makes (a blank insert, a copy, an undone * delete) is in the page list before the engine has it. Until it lands * nothing asks the engine for its pictures: a blank page shows its * background, a page coming back the pictures still kept under its keys, * and a copy the pictures of the page it copies. */ const isPending = (page: PageRef): boolean => ctx.document()?.pendingPages.has(page.objectNumber) ?? false; /** The page a pending copy copies; null for any other page. */ const copiedFrom = (page: PageRef): PageRef | null => { const pending = ctx.document()?.pendingPages.get(page.objectNumber); return pending?.kind === 'copy' ? pending.of : null; }; /** Resolves once the engine has a pending page; rejects `not-found` when it went first. */ const whenHeld = async (page: PageRef, signal: AbortSignal | undefined): Promise => { await ctx.waitFor(() => !isPending(page), signal ? { signal } : undefined); if (!ctx.getPage(page)) ctx.assertPageRef(page); }; // The one base-sizing path: renderSource, getSourceKey, conformViewport, // and (through the tile manager) engagement all go through baseAskWidth. const conformViewport = (page: PageRef, scale: number): PageRenderViewport => { const demandWidth = scale * pageWidthOf(page); const width = baseAskWidth(currentStrategy(), demandWidth); warnPastBudgetNoTiles(demandWidth, width); return { kind: 'width', width }; }; const epochOf = (pageObjectNumber: PageObjectNumber, layers: PageRenderLayers): number => renderEpochOf(ctx.state.get(), pageObjectNumber, layers); // A raster's identity includes its encode format: the cloud policy arrives // asynchronously after open, so the resolved format can change under a // live store, and the key must change with it. An absent format (the // engine default) adds nothing. const rasterKey = ( pageObjectNumber: PageObjectNumber, width: number, layers: PageRenderLayers, format: RenderFormat | undefined, quality: number | undefined, ): string => `${pageObjectNumber}|w${width}|${layersKeyOf(layers)}|e${epochOf(pageObjectNumber, layers)}` + `${format ? `|f${format}` : ''}${quality !== undefined ? `|q${quality}` : ''}`; // A thumbnail is one picture per page, whatever the screen asks: its key // has no width. const thumbnailKey = ( pageObjectNumber: PageObjectNumber, layers: PageRenderLayers, format: RenderFormat | undefined, quality: number | undefined, ): string => `${pageObjectNumber}|thumbnail|${layersKeyOf(layers)}|e${epochOf(pageObjectNumber, layers)}` + `${format ? `|f${format}` : ''}${quality !== undefined ? `|q${quality}` : ''}`; // ── the raster store door (shared by both render doors and the tiles) ── function acquireRaster( page: PageRef, key: string, request: { viewport: PageRenderViewport; layers: PageRenderLayers; format: RenderFormat | undefined; quality: number | undefined; /** The view whose picture it is, so the engine ranks it by where the page is there. */ view: string | undefined; }, signal: AbortSignal | undefined, ): Promise { const result = store.acquire( key, (storeSignal) => { const draw = (drawn: PageRef): Promise => { const doc = ctx.doc.with({ priority: 'high', ...(request.view !== undefined ? { view: request.view } : {}), }); const task = doc.page(drawn).render.image({ viewport: request.viewport, ...request.layers, ...(request.format !== undefined ? { format: request.format } : {}), ...(request.quality !== undefined ? { quality: request.quality } : {}), }); if (storeSignal.aborted) task.abort(reasonOf(storeSignal)); else storeSignal.addEventListener('abort', () => task.abort(reasonOf(storeSignal)), { once: true, }); return task; // AbortablePromise is a Promise }; const drawnWhenHeld = (drawn: PageRef) => isPending(drawn) ? whenHeld(drawn, storeSignal).then(() => draw(drawn)) : draw(drawn); // A copy draws as the page it copies, which the engine may not have yet either. return drawnWhenHeld(copiedFrom(page) ?? page); }, signal, ); return result.then( (image) => { renderCompleted.emit({ page, key }); return image; }, (error: unknown) => { const mapped = toPluginError('render', error); if ( !isPluginError(mapped, 'operation-cancelled') && !isPluginError(mapped, 'instance-closed') ) { renderFailed.emit({ page, key, error: toPluginErrorInfo(mapped) }); } throw mapped; }, ); } /** The host door: conformed to the render points. Async so refusals reject. */ async function renderSource( page: PageRef, { scale, view, signal, thumbnail, ...options }: RenderSourceOptions & { signal?: AbortSignal }, ): Promise { if (thumbnail) return thumbnailOf(page, { ...options, view, signal }, 'render.renderSource'); ctx.assertAllowed(RENDER_SCOPE, 'render.renderSource'); const layers = pictureLayers(options, 'render.renderSource'); const viewport = conformViewport(page, scale); const strategy = currentStrategy(); const key = rasterKey( page.objectNumber, viewport.kind === 'width' ? viewport.width : 0, layers, strategy.format, undefined, ); return acquireRaster( page, key, { viewport, layers, format: strategy.format, quality: strategy.quality, view, }, signal, ); } /** * A picture of part of a page, or a turned one, for its caller alone: no * layer asks for it, so it skips the store. The rect is cut at the page's * edge, and the size is the caller's, as the engine takes it. */ function renderPart( page: PageRef, pageSize: { width: number; height: number }, options: RenderPageOptions, layers: PageRenderLayers, format: RenderFormat | undefined, quality: number | undefined, ): Promise { const rect = options.rect && intersectRects(options.rect, { x: 0, y: 0, ...pageSize }); if (rect && !(rect.width > 0 && rect.height > 0)) { throw new PluginError('invalid-input', 'render', 'the rect misses the page', { details: { field: 'rect' }, }); } const signal = options.signal; const draw = (drawn: PageRef): Promise => { const task = ctx.doc .with({ priority: 'high' }) .page(drawn) .render.image({ ...(rect ? { target: { kind: 'rect' as const, rect } } : {}), viewport: options.width !== undefined ? { kind: 'width', width: Math.max(1, Math.round(options.width)) } : { kind: 'scale', scale: options.scale ?? 1 }, ...(options.rotation ? { rotation: options.rotation } : {}), ...layers, ...(format !== undefined ? { format } : {}), ...(quality !== undefined ? { quality } : {}), }); if (signal?.aborted) task.abort(reasonOf(signal)); else signal?.addEventListener('abort', () => task.abort(reasonOf(signal)), { once: true }); return task; }; // A copy draws as the page it copies, which the engine may not have yet either. const drawn = copiedFrom(page) ?? page; return isPending(drawn) ? whenHeld(drawn, signal).then(() => draw(drawn)) : draw(drawn); } /** The public door: the requested size, exactly. Async so refusals reject. */ async function renderPage( pageArgument: PageRef | number, options: RenderPageOptions = {}, ): Promise { ctx.assertAllowed(RENDER_SCOPE, 'render.renderPage'); const { ref: page, size } = ctx.pageOf(pageArgument); const layers = pictureLayers(options, 'render.renderPage'); const strategy = currentStrategy(); const format = options.format ?? strategy.format; const quality = options.quality ?? strategy.quality; if (options.rect !== undefined || options.rotation) { return ctx.cancellable( options.signal, renderPart(page, size, options, layers, format, quality), ); } const width = Math.max(1, Math.round(options.width ?? (options.scale ?? 1) * size.width)); // Exact-size renders share the store with the conformed door: a width // that matches a conformed raster (same format, default quality) is the // same key, so the cached image serves it. const key = rasterKey(page.objectNumber, width, layers, format, options.quality); return ctx.cancellable( options.signal, acquireRaster( page, key, { viewport: { kind: 'width', width }, layers, format, quality, view: undefined, }, options.signal, ), ); } /** A page's thumbnail, by either door: one picture per page and layers. */ async function thumbnailOf( page: PageRef, { view, signal, format: askedFormat, quality: askedQuality, ...options }: RenderThumbnailOptions & { view?: string | undefined }, operation: string, ): Promise { ctx.assertAllowed(THUMBNAIL_SCOPE, operation); const layers = pictureLayers(options, operation); const strategy = currentStrategy(); const format = askedFormat ?? strategy.format; const quality = askedQuality ?? strategy.quality; return acquireRaster( page, thumbnailKey(page.objectNumber, layers, format, askedQuality), { viewport: { kind: 'thumbnail' }, layers, format, quality, view }, signal, ); } async function renderPages( pages: readonly (PageRef | number)[], options: RenderPagesOptions = {}, ): Promise> { ctx.assertAllowed(RENDER_SCOPE, 'render.renderPages'); const concurrency = Math.max(1, options.concurrency ?? DEFAULT_BATCH_CONCURRENCY); // Each entry keeps its place in the input, so the result reads in the // order given whatever order the renders finished in. const applied: { index: number; render: PageRender }[] = []; const failed: { index: number; ref: PageRef | number; error: PluginErrorInfo }[] = []; const queue = pages.map((page, index) => ({ page, index })); const worker = async () => { for (let next = queue.shift(); next; next = queue.shift()) { const { page, index } = next; try { const image = await renderPage(page, options); applied.push({ index, render: { page: ctx.pageOf(page).ref, image } }); } catch (error) { failed.push({ index, ref: page, error: toPluginErrorInfo(toPluginError('render', error)), }); } } }; const batch = Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, worker)); await ctx.cancellable(options.signal, batch); const byInput = (left: { index: number }, right: { index: number }) => left.index - right.index; return { applied: applied.sort(byInput).map(({ render }) => render), skipped: [], failed: failed.sort(byInput).map(({ ref, error }) => ({ ref, error })), }; } // ── appearance pictures: the owners' items, shared between their views ── async function renderAppearances( page: PageRef, { family, scale, items, signal }: AppearancesOptions, ): Promise { ctx.assertAllowed( family === 'widgets' ? FORMS_SCOPE : ANNOTATIONS_SCOPE, 'render.renderAppearances', ); const pageObjectNumber = ctx.pageOf(page).ref.objectNumber; const versions = new Map(items.map((item) => [annotationKey(item.ref), item.version])); const asked = [...versions].map(([item, version]) => `${item}@${version}`).sort(); const group = `${family}|${pageObjectNumber}`; const pictures = appearances.acquire( group, `${group}|s${scale}|${asked.join(',')}`, async (fetchSignal) => { if (isPending(page)) await whenHeld(page, fetchSignal); // The look at rest only, in every state: a check box keeps both its // pictures, and the looks under the pointer and pressed aren't drawn. const pageHandle = ctx.doc.page(toPageRef(pageObjectNumber)); const options = { viewport: { kind: 'scale' as const, scale }, modes: ['normal' as const] }; const task = family === 'widgets' ? pageHandle.forms.renderAppearances(options) : pageHandle.annotations.renderAppearances(options); if (fetchSignal.aborted) task.abort(reasonOf(fetchSignal)); else fetchSignal.addEventListener('abort', () => task.abort(reasonOf(fetchSignal)), { once: true, }); // The asked items' pictures, each tagged with the version it was asked at. const drawn = (await task).appearances.flatMap((picture): AppearancePicture[] => { const version = versions.get(annotationKey(picture.ref)); return version === undefined ? [] : [{ ...picture, version }]; }); recentAppearances.remember(family, drawn, (picture) => annotationKey(picture.ref)); return drawn; }, signal, ); return ctx.cancellable( signal, pictures.catch((error: unknown) => { throw toPluginError('render', error); }), ); } // ── invalidation: the one place the ledger bumps and onInvalidated fires ── function publishInvalidation( pageObjectNumbers: readonly PageObjectNumber[], scope: InvalidateScope, origin: EventOrigin | null, ): void { if (pageObjectNumbers.length === 0) return; ctx.state.update(invalidatePages, pageObjectNumbers, scope); // Every view's plan for these pages points at old-epoch pixels: re-plan // now, so `getPlan` reads fresh on the subscribers' next look. for (const pageObjectNumber of pageObjectNumbers) replanPage(pageObjectNumber); invalidated.emit({ pages: pageObjectNumbers.map((pageObjectNumber) => toPageRef(pageObjectNumber)), scope, origin, }); } function invalidate({ pages, scope = 'content' }: InvalidateOptions = {}): void { const named = pages?.flatMap((page) => ctx.getPage(page)?.ref.objectNumber ?? []); publishInvalidation(named ?? allPageObjectNumbers(), scope, null); } // ── tiles: one manager, per-view demand handles with pure reads ── // Tile resolutions arrive in bursts (a want set landing): coalesce the // re-plans per frame, so N arrivals become one re-plan and one wake-up. const pendingAdvance = new Set(); let advanceScheduled = false; const wake = (pageObjectNumber: PageObjectNumber) => { pendingAdvance.add(pageObjectNumber); if (advanceScheduled) return; advanceScheduled = true; ctx.clock.nextFrame(() => { advanceScheduled = false; const advanced = [...pendingAdvance]; pendingAdvance.clear(); for (const advancedPage of advanced) replanPage(advancedPage); }); }; const tiles = new TileManager({ store, getOptions: resolvedOptions, getPolicy: renderPolicy, getPageSize: (pageObjectNumber) => ctx.getPage(toPageRef(pageObjectNumber))?.size, getEpoch: epochOf, after: ctx.clock.after, fetchTile: async (view, pageObjectNumber, rect: Rect, scale, layers, signal) => { // The same refusal the engine would send, without the round trip: a // denied session's viewport would otherwise be refused once per tile. ctx.assertAllowed(RENDER_SCOPE, 'render.tile'); const page = toPageRef(pageObjectNumber); if (isPending(page)) await whenHeld(page, signal); const strategy = currentStrategy(); const task = ctx.doc .with({ priority: 'high', view }) .page(page) .render.image({ target: { kind: 'rect', rect }, viewport: { kind: 'scale', scale }, ...layers, ...(strategy.format !== undefined ? { format: strategy.format } : {}), ...(strategy.quality !== undefined ? { quality: strategy.quality } : {}), }); if (signal.aborted) task.abort(reasonOf(signal)); else signal.addEventListener('abort', () => task.abort(reasonOf(signal)), { once: true }); return task; }, onAdvance: wake, debug: (message: string) => { if (resolvedOptions().debug) console.debug(`[render] ${message}`); }, }); /** One handle per view id, reference-counted; demands and plans per page. */ const views = new Map< string, { handle: ViewDemand; refs: number; pages: Map } >(); /** Re-plan a page for every view that wants it (schedules the next want * set), and wake readers once when any plan changed. */ function replanPage(pageObjectNumber: PageObjectNumber): void { let changed = false; for (const [viewId, view] of views) { const entry = view.pages.get(pageObjectNumber); if (!entry) continue; const plan = tiles.plan(viewId, pageObjectNumber, entry.demand, entry.layers); if (plan !== entry.plan) { entry.plan = plan; changed = true; } } if (changed) ctx.notify(); } function createViewDemand(viewId: string): ViewDemand { const existing = views.get(viewId); if (existing) { existing.refs += 1; return existing.handle; } const pages = new Map(); const handle: ViewDemand = { setDemand: (page, demand, options) => { const pageObjectNumber = page.objectNumber; const layers = layersOf(options ?? {}); const previous = pages.get(pageObjectNumber); const plan = tiles.plan(viewId, pageObjectNumber, demand, layers); pages.set(pageObjectNumber, { demand, layers, plan }); if (plan !== previous?.plan) ctx.notify(); }, getPlan: (page) => pages.get(page.objectNumber)?.plan ?? EMPTY_TILE_PLAN, markPainted: (page, key) => tiles.sourcePainted(viewId, page.objectNumber, key), markUnpainted: (page, key) => tiles.sourceUnpainted(viewId, page.objectNumber, key), release: (page) => { pages.delete(page.objectNumber); tiles.releasePage(viewId, page.objectNumber); }, destroy: () => { const view = views.get(viewId); if (!view || view.refs === 0) return; view.refs -= 1; if (view.refs > 0) return; // The last reference releases the view's pages. The entry itself stays // (a few ids per document) so a handle that is re-acquired or reused // after a dispose (React's development double-mount) keeps working. for (const pageObjectNumber of [...view.pages.keys()]) { tiles.releasePage(viewId, pageObjectNumber); } view.pages.clear(); }, }; views.set(viewId, { handle, refs: 1, pages }); return handle; } // What the layers paint with: the same object until a setting it reads changes. const paintSettings = memo( () => [resolvedOptions().tiles.enabled] as const, (enabled): PaintSettings => Object.freeze({ tiles: enabled }), ); // A settings change reaches every view's plans at once: re-plan what they show. ctx.listen(settings.api.onSettingsChanged, () => { const shown = new Set(); for (const view of views.values()) for (const page of view.pages.keys()) shown.add(page); for (const page of shown) replanPage(page); }); const snapshots = createSnapshots(ctx, { renderPage, renderPolicy, settings: () => settings.get().snapshot, }); const api: RenderHostCapability = { // ── public lens ── ...settings.api, canRender, canRenderThumbnail, handOverPictures, getPicturePainter: () => picturePainter, renderPage, renderThumbnail: async (pageArgument, options = {}) => ctx.cancellable( options.signal, thumbnailOf(ctx.pageOf(pageArgument).ref, options, 'render.renderThumbnail'), ), renderPages, getRenderPolicy: renderPolicy, getRenderEpoch: (page, layers = {}) => { const info = ctx.getPage(page); return info ? epochOf(info.ref.objectNumber, layersOf(layers)) : 0; }, invalidate, onInvalidated: invalidated.on, getPictureState: (page, view) => { const info = ctx.getPage(page); return info ? pictures.stateIn(view, info.ref.objectNumber) : PICTURE_STATES.idle; }, onPictureStateChanged: pictureStateChanged.on, // ── host lens ── renderSource, getSourceKey: (page, { scale, view: _view, thumbnail, ...options }) => { if (thumbnail) { return thumbnailKey( page.objectNumber, layersOf(options), currentStrategy().format, undefined, ); } const viewport = conformViewport(page, scale); return rasterKey( page.objectNumber, viewport.kind === 'width' ? viewport.width : 0, layersOf(options), currentStrategy().format, undefined, ); }, conformViewport, getPaintSettings: paintSettings, getLayerRights: rights, createViewDemand, reportPicture: pictures.open, renderAppearances, getKeptAppearances: (family, item) => recentAppearances.of(family, annotationKey(item)), getAppearanceScale: (renderScale) => snapAppearanceScale(renderPolicy(), renderScale), onRenderCompleted: renderCompleted.on, onRenderFailed: renderFailed.on, // ── snapshots, both lenses ── ...snapshots.api, }; return { api, connect() { // Confirmed pixel-changing facts, own or remote, and the stream // notice that some were lost. ctx.listen(ctx.doc.events, (event) => { const change = pixelChangeOf(event, allPageObjectNumbers); if (!change) return; publishInvalidation(change.pages, change.scope, 'origin' in event ? event.origin : null); }); snapshots.connect(); }, }; }