From 60f99172b0d29e2a3f3611f10a45ebc08d0f2505 Mon Sep 17 00:00:00 2001 From: prete Date: Tue, 24 Nov 2026 20:57:11 +0000 Subject: [PATCH 1/3] Plan Phase 27: Screenshot, the spatial view as a high-resolution PNG A Screenshot button beside Share saves the main 2D view at 1x-8x, drawn again off screen: the image at the pyramid level the larger size needs, the deck.gl layers at that pixel density, and the scale bar, legend, axes and selections from their models. Decisions D1-D12, the drawing steps, tasks A-I with a spike first, risks, and the user's answers to the four open questions (every loaded cell, 2x to start, a failed tile fails with Retry, Copy later). PLAN.md gets the phase's row. --- PLAN.md | 1 + docs/plan/phases/27-screenshot.md | 449 ++++++++++++++++++++++++++++++ 2 files changed, 450 insertions(+) create mode 100644 docs/plan/phases/27-screenshot.md diff --git a/PLAN.md b/PLAN.md index 3e58929b..723244b3 100644 --- a/PLAN.md +++ b/PLAN.md @@ -59,6 +59,7 @@ Legend: `[x]` done · `[ ]` open · **Deferred** · **Dropped** · **Superseded* | [Phase 24](docs/plan/phases/24-section-stack.md) | 3D section stack: registered serial sections in 3D | Done (2026-11-18); one file's z and sections 2026-11-20 | | [Phase 25](docs/plan/phases/25-imported-segmentations.md) | Segmentations imported onto images (masks, polygons) | Done (2026-11-19) | | [Phase 26](docs/plan/phases/26-image-channel-conditions.md) | Cell query on image channels: mean and % above per cell | M1 and M2 done (2026-11-19): TIFF and OME-Zarr images | +| [Phase 27](docs/plan/phases/27-screenshot.md) | Screenshot: the spatial view as a high-resolution PNG | Planned (2026-11-24); spike next | **Done** means a phase's tasks shipped. Most phase files also keep a Known Gaps list whose items stay open; [Open Items](docs/plan/open-items.md) diff --git a/docs/plan/phases/27-screenshot.md b/docs/plan/phases/27-screenshot.md new file mode 100644 index 00000000..44c9ad51 --- /dev/null +++ b/docs/plan/phases/27-screenshot.md @@ -0,0 +1,449 @@ +# Phase 27 — Screenshot + +Planned 2026-11-24. Requested: a high-resolution image of the spatial view +for paper figures. The canvas has no export today. The only image the app +saves is a plot's `Export PNG` ([Phase 22](22-plots-panel.md), plan +22-D10). + +The scope is a `Screenshot` button in the top bar. It saves the main 2D +view as a PNG at 1×, 2×, 4× or 8× its size on screen. The PNG is drawn +again off screen rather than copied from the page: + +- the image at the pyramid level the larger size needs; +- the deck.gl layers at that pixel density; +- the scale bar, legend, axes and selections drawn from their models. + +The live view does not change while it runs. + +The decisions below were proposed on 2026-11-24. The user answered the +plan's four questions the same day +([Answered Questions](#answered-questions)); D3, D5, the failure rule and +Later carry the answers. + +The plan rests on a code map made on 2026-11-24 at `24f0fd2`. It is cited +below as `file:line`; line numbers drift as the code changes. + +Sizes are for one developer: **S** ≤ 1 day, **M** 2–4 days, **L** 1–2 weeks. + +## Why A Browser Screenshot Is Not Enough + +Until this phase, the advice for a figure was a browser screenshot at a +higher device pixel ratio (DevTools device mode, or Playwright's +`deviceScaleFactor` on a `Share` link). That falls short in five ways: + +- **The image does not gain detail.** The pyramid level is chosen per CSS + pixel, not per device pixel (`MorphologyCanvas.tsx:455`). Both loaders + take the coarsest level whose pixel is at most 1.5 CSS px on screen + (`tiff/loader.ts:2155-2169`; `omeZarrLoader.ts:54`, `:480-491`). At 4× + the image is upsampled. Cells, outlines and text do get sharper. +- **A larger window trades one problem for another.** It reads a finer + level, but points, outline widths and text are sized in CSS pixels, so + they shrink against the figure. +- **The legend is outside the frame.** It sits in the notification stack + with the loading list (`ViewerCore.tsx:2489-2500`). A capture of the + frame leaves it out, and a capture of the page takes the panels too. +- **The canvas thins cells.** Cell points are sampled down to the render + cap: 250,000 on the expanded budget, 150,000 balanced, 75,000 compact + (`performanceBudget.ts:18-41`; `ViewerCore.tsx:929-951`). AnnData has no + cap (`App.tsx:1423-1425`). On the expanded budget, the 1.4M-cell Xenium + demo zoomed out shows about one cell in six. +- **deck.gl's canvas cannot be read afterwards.** It does not keep its + drawing buffer, so `toDataURL` on it is blank. + +## Goals And Non-Goals + +Goals: + +- A `Screenshot` button beside `Share` that opens a popover: scale, what + to include, background, and `Save PNG`. +- The PNG is the canvas's frame at a whole-number scale of its CSS size, + looking as the screen does: the same view, colours, and point sizes and + line widths relative to the frame. +- The image read at the level the PNG's pixel size needs. +- Every loaded cell drawn, not the render cap's sample (D5). +- The scale bar, legend, axes and saved selections drawn sharp at the + PNG's scale. +- An estimate of the image read before it starts, a question before a + large one, then progress and `Cancel`. The live view keeps working. +- The PNG records its dpi and, in text chunks, the dataset, the view and + µm per pixel. +- The axe baseline stays empty and `nativeTitleAudit` passes. + +Non-goals: + +- Vector output (SVG, PDF) of the map. A million cell outlines is not a + file anyone can edit. See [Later](#later). +- Collection sections side by side (`LinkedSections.tsx:268`), the + section stack (`SectionStackViewer.tsx:276`) and the 3D views + (`VolumeViewer.tsx:138`). Each has its own deck.gl canvas. The + screenshot is of the main 2D view. +- Loading more than the view holds. The screenshot draws the cells, + expression and transcripts the canvas has loaded. It does not switch + expression to `All cells` or transcripts to `Exact`; it says when the + view is a sample (D7). +- A frame other than the canvas's. The PNG has the canvas's aspect; the + window or the panels change it. A crop frame is [Later](#later). +- Hover tooltips, the keyboard crosshair, the coordinate and zoom + readouts, tool hints, a selection or measurement still being drawn, the + minimap and the zoom buttons. +- Keeping the popover's choices in the link. + +## Current State + +What the work can build on: + +- **The frame's layers** (`ViewerCore.tsx:2271-2446`), bottom to top: + - `MorphologyCanvas`, a 2D canvas (`:2298-2310`). Its backing store is + the frame's CSS size times `devicePixelRatio` + (`MorphologyCanvas.tsx:555-571`). The image layer's opacity is CSS + opacity on the element (`:306`). + - deck.gl in `.deckgl-host` (`ViewerCore.tsx:2311-2328`): `MemoDeckGL` + with `Deck={ReleasingDeck}`, `spatialOverviewView` (an + `OrthographicView` with `flipY: false`, `deckLayers.ts:106-109`) and + `layers`. + - Saved and active selections as SVG paths in `.roi-draw-layer` + (`ViewerCore.tsx:2329-2373`), the measurement overlay, + `ViewerSelectionOverlay` (`:2386-2388`), the Magic Lens and the + tooltips. + - `ViewerAxes` and `ScaleBar` (`:2444-2445`), from `viewerAxesModel` + and `scaleBarModel` (`:1461-1505`; `ScaleBarModel`, + `viewerMeasurements.ts:25-28`; `AxesModel`, `viewerAxesModel.ts:31`). + - Outside the frame: the minimap and the zoom buttons (`:2447-2483`), + and the legend (`ViewerLegendSection`, `viewerLegendTypes.ts:40`) with + the loading list (`:2489-2500`). +- **Drawing the image is already pure.** + - `drawMorphologyTileChannels(context, batches, viewState, viewport)` + and `drawFlatImage` (`morphologyCanvas.ts:66-121`) draw into any 2D + context, for any view state and CSS viewport. + - Channels are added (`lighter`), except a single RGB channel, which is + drawn over (`:73-93`). So tiles can be drawn in any order. + - The level is `loader.bestLevel(2 ** zoom)` (`MorphologyCanvas.tsx:455`). + Each channel has a `MorphologyTileStore` cache and scheduler. While a + level loads, ready tiles of another level stand in (`:350-384`). + - The flat Visium image loads with `crossOrigin = 'anonymous'` + (`morphologyTileStore.ts:157-158`). TIFF and Zarr tiles are + `ImageBitmap`s decoded from fetched bytes. A canvas drawn from either + can be read back. + - `persist: false` on a tile fetch reads the IndexedDB byte-range cache + without adding to it (`imagePyramid.ts:103-108`, plan 26-D8). +- **The deck.gl layers** come from + `createOverviewLayers(cells, boundaries, options)` (`deckLayers.ts:166`), + called with ViewerCore's inputs (`ViewerCore.tsx:1147-1173`). + - Point sizes depend on the zoom against the fitted zoom and on the full + view's point count (`pointSizeZoomDelta`, `pointSizeCellCount`). + - Outline widths are in pixels (`lineWidthUnits: 'pixels'`). Cell discs + are in µm (`radiusUnits: 'common'`) or pixels. + - No layer fetches its own data: there is no `TileLayer`. +- **The render cap.** `cellPointSampleFraction` thins cell points to + `overviewRenderCellLimit` (`ViewerCore.tsx:929-951`). While the view + moves, a smaller limit applies until it has been still for 200 ms + (`:238`). +- **Expression samples.** `GeneExpressionLoadMode` is `exact`, `sampled`, + `overview-sampled`, `exact-region` or `all-cells` + (`geneExpressionLod.ts:26-31`). Above 500,000 cells, `Auto LOD` reads a + sample when zoomed out, keeping every expressing cell (`helpText.ts:6`). +- **WebGL contexts.** `ReleasingDeck` (`releasingDeck.ts`) loses a Deck's + context once its canvas leaves the page. Chromium keeps 16 live contexts + per page and drops the oldest past that. +- **Lost contexts** (`useDeckDeviceLoss.ts`, + [PR #420](https://github.com/cellgeni/explorer/pull/420)). After a lost + context the main view draws again on a new canvas, up to 3 times, then + says to reload (`:13`). Only a canvas in the page counts (`:27-35`), so + an off-screen canvas losing its context does not. + - The new deck gets `cloneLayers(layers)` (`:49-53`; + `ViewerCore.tsx:1207-1210`): deck.gl refuses layer instances a + finalized deck has used, so a second deck needs clones. +- **Requests into the viewer are props**: `focusRequest` and + `fitRequestKey` (`ViewerCore.tsx:542-548`; `App.tsx:4998`, + `:5415-5420`). The app has no imperative handles. +- **Image export elsewhere.** + - `plotFileName` names files `{dataset}-…` (`plotExport.ts:132-145`). + - `svgPngBlob` draws an SVG on a canvas at a scale and writes a PNG + (`:172-205`). Its SVG holds no external images or fonts, so the canvas + can be read. + - `documentPlotPaint` reads the theme's tokens (`:18-31`). + - `downloadBlob` saves a file (`appRuntimeModel.ts:499-507`). + - ROI exports record `dataset_url` without a presigned URL's signature + (`urlWithoutCredentials`, `urlCredentials.ts:13`; + `useRoiWorkflow.ts:797-802`), and `exported_at`. +- **The top bar's right end** (`TopBar.tsx:176-200`): the panel toggles, + `ShareButton` (`:539-575`, an icon alone on narrow screens), the Help + menu, and Settings, whose switches include the legend, the scale bar and + the axes. +- **One theme, dark.** The canvas is `--canvas: #000` (`tokens.css:4-17`; + `viewer.css:138-144`). The scale bar and the legend sit on + `--surface-1` boxes with `--text-1` text. +- **Loads in progress** reach ViewerCore as `loadingTasks` + (`ViewerCore.tsx:520`). A `LoadingTaskSummary` can carry progress and a + cancel (`AppStatusPanels.tsx:36-43`). + +What is missing: + +- A way to draw the view into a canvas the app can read. +- A level choice for a pixel density other than the screen's. +- The legend, scale bar, axes and selections drawn outside the DOM. +- PNG chunks: `pHYs` for the dpi, `tEXt` for the metadata. + +## Product Decisions + +Proposed 2026-11-24. D3, D5 and the failure rule in +[How A Screenshot Runs](#how-a-screenshot-runs) are settled by the user's +answers the same day; the others stand as proposed. + +- **D1. `Screenshot` in the top bar**, between the panel toggles and + `Share`, with a camera icon. Under 860 px it is an icon alone, as + `Share` is. It opens a popover. It is disabled until the view has drawn + a dataset. +- **D2. The canvas's frame, as on screen.** + - The PNG covers what the frame shows when `Save PNG` is pressed: the + same target, zoom and CSS size, including any part of the map under a + drawer or a card. + - Everything sized in CSS pixels on screen (points, outlines, text, the + scale bar) is N times larger in the PNG. The figure looks like the + screen, only sharper. +- **D3. Scale 1×, 2×, 4× or 8×**, 2× to start. + - Whole numbers keep tile edges on whole pixels (D9). + - The popover gives the size and what it means in print, e.g. + "3,000 × 1,800 px · 0.85 µm per pixel · 254 × 152 mm at 300 dpi". + - A `DPI` field, 300 to start, sets only the PNG's `pHYs` and the mm + figure. + - A scale over the size limit (D10) is disabled, and says why. +- **D4. The image at the screenshot's density.** + - Each channel's level is `bestLevel(2 ** zoom × N)`: a 4× screenshot + reads the level a window 4 times larger would. + - The popover gives the number of tiles it will read, and their size + where the tile index knows it (TIFF). Above 512 MiB it asks first, as + Cell Query does (26-D7). + - Tiles of another level never stand in. The screenshot waits for its + own. + - Reads use `persist: false`, so they do not evict what the canvas and + the readers keep in the byte-range cache. +- **D5. Every loaded cell.** The screenshot draws without the render cap's + sample: zoomed out, the Xenium demo shows all 1.4 million cells, not + about 250,000. Points keep the screen's size. It is one frame, drawn + once, so the cap's reason (frame rate while moving) does not apply. + The popover says so when the screen is a sample: "Draws all 1,414,155 + cells; the screen shows 250,000." +- **D6. Include**: `Scale bar`, `Legend`, `Axes` and `Selections`. + - The first three start from Settings (`Show scale bar`, `Show legend`, + `Show axes`). `Selections`, the saved and active selection outlines, + starts on. + - Geometric annotations are deck.gl layers, so they come with the + cells. + - The legend sits top right, as on screen, and lists what the screen + lists, including classes shown with `Show more`. +- **D7. Notes on what the view holds.** Each says what would change it. + `Save PNG` stays enabled: the notes inform, they do not block. + - Expression is `sampled` or `overview-sampled`: "Expression is a + sample at this zoom. Set Expression detail to All cells to colour + every cell." + - Transcripts are shown as density squares: "Transcripts are density + squares at this zoom. Set Detail to Exact, or zoom in, for points." + - Loads are in progress: "Still loading: {labels}. The screenshot shows + what has loaded." +- **D8. Background**: `Canvas` (black, as the screen), `White` or + `Transparent`. The scale bar and the legend keep their boxes: dark with + light text on `Canvas` and `Transparent`, white with dark text on + `White`. +- **D9. Drawn off screen, in tiles.** The live canvas is never resized or + read. The PNG is drawn tile by tile, each tile at most 4,096 device + pixels a side and a whole number of CSS pixels, because WebGL silently + shrinks a drawing buffer past its limit. See + [How A Screenshot Runs](#how-a-screenshot-runs). +- **D10. A size limit**: at most 16,384 px on the longer side and 128 + megapixels. Chromium allows 2D canvases of 16,384 px a side and about + 268 megapixels, but encoding holds the RGBA pixels (512 MiB at 128 + megapixels) beside the canvas. The spike checks both numbers (task A). +- **D11. The file.** `{dataset}-screenshot.png`, with `{dataset}` as in + plot exports (`plotFileName`). + - `pHYs` from `DPI`. + - `tEXt` chunks with the PNG specification's keywords: + - `Software`: the app's name and version; + - `Source`: the dataset URL without credentials, as ROI exports + write it; + - `Description`: the view in µm (x and y ranges), µm per pixel, the + scale and, for a z-stack, the plane; + - `Creation Time`: the time of saving, in UTC (ISO 8601). +- **D12. One at a time, in the loading list.** + - Progress shows in the popover and as a task in the loading list, with + `Cancel`, so closing the popover does not stop it. + - `Save PNG` is disabled while one runs. + - Changing dataset cancels it. + +## How A Screenshot Runs + +1. **Snapshot.** At `Save PNG`, ViewerCore takes: + - the view state, once the view has been still for 200 ms; + - the frame's CSS size; + - the `createOverviewLayers` inputs; + - the image channels, or the flat image, and the layer's opacity; + - the overlay models: scale bar, axes, legend sections, selections. + + Pans, zooms and loads after that do not change the screenshot. + +2. **Plan.** A pure `planScreenshot` gives: + - the PNG's size and whether it is within the limit (D10); + - the tile grid (D9); + - each channel's level, and its tiles under each grid tile (D4); + - the read estimate and the notes (D7). +3. **Each grid tile**, row by row: + 1. **Image.** Every channel's tiles under the grid tile are fetched + through the channel's tile store (`persist: false`). They are drawn + into a scratch 2D canvas as they arrive, with the canvas's rules + (`morphologyCanvas.ts:66-121`), the context scaled by N and the view + state's target moved to the grid tile. + 2. **Composite.** The background fill, then the scratch canvas at the + image layer's opacity (`globalAlpha`). + 3. **deck.gl.** The off-screen Deck renders the grid tile: width and + height the tile's CSS size, `useDevicePixels: N`, the target at the + tile's centre. Its canvas is drawn onto the PNG's canvas in the same + task as `redraw`, before the browser can clear it. + + If the off-screen Deck loses its context, the screenshot fails and says + so. A tile that fails is read once more. If it fails again, the screenshot + fails, names the channel and offers `Retry`: a figure with a hole in it + is worse than none. + +4. **Overlays.** One SVG over the whole frame in CSS pixels, from the + snapshot's models, drawn onto the PNG's canvas at N× through an + `Image`, as `svgPngBlob` does. It holds no external fonts or images, + so the canvas stays readable. +5. **Writing.** `toBlob('image/png')`. Then the `pHYs` and `tEXt` chunks + are inserted after `IHDR` (D11), and `downloadBlob` saves the file. +6. **Clean-up.** The off-screen Deck is finalized and its context lost, as + `ReleasingDeck` does. The canvases are emptied (width 0). `Cancel` + aborts the tile fetches and the decode requests. + +**The off-screen Deck** has its own canvas, never in the page. Its layers +come from `createOverviewLayers` with the snapshot's inputs and three +overrides: a sample fraction of 1 (D5), nothing pickable, and no hover +highlight. Layers rebuilt by `createOverviewLayers` are new instances; +layers cloned from the live view instead would go through `cloneLayers`, +as a redraw after a lost context does. One Deck draws every grid tile; it +is made once per screenshot. + +If a second context holding the cells' buffers is too costly on the +Xenium demo, the alternative is the live Deck drawing each grid tile into +a framebuffer (`_framebuffer`) through a second view, which reuses its +buffers. The spike chooses (task A). + +## Tasks + +- [ ] **A. Spike.** (M) A throwaway screenshot of the Xenium demo + (1,414,155 cells, four channels) in a production build in headless + Chromium on the Mac's GPU. Record in this file: + - the off-screen Deck: time to the first frame with every cell and with + the cap's sample; GPU memory; whether it draws in a hidden tab, where + `requestAnimationFrame` stops; + - the framebuffer alternative: memory, and whether the live view + flickers; + - `drawingBufferWidth` asked for at 4,096, 8,192 and 16,384 px, and + seams at tile edges where points cross them; + - `toBlob` time and PNG size at 4,096, 8,192 and 16,384 px; + - image tiles at 4× for the brain view and for the whole slide: count, + MB and time; + - revisit D5, D9 and D10 if a 4× screenshot of the whole slide takes + over a minute, or the tab grows by more than 2 GB. +- [ ] **B. The plan.** (S) `planScreenshot` in + `src/features/screenshot/screenshotPlan.ts`: size and limit (D10), + the tile grid (D9), levels and tiles per channel (D4), the read + estimate and the notes (D7). + - fast-check tests: the tiles cover the frame exactly, without overlap, + on whole device pixels. + - The level at N× equals the level at 1× for a frame N times larger. +- [ ] **C. The image.** (M) `ScreenshotImageComposer`: fetch, draw and + composite per grid tile, with progress and abort. + - Tests with a fake loader and a recording 2D context: levels, flipped + and swapped placements, an origin offset (MERSCOPE), the flat image, + a z plane, and a tile that fails twice. +- [ ] **D. The deck.gl tiles.** (M) The off-screen renderer the spike + chooses. + - Tests that its layers carry the overrides, and that it loses its + context when done (count live contexts with a `WeakRef` wrapper on + `getContext`, as for the 3D overlays). +- [ ] **E. Overlays.** (M) One SVG from the models: the scale bar, the + legend's continuous and category sections, the axes and the + selections, in the colours D8 gives each background. Tests on the + SVG. +- [ ] **F. The PNG file.** (S) Insert `pHYs` and `tEXt` chunks with their + CRC-32 (D11); the file name. Tests read the chunks back. +- [ ] **G. ViewerCore and the runner.** (M) + - A `screenshotRequest` prop, as `focusRequest` is, carrying the + options. ViewerCore takes the snapshot and runs it. + - Progress and `Cancel` in `loadingTasks`; one at a time; cancelled by a + dataset change (D12). + - The no-redraw guard: opening the popover and taking a screenshot must + not render the live DeckGL, which costs about 9 s per render headless. +- [ ] **H. The popover.** (M) `ScreenshotButton` in `TopBar.tsx`: scale, + the size line, `DPI`, include, background, the notes, the read + question, `Save PNG`, progress and `Cancel`. Tests in + `TopBar.test.tsx` on a fake runner. +- [ ] **I. Docs and end-to-end tests.** (M) + - Docs: [Docs To Update](#docs-to-update). + - Playwright on an offline fixture (a local OME-TIFF with cells under an + AnnData manifest): a 2× screenshot; check the download's size, its + `pHYs` and text chunks, and pixels at a known cell and a known image + feature. + - The axe test opens the popover; the baseline stays `{}`. + - A nightly `@live` test: a 4× screenshot of the Xenium demo, timed. + +## Order And Size + +| Milestone | Contents | Size | +| --------------- | -------- | ------------- | +| M0 — Spike | A | M | +| M1 — Screenshot | B to I | About 2 weeks | + +- B, E and F can go in parallel with A. C and D need A's answers. +- G needs C, D and E. H can start on a fake runner. +- The total is about 2½ weeks. + +## Risks + +| Risk | Effect | Mitigation | +| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | +| A second WebGL context with the cells' buffers | GPU memory doubles for a moment; a lost context on small GPUs | The spike measures it; the framebuffer alternative; the context lost as soon as it is done | +| Chromium's 16 live contexts | The oldest context, another view's, is dropped; the main view draws again, which counts toward its 3 (PR #420) | One off-screen Deck at a time, lost right after; the spike checks which context goes | +| WebGL shrinks a large drawing buffer silently | A tile drawn small and stretched | Tiles of at most 4,096 px (D9); check `drawingBufferWidth` and fail rather than stretch | +| Many image tiles at 4× and 8× | Minutes on a slow host (BioImage Archive, 3–10 MB/s) | The estimate and the question (D4), progress, `Cancel` | +| The read evicts the byte-range cache | The canvas and the readers lose their cached bytes | `persist: false` (D4) | +| Seams at tile edges | Lines across the PNG | Tiles on whole device pixels (D3, D9); the spike checks | +| A hidden tab | No animation frames; the Deck may not draw | `redraw` called directly; the spike checks | +| A large PNG | Seconds to encode; 512 MiB of pixels at the limit | The size limit (D10); `toBlob` is asynchronous | +| Every cell drawn (D5) | Denser than the screen, which samples | The popover says so, with both counts | +| Large typed arrays in React props | React 19's dev build walks them; dev tabs crash | The snapshot and the plan stay out of props, in the runner's private fields | + +## Docs To Update + +- `docs/ui-reference.md`: `Screenshot` in the Top Bar table, and a + Screenshot section with the popover's controls, the notes, the file + name and its chunks. +- `docs/user-guide.md`: making a figure, under Spatial Navigation: the + scale, the notes, and `All cells` and `Exact` for a complete view. +- `docs/architecture.md`: the off-screen drawing. +- `PLAN.md`: this phase's row. + +## Answered Questions + +Answered by the user on 2026-11-24 and folded into the decisions. + +1. **Every loaded cell** (D5), not the screen's sample. A strict "what you + see", with the render cap, was the other choice. +2. **Default scale: 2×** (D3), about 3,000 px wide for a 1,500 px canvas. + At 300 dpi that is 254 mm, wider than a journal's full page (about + 180 mm). 4× was the other choice. +3. **A tile that cannot be read fails the screenshot**, with `Retry` + ([How A Screenshot Runs](#how-a-screenshot-runs)), rather than saving + with a gap. +4. **`Copy` later.** The first version saves a PNG; putting it on the + clipboard (`ClipboardItem`) is under [Later](#later). + +## Later + +- The legend as its own SVG beside the PNG, to edit in Illustrator. +- `Copy` to the clipboard. +- A crop frame with a set aspect, or a size in mm. +- Collection sections side by side, the section stack and the 3D views. +- Vector SVG of small views (outlines and points under a limit), with the + image embedded. +- A keyboard shortcut. From 893c0ff7557097ed4f7100554c88ec4ac66a625d Mon Sep 17 00:00:00 2001 From: prete Date: Tue, 24 Nov 2026 21:41:53 +0000 Subject: [PATCH 2/3] Phase 27: own tile caches for screenshots; recheck at fe50d70 The canvas's tile caches already read a failed tile again after 1, 2 and 4 s (TILE_RETRY_DELAYS_MS; the early-timer fix in #426), then keep the error until the tile is evicted, with no way to forget one tile. So the screenshot gets its own TileCache and scheduler per channel: a Retry reads failed tiles again, and a read of hundreds of tiles does not push the canvas's tiles out of its cache. D4, the drawing steps, task C and the risks say so; the code map is rechecked at fe50d70. --- docs/plan/phases/27-screenshot.md | 55 ++++++++++++++++++++++++------- 1 file changed, 43 insertions(+), 12 deletions(-) diff --git a/docs/plan/phases/27-screenshot.md b/docs/plan/phases/27-screenshot.md index 44c9ad51..cac5dc2d 100644 --- a/docs/plan/phases/27-screenshot.md +++ b/docs/plan/phases/27-screenshot.md @@ -20,7 +20,8 @@ plan's four questions the same day ([Answered Questions](#answered-questions)); D3, D5, the failure rule and Later carry the answers. -The plan rests on a code map made on 2026-11-24 at `24f0fd2`. It is cited +The plan rests on a code map made on 2026-11-24 at `24f0fd2` and +rechecked the same day at `fe50d70`. It is cited below as `file:line`; line numbers drift as the code changes. Sizes are for one developer: **S** ≤ 1 day, **M** 2–4 days, **L** 1–2 weeks. @@ -118,14 +119,29 @@ What the work can build on: - Channels are added (`lighter`), except a single RGB channel, which is drawn over (`:73-93`). So tiles can be drawn in any order. - The level is `loader.bestLevel(2 ** zoom)` (`MorphologyCanvas.tsx:455`). - Each channel has a `MorphologyTileStore` cache and scheduler. While a - level loads, ready tiles of another level stand in (`:350-384`). + While a level loads, ready tiles of another level stand in + (`:350-384`). + - A `MorphologyTileStore` makes a `TileCache` and a + `TileRequestScheduler` for each channel (`morphologyTileStore.ts:60-80`), + sharing one `TileRequestSlots` when given a request limit (`:49-56`). + A cache holds 72, 120 or 180 tiles, by performance budget + (`performanceBudget.ts:18-41`). - The flat Visium image loads with `crossOrigin = 'anonymous'` (`morphologyTileStore.ts:157-158`). TIFF and Zarr tiles are `ImageBitmap`s decoded from fetched bytes. A canvas drawn from either can be read back. - `persist: false` on a tile fetch reads the IndexedDB byte-range cache without adding to it (`imagePyramid.ts:103-108`, plan 26-D8). +- **Failed tiles.** + - A failed read is read again after 1, 2 and 4 s + (`TILE_RETRY_DELAYS_MS`, `tileCache.ts:77-81`). The scheduler asks + again when the time comes, while a canvas still wants the tile + (`tileRequestScheduler.ts:85-87`, `:224-252`). Since + [PR #426](https://github.com/cellgeni/explorer/pull/426), a timer that + fires early waits again. + - Once the retries are spent, the cache keeps the error until the tile + is evicted or the cache is cleared (`tileCache.ts:77-80`). It has no + way to forget one tile: `clear()` empties it (`:217-227`). - **The deck.gl layers** come from `createOverviewLayers(cells, boundaries, options)` (`deckLayers.ts:166`), called with ViewerCore's inputs (`ViewerCore.tsx:1147-1173`). @@ -218,6 +234,13 @@ answers the same day; the others stand as proposed. own. - Reads use `persist: false`, so they do not evict what the canvas and the readers keep in the byte-range cache. + - The screenshot has its own `TileCache` and scheduler for each channel, + with the channel's colour and contrast, holding one grid tile's tiles, + and empties them when it ends. A read of hundreds of tiles at another + level would otherwise push the canvas's tiles out of its cache (72–180 + tiles), and `Retry` would get back the error of a tile whose retries + were spent. Its requests are limited to the budget's + `maxConcurrentTileRequests` (2, 4 or 6). - **D5. Every loaded cell.** The screenshot draws without the render cap's sample: zoomed out, the Xenium demo shows all 1.4 million cells, not about 250,000. Points keep the screen's size. It is one frame, drawn @@ -288,7 +311,8 @@ answers the same day; the others stand as proposed. - the read estimate and the notes (D7). 3. **Each grid tile**, row by row: 1. **Image.** Every channel's tiles under the grid tile are fetched - through the channel's tile store (`persist: false`). They are drawn + through the screenshot's own caches (D4; `persist: false`). They are + drawn into a scratch 2D canvas as they arrive, with the canvas's rules (`morphologyCanvas.ts:66-121`), the context scaled by N and the view state's target moved to the grid tile. @@ -300,9 +324,10 @@ answers the same day; the others stand as proposed. task as `redraw`, before the browser can clear it. If the off-screen Deck loses its context, the screenshot fails and says - so. A tile that fails is read once more. If it fails again, the screenshot - fails, names the channel and offers `Retry`: a figure with a hole in it - is worse than none. + so. A tile that fails is read again after 1, 2 and 4 s, as the canvas's + tiles are. Once those retries are spent, the screenshot fails, names the + channel and offers `Retry`, which starts again with new caches: a figure + with a hole in it is worse than none. 4. **Overlays.** One SVG over the whole frame in CSS pixels, from the snapshot's models, drawn onto the PNG's canvas at N× through an @@ -311,8 +336,9 @@ answers the same day; the others stand as proposed. 5. **Writing.** `toBlob('image/png')`. Then the `pHYs` and `tEXt` chunks are inserted after `IHDR` (D11), and `downloadBlob` saves the file. 6. **Clean-up.** The off-screen Deck is finalized and its context lost, as - `ReleasingDeck` does. The canvases are emptied (width 0). `Cancel` - aborts the tile fetches and the decode requests. + `ReleasingDeck` does. The canvases are emptied (width 0) and the + screenshot's tile caches cleared. `Cancel` aborts the tile fetches and + the decode requests. **The off-screen Deck** has its own canvas, never in the page. Its layers come from `createOverviewLayers` with the snapshot's inputs and three @@ -351,11 +377,15 @@ buffers. The spike chooses (task A). - fast-check tests: the tiles cover the frame exactly, without overlap, on whole device pixels. - The level at N× equals the level at 1× for a frame N times larger. -- [ ] **C. The image.** (M) `ScreenshotImageComposer`: fetch, draw and - composite per grid tile, with progress and abort. +- [ ] **C. The image.** (M) `ScreenshotImageComposer`: its own tile caches + (D4); fetch, draw and composite per grid tile, with progress and + abort. - Tests with a fake loader and a recording 2D context: levels, flipped and swapped placements, an origin offset (MERSCOPE), the flat image, - a z plane, and a tile that fails twice. + a z plane, a tile whose retries are spent, and `Retry` reading it + again. + - The canvas's caches hold the same tiles before and after a + screenshot. - [ ] **D. The deck.gl tiles.** (M) The off-screen renderer the spike chooses. - Tests that its layers carry the overrides, and that it loses its @@ -407,6 +437,7 @@ buffers. The spike chooses (task A). | WebGL shrinks a large drawing buffer silently | A tile drawn small and stretched | Tiles of at most 4,096 px (D9); check `drawingBufferWidth` and fail rather than stretch | | Many image tiles at 4× and 8× | Minutes on a slow host (BioImage Archive, 3–10 MB/s) | The estimate and the question (D4), progress, `Cancel` | | The read evicts the byte-range cache | The canvas and the readers lose their cached bytes | `persist: false` (D4) | +| The read evicts the canvas's decoded tiles | The canvas fetches and decodes its tiles again | The screenshot's own caches (D4) | | Seams at tile edges | Lines across the PNG | Tiles on whole device pixels (D3, D9); the spike checks | | A hidden tab | No animation frames; the Deck may not draw | `redraw` called directly; the spike checks | | A large PNG | Seconds to encode; 512 MiB of pixels at the limit | The size limit (D10); `toBlob` is asynchronous | From 5c59fa36a2e142b151e06903214be6d77940aaa7 Mon Sep 17 00:00:00 2001 From: prete Date: Tue, 24 Nov 2026 22:44:56 +0000 Subject: [PATCH 3/3] Phase 27: Screenshot, the spatial view as a high-resolution PNG MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Screenshot button beside Share saves the main 2D view as a PNG at 1×, 2×, 4× or 8× its size on screen, drawn again off screen: - the image at the pyramid level the PNG's pixel size needs, through the screenshot's own tile caches (persist: false), retried after 1, 2 and 4 s, then failing with Retry; - every loaded cell, not the render cap's sample, from an off-screen Deck at useDevicePixels N, in tiles of at most 4,096 px; - the scale bar, legend, axes and selections as one SVG at N×; - pHYs for the dpi and tEXt chunks for the software, source, view and time. App owns a ScreenshotRunner, which ViewerCore connects to its view, so no layers or typed arrays go into props and the live DeckGL does not render again. Progress and Cancel show in the popover and the loading list; changing dataset cancels it. deck.gl applies layers given before its device is ready in an animation frame, which a hidden page never runs, so the renderer runs one itself. On the Mac's GPU a 4× PNG of the whole Xenium slide, all 1,414,155 cells, took 1.6 s. The plan records the spike and where the build differs from it. --- PLAN.md | 2 +- docs/architecture.md | 12 + docs/plan/phases/27-screenshot.md | 102 ++- docs/ui-reference.md | 61 +- docs/user-guide.md | 22 + src/App.tsx | 79 +++ src/components/MorphologyCanvas.tsx | 24 +- src/components/ViewerCore.test.tsx | 66 ++ src/components/ViewerCore.tsx | 153 ++++- src/components/morphologyCanvasChannels.ts | 28 + src/components/ui/Popover.tsx | 7 + src/components/ui/icons.tsx | 10 + src/components/ui/index.ts | 1 + src/components/viewerCoreTypes.ts | 4 + src/features/app-shell/appRuntimeModel.ts | 21 + .../screenshot/ScreenshotButton.test.tsx | 286 +++++++++ src/features/screenshot/ScreenshotButton.tsx | 409 ++++++++++++ src/features/screenshot/pngChunks.test.ts | 75 +++ src/features/screenshot/pngChunks.ts | 204 ++++++ .../screenshot/screenshotDeck.test.ts | 259 ++++++++ src/features/screenshot/screenshotDeck.ts | 229 +++++++ .../screenshot/screenshotImage.test.ts | 354 +++++++++++ src/features/screenshot/screenshotImage.ts | 338 ++++++++++ src/features/screenshot/screenshotModel.ts | 51 ++ .../screenshot/screenshotOverlay.test.ts | 204 ++++++ src/features/screenshot/screenshotOverlay.ts | 589 ++++++++++++++++++ .../screenshot/screenshotPlan.test.ts | 238 +++++++ src/features/screenshot/screenshotPlan.ts | 262 ++++++++ src/features/screenshot/screenshotRun.test.ts | 317 ++++++++++ src/features/screenshot/screenshotRun.ts | 335 ++++++++++ .../screenshot/screenshotRunner.test.ts | 220 +++++++ src/features/screenshot/screenshotRunner.ts | 199 ++++++ src/features/shell/TopBar.tsx | 4 + src/features/shell/topBarModel.ts | 6 + src/rendering/morphologyCanvas.ts | 28 +- src/styles/shell.css | 123 +++- src/test/sectionModels.ts | 1 + tests/e2e/app.spec.ts | 167 +++++ 38 files changed, 5409 insertions(+), 81 deletions(-) create mode 100644 src/components/morphologyCanvasChannels.ts create mode 100644 src/features/screenshot/ScreenshotButton.test.tsx create mode 100644 src/features/screenshot/ScreenshotButton.tsx create mode 100644 src/features/screenshot/pngChunks.test.ts create mode 100644 src/features/screenshot/pngChunks.ts create mode 100644 src/features/screenshot/screenshotDeck.test.ts create mode 100644 src/features/screenshot/screenshotDeck.ts create mode 100644 src/features/screenshot/screenshotImage.test.ts create mode 100644 src/features/screenshot/screenshotImage.ts create mode 100644 src/features/screenshot/screenshotModel.ts create mode 100644 src/features/screenshot/screenshotOverlay.test.ts create mode 100644 src/features/screenshot/screenshotOverlay.ts create mode 100644 src/features/screenshot/screenshotPlan.test.ts create mode 100644 src/features/screenshot/screenshotPlan.ts create mode 100644 src/features/screenshot/screenshotRun.test.ts create mode 100644 src/features/screenshot/screenshotRun.ts create mode 100644 src/features/screenshot/screenshotRunner.test.ts create mode 100644 src/features/screenshot/screenshotRunner.ts diff --git a/PLAN.md b/PLAN.md index d421536f..64c611cd 100644 --- a/PLAN.md +++ b/PLAN.md @@ -59,7 +59,7 @@ Legend: `[x]` done · `[ ]` open · **Deferred** · **Dropped** · **Superseded* | [Phase 24](docs/plan/phases/24-section-stack.md) | 3D section stack: registered serial sections in 3D | Done (2026-11-18); one file's z and sections 2026-11-20 | | [Phase 25](docs/plan/phases/25-imported-segmentations.md) | Segmentations imported onto images (masks, polygons) | Done (2026-11-19) | | [Phase 26](docs/plan/phases/26-image-channel-conditions.md) | Cell query on image channels: mean and % above per cell | M1 and M2 done (2026-11-19): TIFF and OME-Zarr images | -| [Phase 27](docs/plan/phases/27-screenshot.md) | Screenshot: the spatial view as a high-resolution PNG | Planned (2026-11-24); spike next | +| [Phase 27](docs/plan/phases/27-screenshot.md) | Screenshot: the spatial view as a high-resolution PNG | Done (2026-11-24) | **Done** means a phase's tasks shipped. Most phase files also keep a Known Gaps list whose items stay open; [Open Items](docs/plan/open-items.md) diff --git a/docs/architecture.md b/docs/architecture.md index 6fcdf9ef..25ca6857 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -336,6 +336,18 @@ lets tests replace them. WebGL context live, and Chromium keeps 16 per page and drops the oldest, which is the 2D view's. `ReleasingDeck` loses the context and stops luma.gl's canvas observers once its canvas has left the page. +- Screenshots (`src/features/screenshot/`, plan 27) draw the view again off + screen. App makes one `ScreenshotRunner`; ViewerCore connects its snapshot + to it (the view, the frame, the image channels, a function that builds the + layers with every loaded cell, and the overlay models), and the top bar's + popover starts it. `drawScreenshot` draws the frame in tiles of at most + 4,096 px: the image through a `ScreenshotImageComposer`, with its own + `TileCache`s at the level the PNG needs, then the layers through a + `ScreenshotDeckRenderer`, a `ReleasingDeck` of its own whose canvas sits + hidden in the page and is copied out in the same task each tile is drawn, + then the scale bar, legend, axes and selections as one SVG. `pngChunks` + adds the dpi and text chunks. The Deck loses its context as soon as the + screenshot ends. ## Default Colours diff --git a/docs/plan/phases/27-screenshot.md b/docs/plan/phases/27-screenshot.md index cac5dc2d..33620cfa 100644 --- a/docs/plan/phases/27-screenshot.md +++ b/docs/plan/phases/27-screenshot.md @@ -20,6 +20,9 @@ plan's four questions the same day ([Answered Questions](#answered-questions)); D3, D5, the failure rule and Later carry the answers. +Built the same day, tasks A to I: [Spike Results](#spike-results-2026-11-24) +and [As Built](#as-built-2026-11-24). + The plan rests on a code map made on 2026-11-24 at `24f0fd2` and rechecked the same day at `fe50d70`. It is cited below as `file:line`; line numbers drift as the code changes. @@ -89,6 +92,87 @@ Non-goals: minimap and the zoom buttons. - Keeping the popover's choices in the link. +## Spike Results (2026-11-24) + +Task A, on the built screenshot rather than a throwaway one. A +production build in headless Chromium on the Mac's GPU (Apple M3, ANGLE +Metal), a 1,500 × 900 window and a frame of 1,140 × 852 CSS px, with the +Xenium demo. + +- **WebGL limits.** The renderbuffer, viewport and texture limits are + 16,384. Drawing buffers asked for at 4,096, 8,192 and 16,384 px a side + were all granted at that size. + +| View | PNG | Image read | Time from `Save PNG` | PNG size | JS heap at load, and at most while saving | +| ------------------------- | ---------------- | ------------------------------------ | -------------------- | -------- | ----------------------------------------- | +| Brain, 2× | 2,280 × 1,704 px | 4 tiles, 3.47 MB, cached | 0.50 s | 5.0 MiB | 550, 562 MiB | +| Brain, 4× | 4,560 × 3,408 px | 6 tiles, 3.47 MB, cached | 0.98 s | 16.6 MiB | 758, 557 MiB | +| Whole slide, 4×, on White | 4,560 × 3,408 px | 6 tiles, 3.67 MB; 5 fetches, 3.5 MiB | 1.57 s | 4.5 MiB | 1,302, 1,314 MiB | + +- **Every cell.** The whole slide drew all 1,414,155 cells; the screen + showed about 250,000. The tab grew 12 MiB, far under task A's 2 GB. +- **The brain view's tiles were cached.** At 0.088 and 0.044 µm per PNG + pixel both scales read level 0, which the canvas had read, so the bytes + came from the byte-range cache and nothing was fetched. +- **No seam** where a 4,096 px tile edge crosses points, in a crop of the + PNG around it. +- **The hidden host is gone after every run**, and the end-to-end test + counts one live WebGL context after a screenshot and no loss on the page. +- **The off-screen Deck stays.** It made each screenshot in a second or + two, so the framebuffer alternative was not tried. GPU memory was not + measured. +- **No animation frame, no cells.** deck.gl applies the layers it is given + before its device is ready in an animation frame. In a hidden page, + where `requestAnimationFrame` stops (the Browser pane when it is not + shown), the PNG had the image and no cells. The renderer now runs one + frame itself after `onLoad` (`animationLoop.redraw()`); the hidden pane + then drew the cells. +- **Not measured:** `toBlob` at 8,192 and 16,384 px, and the time with the + render cap's sample against every cell. +- **The `@live` test** (a 4× screenshot of the whole slide) passed in + 1.8 minutes, nearly all of it the dataset's load. + +## As Built (2026-11-24) + +All of D1 to D12, with these differences from the plan: + +- **A runner, not a request prop** (task G). App makes one + `ScreenshotRunner` and passes it to ViewerCore as `screenshot` and to the + top bar through its model. ViewerCore connects a function that returns + the snapshot of its view; the popover starts, cancels and retries + through the runner, and reads its state with `useSyncExternalStore`. The + snapshot holds a function that makes the layers, so no layer or typed + array goes into React props, and the live DeckGL does not render again + (ViewerCore's test checks it). +- **No `planScreenshot`** (task B). The plan is small functions in + `screenshotPlan.ts`: the size and the limit, the grid, each tile's view + state, each channel's level and reads, the print size and the notes. + The popover counts the read itself. +- **A pool, not a scheduler** (task C). The image composer keeps its own + `TileCache` per channel, holding twice the request limit plus 8 tiles, + and reads through a pool of `maxConcurrentTileRequests` workers rather + than a `TileRequestScheduler`. It reads again after each of + `TILE_RETRY_DELAYS_MS` itself. +- **The legend at the bottom left**, where the screen's notification stack + puts it, not the top right (D6). It leaves out classes hidden on the + screen, and lists those past what fits as "N more". +- **An image with no channel list** (a loader's image in white) gets its + contrast from the screenshot's first tile, as the canvas's cache does + from its own, so the two can differ a little. +- **The default scale** is 2×, or the largest scale under the limit when + 2× is over it. +- **Level of detail keyed on zoom** (grid cells, transcript density + squares) follows the screen's zoom: the Deck draws at that zoom with + `useDevicePixels: N`. +- **Top-bar labels.** `Screenshot` shows its label from 1,340 px and is + an icon alone below that; the panel toggles' labels now show from + 1,180 px rather than 1,100 px. Measured with the Mac's font and with + Verdana (wider, as on Linux), the bar has room at 861, 1,180 and + 1,340 px. +- **End-to-end** (task I): the offline smoke test uses a 64² TIFF with one + imported outline rather than an AnnData manifest. It compares the PNG, + halved, with a screenshot of the frame: the mean difference was 0.09 of 255. The axe test opens the popover. + ## Current State What the work can build on: @@ -355,7 +439,7 @@ buffers. The spike chooses (task A). ## Tasks -- [ ] **A. Spike.** (M) A throwaway screenshot of the Xenium demo +- [x] **A. Spike.** (M) A throwaway screenshot of the Xenium demo (1,414,155 cells, four channels) in a production build in headless Chromium on the Mac's GPU. Record in this file: - the off-screen Deck: time to the first frame with every cell and with @@ -370,14 +454,14 @@ buffers. The spike chooses (task A). MB and time; - revisit D5, D9 and D10 if a 4× screenshot of the whole slide takes over a minute, or the tab grows by more than 2 GB. -- [ ] **B. The plan.** (S) `planScreenshot` in +- [x] **B. The plan.** (S) `planScreenshot` in `src/features/screenshot/screenshotPlan.ts`: size and limit (D10), the tile grid (D9), levels and tiles per channel (D4), the read estimate and the notes (D7). - fast-check tests: the tiles cover the frame exactly, without overlap, on whole device pixels. - The level at N× equals the level at 1× for a frame N times larger. -- [ ] **C. The image.** (M) `ScreenshotImageComposer`: its own tile caches +- [x] **C. The image.** (M) `ScreenshotImageComposer`: its own tile caches (D4); fetch, draw and composite per grid tile, with progress and abort. - Tests with a fake loader and a recording 2D context: levels, flipped @@ -386,29 +470,29 @@ buffers. The spike chooses (task A). again. - The canvas's caches hold the same tiles before and after a screenshot. -- [ ] **D. The deck.gl tiles.** (M) The off-screen renderer the spike +- [x] **D. The deck.gl tiles.** (M) The off-screen renderer the spike chooses. - Tests that its layers carry the overrides, and that it loses its context when done (count live contexts with a `WeakRef` wrapper on `getContext`, as for the 3D overlays). -- [ ] **E. Overlays.** (M) One SVG from the models: the scale bar, the +- [x] **E. Overlays.** (M) One SVG from the models: the scale bar, the legend's continuous and category sections, the axes and the selections, in the colours D8 gives each background. Tests on the SVG. -- [ ] **F. The PNG file.** (S) Insert `pHYs` and `tEXt` chunks with their +- [x] **F. The PNG file.** (S) Insert `pHYs` and `tEXt` chunks with their CRC-32 (D11); the file name. Tests read the chunks back. -- [ ] **G. ViewerCore and the runner.** (M) +- [x] **G. ViewerCore and the runner.** (M) - A `screenshotRequest` prop, as `focusRequest` is, carrying the options. ViewerCore takes the snapshot and runs it. - Progress and `Cancel` in `loadingTasks`; one at a time; cancelled by a dataset change (D12). - The no-redraw guard: opening the popover and taking a screenshot must not render the live DeckGL, which costs about 9 s per render headless. -- [ ] **H. The popover.** (M) `ScreenshotButton` in `TopBar.tsx`: scale, +- [x] **H. The popover.** (M) `ScreenshotButton` in `TopBar.tsx`: scale, the size line, `DPI`, include, background, the notes, the read question, `Save PNG`, progress and `Cancel`. Tests in `TopBar.test.tsx` on a fake runner. -- [ ] **I. Docs and end-to-end tests.** (M) +- [x] **I. Docs and end-to-end tests.** (M) - Docs: [Docs To Update](#docs-to-update). - Playwright on an offline fixture (a local OME-TIFF with cells under an AnnData manifest): a 2× screenshot; check the download's size, its diff --git a/docs/ui-reference.md b/docs/ui-reference.md index 0435e512..2f1c099b 100644 --- a/docs/ui-reference.md +++ b/docs/ui-reference.md @@ -231,6 +231,7 @@ shown sections first (`setLinked`). | Measure ▾ | While measuring: `Measure unit` (µm or px, starting at the mouse coordinate unit) and `Clear Measurement` | | Magic Lens ▾ | `Radius` (10–500 µm, step 10; 80 µm) and `Summarise View`, which scans the whole view into the Magic Lens card | | Panels | `Embedding`, `Plots` and `Query` open and close the [Embedding](#embedding-panel), [Plots](#plots-panel) and [Cell Query](#cell-query-panel) panels; an open one is pressed. See below | +| `Screenshot` | A camera: saves the spatial view as a PNG at 1×, 2×, 4× or 8× its size; see [Screenshot](#screenshot) | | `Share` | Copies the link (the address, which holds the view) and says "Link copied" | | `Help` | `?` opens and closes it. Lists the keyboard shortcuts, from `SHORTCUTS` (`src/features/shell/shortcuts.ts`), the table the key handlers read, and links to the guides on GitHub (`HELP_LINKS`) | | `Settings` | See [Settings](#settings) | @@ -238,9 +239,10 @@ shown sections first (`setLinked`). **Panels** (the `Panels` group, `PanelToggles` in `TopBar.tsx`): the windows' toggles sit at the right of the bar, above where the windows open. A dataset shows only the ones it has: none on images, no `Plots` or `Query` -on Visium HD, whose bins are not cells the panels can read. From 1100 px -wide each shows its icon and name; between 860 and 1100 px only the icon, -with the name still read and in the tooltip. Under 860 px they fold into a +on Visium HD, whose bins are not cells the panels can read. From 1180 px +wide each shows its icon and name; between 860 and 1180 px only the icon, +with the name still read and in the tooltip. `Screenshot` shows its name +from 1340 px, and its camera alone below that. Under 860 px they fold into a menu (see [Narrow Screens](#narrow-screens)). Until 2026-11-19 they were Cells › Panels › `Show Embedding`, `Show Plots` and `Show Query`, below the genes and clusters. A window the open dataset lacks closes, so a dataset @@ -323,6 +325,55 @@ shown tooltip does only that, and the tool stays. `Boundary limit` applies on Enter or when the field is left. Escape puts the limit back, and a field left empty keeps it. +### Screenshot + +`Screenshot` (`ScreenshotButton`, `src/features/screenshot/`, plan 27) saves +the main 2D view as a PNG for a figure. It is off until a dataset is open, +and says so when the view has not drawn yet. Its popover: + +| Control | Type | Default | Notes | +| ------------ | -------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------- | +| `Scale` | Segmented 1× / 2× / 4× / 8× | 2×, or the largest under the limit below it | A scale over 16,384 px on a side or 128 megapixels is off, and its tooltip says which | +| Size line | Text | | "3,000 × 1,800 px · 0.25 µm per pixel · 254 × 152 mm at 300 dpi" | +| `DPI` | Number, 30–2400 | 300 | Written into the PNG; changes only the mm figure, not the pixels | +| `Include` | Checkboxes | `Scale bar`, `Legend`, `Axes` from Settings; `Selections` on | The scale bar bottom right, the legend bottom left, the rulers, and the saved and active selections | +| `Background` | Segmented Canvas / White / Transparent | Canvas | On White the scale bar's and legend's boxes turn white with dark text | +| Read line | Text | | "Reads 480 image tiles (96 MB)": the tiles at the PNG's scale, and their size where the TIFF index says | +| Notes | List | | What the view holds that the PNG shows differently, or still loads; see below | +| `Save PNG` | Button | | Above 512 MiB of tiles it asks first: `Read {size} and save` or `Back` | + +While it runs the popover shows its progress with `Cancel`, and so does the +loading list, as `Screenshot`; closing the popover does not stop it. One runs +at a time, and opening another dataset cancels it. A tile that cannot be read +after the canvas's retries (1, 2 and 4 s) fails it with `Retry`, which reads +again with new caches; a figure with a hole in it is worse than none. It ends +with "Saved {file}". + +The PNG is the canvas's frame, the part under the layer panel and the cards +included, drawn again off screen rather than copied (the live view is never +resized or read): + +- The image at the pyramid level the PNG's pixel size needs: a 4× PNG reads + the level a window four times larger would. Its tiles go through caches of + the screenshot's own, and reads leave the byte-range cache as it is. +- Every loaded cell, not the render cap's sample. The notes say so when the + screen samples ("Draws all 1,414,155 cells in view; the screen shows about + 250,000."), when expression is a sample at this zoom, when transcripts are + density squares, and what is still loading. The PNG shows what has loaded; + `All cells` and `Exact` make the view complete. +- Points, outlines and text keep their size against the frame, so the PNG + looks as the screen does, only sharper. +- The marks are drawn from their models at the PNG's scale. The legend leaves + out its controls and the classes hidden on the map. Tooltips, the + crosshair, the readouts, tool hints, a shape or measurement being drawn, + the minimap and the zoom buttons are left out. + +The file is `{dataset}-screenshot.png`, named as plot exports are. It records +its dpi (`pHYs`) and, in `tEXt` chunks, `Software` (the app, its release and +commit), `Source` (the dataset address without a presigned URL's +signature), `Description` (the view's x and y ranges, µm per pixel, the +scale and, for a z-stack, the plane) and `Creation Time` (UTC, ISO 8601). + ## Layer Panel The layer panel is an accordion with a section per layer. Each header has a @@ -1812,8 +1863,8 @@ stylesheet's narrow rules use too) the shell folds up: - The tools fold into a menu: its button shows the active tool ("Tools: Pan"), and it lists each tool with its key and, when off, why. Picking one closes the menu and returns focus to its button. The brand is - hidden, the summary chip is read out but not shown, and Share shows only its - icon. The Magic Lens options appear only while the lens is on. The dataset + hidden, the summary chip is read out but not shown, and Screenshot and + Share show only their icons. The Magic Lens options appear only while the lens is on. The dataset name gives way to the buttons, ending in "…". - The window toggles fold into a `Panels` menu beside Share, listing `Embedding`, `Plots` and `Query` with the open one pressed. Picking one diff --git a/docs/user-guide.md b/docs/user-guide.md index a4dd1a31..d3939744 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -269,6 +269,28 @@ the top bar copies the link to share the same view. Older links with `tab=` still work. Each dataset you open is a step in the browser's history, so Back returns to the previous dataset, or to the start screen. +### Making A Figure + +`Screenshot` (the camera in the top bar) saves the spatial view as a PNG for +a figure. Frame the view, then pick: + +- **Scale**: the PNG is 1, 2, 4 or 8 times the size of the view on screen. + The line under it gives the size in pixels, µm per pixel and the size in + print at the `DPI` you set (300 to start). The image is read at the detail + the larger size needs, and points, outlines and text grow with it, so the + PNG looks like the screen, only sharper. +- **Include**: the scale bar, legend and axes start from Settings; the + selections' outlines start on. +- **Background**: black as on screen, white, or transparent. + +The PNG draws every loaded cell, where the screen draws a sample of a large +dataset zoomed out; the popover says so. It also says when expression is a +sample at this zoom or transcripts are density squares: set +`Expression detail` to `All cells`, and the transcripts' `Detail` to `Exact` +(or zoom in), for a complete figure. A screenshot that reads a lot of image +asks first, and you can cancel it from the popover or the loading list. The +file records the dpi, the dataset, the view in µm and when it was made. + ## Layers And Genes The layer panel's Image section controls dataset image opacity, image diff --git a/src/App.tsx b/src/App.tsx index d098890f..40abaa6e 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -4,6 +4,7 @@ import { useMemo, useRef, useState, + useSyncExternalStore, type CSSProperties, } from 'react' import { @@ -60,6 +61,14 @@ import { manifestSegmentationSource } from './datasets/datasetManifest' import { datasetManifestFor } from './data/datasetFiles' import { ShellLayout } from './features/shell/ShellLayout' import { useTopBarModel } from './features/shell/topBarModel' +import { + ScreenshotRunner, + screenshotStageText, +} from './features/screenshot/screenshotRunner' +import { + screenshotFileInfo, + type ScreenshotModel, +} from './features/screenshot/screenshotModel' import { useToolShortcuts } from './features/shell/useToolShortcuts' import { useNarrowScreen } from './features/shell/useNarrowScreen' import { useCardStackModel } from './features/cards/cardModels' @@ -520,6 +529,12 @@ export function App({ dependencies }: AppProps = {}) { } | null>(null) const datasetUrl = useViewerStore((state) => state.datasetUrl) + // Screenshots of the spatial view (plan 27), one at a time. + const [screenshotRunner] = useState(() => new ScreenshotRunner()) + const screenshotState = useSyncExternalStore( + screenshotRunner.subscribe, + screenshotRunner.getState, + ) const setDatasetUrl = useViewerStore((state) => state.setDatasetUrl) const appState = useAppDomainState({ initialShareableState, performanceBudget }) const { @@ -2715,9 +2730,21 @@ export function App({ dependencies }: AppProps = {}) { detail: `${importedSegmentation.state.shapeCount.toLocaleString()} outlines`, } : undefined, + screenshotLoading: + screenshotState.status === 'running' + ? { + detail: screenshotStageText(screenshotState.progress), + progress: + screenshotState.progress === null + ? undefined + : screenshotState.progress.done / + Math.max(1, screenshotState.progress.total), + } + : undefined, boundariesAreSegmentation: platformAdapter.kind === 'image', }), [ + screenshotState, importedSegmentation.state, platformAdapter.kind, analysisEmbeddingState, @@ -3975,6 +4002,9 @@ export function App({ dependencies }: AppProps = {}) { 'cell-transcripts': cancelCellDetails, 'roi-cells': handleCancelRoiCells, 'roi-genes': handleCancelRoiGenes, + screenshot: () => { + screenshotRunner.cancel() + }, } cancelLoadingTaskRef.current = (id) => { @@ -4962,6 +4992,53 @@ export function App({ dependencies }: AppProps = {}) { : loadState.status === 'loading' ? loadState.url : null + // Changing dataset cancels a screenshot of the last one (27-D12). + useEffect( + () => () => { + screenshotRunner.cancel() + }, + [loadedDatasetUrl, screenshotRunner], + ) + const screenshotModel = useMemo( + () => + loadedDatasetUrl === null + ? null + : { + runner: screenshotRunner, + available: true, + include: { + scaleBar: showScaleBar, + legend: showLegend, + axes: showAxes, + selections: true, + }, + expressionSampled: + geneExpressionState.status === 'ready' && + (geneExpressionState.mode === 'sampled' || + geneExpressionState.mode === 'overview-sampled'), + transcriptsAsDensity: transcriptLayerAggregateBins.length > 0, + loadingLabels: loadingTasks + .filter((task) => task.id !== 'screenshot') + .map((task) => task.label), + file: screenshotFileInfo( + loadedDatasetUrl, + morphologyImage?.zStack === undefined + ? null + : morphologyImage.zStack.zPlane + 1, + ), + }, + [ + geneExpressionState, + loadedDatasetUrl, + loadingTasks, + morphologyImage, + screenshotRunner, + showAxes, + showLegend, + showScaleBar, + transcriptLayerAggregateBins.length, + ], + ) const topBar = useTopBarModel({ activeTool, appendDebugEvent, @@ -4993,6 +5070,7 @@ export function App({ dependencies }: AppProps = {}) { onReturnToPan: returnToPan, onRoiModeChange: handleRoiModeChange, platform: platformAdapter.kind, + screenshot: screenshotModel, setDebugMode, }) const [fitRequestKey, setFitRequestKey] = useState(0) @@ -5418,6 +5496,7 @@ export function App({ dependencies }: AppProps = {}) { axes={showAxes} scaleBar={showScaleBar} fitRequestKey={fitRequestKey} + screenshot={screenshotRunner} onImageTileError={handleImageTileError} onTileCacheEviction={handleTileCacheEviction} onViewportCellCountChange={setViewportCellCount} diff --git a/src/components/MorphologyCanvas.tsx b/src/components/MorphologyCanvas.tsx index e222d427..220aac4d 100644 --- a/src/components/MorphologyCanvas.tsx +++ b/src/components/MorphologyCanvas.tsx @@ -15,6 +15,7 @@ import { } from '../rendering/morphologyCanvas' import { tileSchedulingForLoader } from '../rendering/morphologyTileScheduling' import { MorphologyTileStore } from '../rendering/morphologyTileStore' +import { visibleMorphologyChannels } from './morphologyCanvasChannels' import type { DisplayWindow } from '../codecs/jpeg2000' import type { CssViewportSize } from '../rendering/morphologyCanvas' import type { ImagePyramidLoader } from '../data/imagePyramid' @@ -407,29 +408,6 @@ function requestedTilesWillRetry(requests: readonly ChannelRequest[]): boolean { ) } -function visibleMorphologyChannels( - loader: ImagePyramidLoader | null | undefined, - channels: readonly MorphologyCanvasChannel[] | undefined, -): readonly MorphologyCanvasChannel[] { - if (channels !== undefined && channels.length > 0) { - return channels.filter((channel) => channel.enabled) - } - - if (loader === null || loader === undefined) { - return [] - } - - return [ - { - id: loader.url, - loader, - enabled: true, - color: [255, 255, 255], - opacity: 1, - }, - ] -} - interface ChannelRequestPlan { readonly spec: MorphologyTileChannelSpec readonly channel: MorphologyCanvasChannel diff --git a/src/components/ViewerCore.test.tsx b/src/components/ViewerCore.test.tsx index 5e0056d6..a9c7e6f9 100644 --- a/src/components/ViewerCore.test.tsx +++ b/src/components/ViewerCore.test.tsx @@ -1,6 +1,7 @@ import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { LinkedViewChannel } from './linkedView' +import { ScreenshotRunner } from '../features/screenshot/screenshotRunner' import { ViewerCore, type ViewerViewportDetail } from './ViewerCore' import { scaffoldDeckLayerCount } from './viewerCoreModel' import type { @@ -3045,6 +3046,71 @@ describe('ViewerCore', () => { }) expect(selection.points).toHaveLength(4) }) + + it('connects a screenshot of its view without drawing the view again (plan 27)', async () => { + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(rect) + vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null) + const runner = new ScreenshotRunner() + const cells = ['a', 'b', 'c', 'd'].map((id, index) => ({ + ...overviewCellDatum(), + id, + position: [index * 10, 0, 0] as [number, number, number], + })) + const legendSections = [ + { + kind: 'categories' as const, + id: 'clusters', + title: 'Clusters', + items: [{ id: '1', label: 'One', color: '#f00', count: 4, visible: true }], + }, + ] + render( + , + ) + await waitFor(() => { + expect(runner.preview()).not.toBeNull() + }) + const renderCountBefore = deckGlMock.renderCount + const snapshot = runner.preview() + + expect(snapshot?.viewport).toEqual({ width: 200, height: 100 }) + expect(snapshot?.cells).toEqual({ inView: 4, onScreen: 1 }) + // Include starts from Settings, so the snapshot keeps what Settings hides. + expect(snapshot?.overlays.legend).toEqual(legendSections) + expect(snapshot?.overlays.scaleBar).not.toBeNull() + expect(snapshot?.overlays.selections).toEqual([ + expect.objectContaining({ saved: false, color: null }), + ]) + + const layers = (snapshot?.layers?.() ?? []).flat() as { + readonly id: string + readonly props: { readonly pickable?: boolean; readonly filterRange?: unknown } + }[] + const points = layers.find((layer) => layer.id === 'cells-overview-scatter') + expect(points?.props.pickable).toBe(false) + expect(points?.props.filterRange).toEqual([ + [0, 1], + [0, 0.5], + ]) + expect(deckGlMock.layers).not.toContain(points) + expect(deckGlMock.renderCount).toBe(renderCountBefore) + }) }) // A luma.gl device whose context is already lost, drawing to `canvas`. diff --git a/src/components/ViewerCore.tsx b/src/components/ViewerCore.tsx index 865983d4..82eb8315 100644 --- a/src/components/ViewerCore.tsx +++ b/src/components/ViewerCore.tsx @@ -14,6 +14,15 @@ import { removeDeckFromTabOrder } from './deckTabOrder' import { ReleasingDeck } from './releasingDeck' import type { LinkedViewChannel } from './linkedView' import { MorphologyCanvas } from './MorphologyCanvas' +import { visibleMorphologyChannels } from './morphologyCanvasChannels' +import { screenshotLayerOptions } from '../features/screenshot/screenshotDeck' +import { screenshotSelectionPaths } from '../features/screenshot/screenshotOverlay' +import { + SCREENSHOT_DEFAULT_TILE_REQUESTS, + screenshotFrame, +} from '../features/screenshot/screenshotPlan' +import type { ScreenshotRunner } from '../features/screenshot/screenshotRunner' +import type { ScreenshotSnapshot } from '../features/screenshot/screenshotRun' import { LoadingIndicator, type LoadingTaskSummary } from './AppStatusPanels' import { CloseIcon, FitIcon, IconButton, MinusIcon, PlusIcon } from './ui' import { useKeepFocus } from './ui/useKeepFocus' @@ -166,7 +175,7 @@ import type { TranscriptAggregateDatum, TranscriptPointDatum, } from '../rendering/deckLayers' -import type { OverviewViewState } from '../rendering/deckLayers' +import type { OverviewLayerOptions, OverviewViewState } from '../rendering/deckLayers' import { DEFAULT_CELL_BOUNDARY_OPACITY, DEFAULT_CELL_FILL_OPACITY, @@ -333,6 +342,7 @@ export function ViewerCore({ axes = false, scaleBar = true, fitRequestKey = 0, + screenshot = null, overviewRenderCellLimit, movingOverviewRenderCellLimit, clipOverviewCellsToViewport = true, @@ -424,6 +434,7 @@ export function ViewerCore({ loadingTasks={loadingTasks} {...(onCancelLoadingTask === undefined ? {} : { onCancelLoadingTask })} legendSections={legend ? legendSections : EMPTY_LEGEND_SECTIONS} + screenshotLegendSections={legendSections} showZoomLevel={showZoomLevel} selectionHighlight={selectionHighlight} {...(onClearSelection === undefined ? {} : { onClearSelection })} @@ -448,6 +459,7 @@ export function ViewerCore({ scaleBar={scaleBar} minimapPoints={minimapDots} fitRequestKey={fitRequestKey} + screenshot={screenshot} {...(overviewRenderCellLimit === undefined ? {} : { overviewRenderCellLimit })} {...(movingOverviewRenderCellLimit === undefined ? {} @@ -520,6 +532,8 @@ interface ViewerSurfaceProps { readonly loadingTasks: readonly LoadingTaskSummary[] readonly onCancelLoadingTask?: (id: string) => void readonly legendSections: readonly ViewerLegendSection[] + // The legend's sections whether or not Settings shows it, for screenshots. + readonly screenshotLegendSections: readonly ViewerLegendSection[] readonly showZoomLevel: boolean readonly selectionHighlight: ViewerSelectionHighlight | null readonly onClearSelection?: () => void @@ -546,6 +560,7 @@ interface ViewerSurfaceProps { readonly scaleBar: boolean readonly minimapPoints: readonly (readonly [number, number])[] readonly fitRequestKey: number + readonly screenshot: ScreenshotRunner | null readonly overviewRenderCellLimit?: number | null readonly movingOverviewRenderCellLimit?: number readonly clipOverviewCellsToViewport: boolean @@ -614,6 +629,7 @@ function ViewerSurface({ loadingTasks, onCancelLoadingTask, legendSections, + screenshotLegendSections, showZoomLevel, selectionHighlight, onClearSelection, @@ -636,6 +652,7 @@ function ViewerSurface({ scaleBar, minimapPoints: minimapDots, fitRequestKey, + screenshot, overviewRenderCellLimit, movingOverviewRenderCellLimit, clipOverviewCellsToViewport, @@ -1144,33 +1161,32 @@ function ViewerSurface({ cellBoundaryFillEnabled, ], ) - const layers = useMemo( - () => - createOverviewLayers(cells, boundaries, { - cellsVisible: cellLayersVisible, - cellFillOpacity, - cellBoundaryOpacity, - cellPointPickable, - cellBoundaryFillEnabled, - cellBoundaryPickable: cellBoundaryHoverEnabled, - nucleusBoundaries, - gridCells: gridCellPacking, - cellBoundaryGeometry: boundaryLayerGeometry, - cellBoundaryStyle: boundaryLayerStyle, - geneExpressionActive, - geneExpressionOverlayElements, - transcriptAggregateBins, - transcriptPoints, - geometricAnnotations, - transcriptOpacity, - transcriptPointSize, - pointSizeZoomDelta: viewState.zoom - fittedViewZoom, - pointSizeFullViewScale, - pointSizeCellCount: fullViewCellPointCount, - trueSizePoints, - cellPointScale, - cellPointPacking, - }), + const overviewLayerOptions = useMemo( + () => ({ + cellsVisible: cellLayersVisible, + cellFillOpacity, + cellBoundaryOpacity, + cellPointPickable, + cellBoundaryFillEnabled, + cellBoundaryPickable: cellBoundaryHoverEnabled, + nucleusBoundaries, + gridCells: gridCellPacking, + cellBoundaryGeometry: boundaryLayerGeometry, + cellBoundaryStyle: boundaryLayerStyle, + geneExpressionActive, + geneExpressionOverlayElements, + transcriptAggregateBins, + transcriptPoints, + geometricAnnotations, + transcriptOpacity, + transcriptPointSize, + pointSizeZoomDelta: viewState.zoom - fittedViewZoom, + pointSizeFullViewScale, + pointSizeCellCount: fullViewCellPointCount, + trueSizePoints, + cellPointScale, + cellPointPacking, + }), [ cellBoundaryOpacity, cellLayersVisible, @@ -1180,9 +1196,7 @@ function ViewerSurface({ cellBoundaryHoverEnabled, boundaryLayerGeometry, boundaryLayerStyle, - boundaries, nucleusBoundaries, - cells, cellPointPacking, gridCellPacking, geneExpressionActive, @@ -1200,6 +1214,10 @@ function ViewerSurface({ fittedViewZoom, ], ) + const layers = useMemo( + () => createOverviewLayers(cells, boundaries, overviewLayerOptions), + [boundaries, cells, overviewLayerOptions], + ) // A lost WebGL context draws the view again on a new canvas (EXP-325), with // new layers: deck.gl cannot reuse a layer its old Deck finalized. const deviceLoss = useDeckDeviceLoss() @@ -1503,6 +1521,81 @@ function ViewerSurface({ viewport, ], ) + // Screenshots (plan 27): the view as it is when one is taken, built only + // then. The runner never changes, so connecting it redraws nothing. + const viewChangedAtRef = useRef(0) + useEffect(() => { + viewChangedAtRef.current = performance.now() + }, [viewState]) + const activeSelectionOutlineColor = selectionOutlines.find( + (outline) => outline.active, + )?.color + const screenshotSnapshotRef = useRef<() => ScreenshotSnapshot | null>(() => null) + useLayoutEffect(() => { + screenshotSnapshotRef.current = () => { + if (!viewportMeasured || !canTrackMouseCoordinates) return null + const frame = screenshotFrame(viewport) + + return { + viewState, + viewport: frame, + image: { + channels: visibleMorphologyChannels(imageLoader, imageChannels), + flatImage, + opacity: imageOpacity, + }, + layers: hasSpatialData + ? () => + createOverviewLayers( + cells, + boundaries, + screenshotLayerOptions(overviewLayerOptions), + ) + : null, + overlays: { + scaleBar: scaleBarModel( + viewState, + frame, + coordinateUnit, + micrometersPerPixel, + physicalUnitLabel, + ), + axes: viewerAxesModel( + viewState, + frame, + coordinateUnit, + micrometersPerPixel, + physicalUnitLabel, + ), + legend: screenshotLegendSections, + selections: screenshotSelectionPaths( + selectionOutlines, + displayedRoiSelection, + activeSelectionOutlineColor ?? null, + viewState, + frame, + ), + }, + cells: hasCells + ? { + inView: visibleCellCount, + onScreen: Math.min( + visibleCellCount, + Math.round(visibleCellCount * cellPointSample), + ), + } + : null, + unitLabel: physicalUnitLabel, + maxConcurrentTileRequests: + maxConcurrentTileRequests ?? SCREENSHOT_DEFAULT_TILE_REQUESTS, + viewChangedAt: viewChangedAtRef.current, + } + } + }) + useEffect( + () => screenshot?.connect(() => screenshotSnapshotRef.current()), + [screenshot], + ) const flushMouseCoordinate = useCallback(() => { mouseCoordinateFrameRef.current = null setMouseCoordinate(pendingMouseCoordinateRef.current) diff --git a/src/components/morphologyCanvasChannels.ts b/src/components/morphologyCanvasChannels.ts new file mode 100644 index 00000000..1858163b --- /dev/null +++ b/src/components/morphologyCanvasChannels.ts @@ -0,0 +1,28 @@ +import type { ImagePyramidLoader } from '../data/imagePyramid' +import type { MorphologyCanvasChannel } from './MorphologyCanvas' + +// The channels a MorphologyCanvas draws: the enabled ones, or the loader's +// image in white when it is given no channels. A screenshot draws the same +// (plan 27). +export function visibleMorphologyChannels( + loader: ImagePyramidLoader | null | undefined, + channels: readonly MorphologyCanvasChannel[] | undefined, +): readonly MorphologyCanvasChannel[] { + if (channels !== undefined && channels.length > 0) { + return channels.filter((channel) => channel.enabled) + } + + if (loader === null || loader === undefined) { + return [] + } + + return [ + { + id: loader.url, + loader, + enabled: true, + color: [255, 255, 255], + opacity: 1, + }, + ] +} diff --git a/src/components/ui/Popover.tsx b/src/components/ui/Popover.tsx index 75170f9c..fd6f26c9 100644 --- a/src/components/ui/Popover.tsx +++ b/src/components/ui/Popover.tsx @@ -14,6 +14,9 @@ export interface PopoverProps { // Which edge of the trigger the popover lines up with. readonly align?: 'start' | 'end' | undefined readonly triggerClassName?: string | undefined + // The trigger's accessible name, where its tooltip says more than its name. + readonly triggerLabel?: string | undefined + readonly disabled?: boolean | undefined readonly className?: string | undefined } @@ -29,6 +32,8 @@ export function Popover({ onOpenChange, align = 'start', triggerClassName, + triggerLabel, + disabled = false, className, }: PopoverProps) { const id = useId() @@ -90,6 +95,8 @@ export function Popover({ aria-haspopup="dialog" aria-expanded={isOpen} aria-controls={isOpen ? id : undefined} + aria-label={triggerLabel} + disabled={disabled} className={classNames('ui-button', 'ui-button--ghost', triggerClassName)} onClick={() => { setOpen(!isOpen) diff --git a/src/components/ui/icons.tsx b/src/components/ui/icons.tsx index 663cd1b7..473de872 100644 --- a/src/components/ui/icons.tsx +++ b/src/components/ui/icons.tsx @@ -227,6 +227,16 @@ export function ImageIcon() { ) } +// A camera, for Screenshot (plan 27). +export function CameraIcon() { + return ( + + ) +} + // Two sections side by side. export function SideBySideIcon() { return ( diff --git a/src/components/ui/index.ts b/src/components/ui/index.ts index 65b85dcd..668d42bd 100644 --- a/src/components/ui/index.ts +++ b/src/components/ui/index.ts @@ -17,6 +17,7 @@ export { Switch, type SwitchProps } from './Switch' export { Tooltip, type TooltipProps } from './Tooltip' export { BoxSelectIcon, + CameraIcon, ChevronDownIcon, ChevronRightIcon, CloseIcon, diff --git a/src/components/viewerCoreTypes.ts b/src/components/viewerCoreTypes.ts index 8904b113..25978eba 100644 --- a/src/components/viewerCoreTypes.ts +++ b/src/components/viewerCoreTypes.ts @@ -21,6 +21,7 @@ import type { import type { ImagePyramidLoader } from '../data/imagePyramid' import type { GridCellColumns } from '../rendering/gridCellColumns' import type { LoadingTaskSummary } from './AppStatusPanels' +import type { ScreenshotRunner } from '../features/screenshot/screenshotRunner' import type { FlatMorphologyCanvasImage, MorphologyCanvasChannel, @@ -125,6 +126,9 @@ export interface ViewerCoreProps { readonly scaleBar?: boolean // Fits the data to the view whenever it changes (the F key). readonly fitRequestKey?: number + // Takes screenshots of the view (plan 27): the viewer connects its + // snapshot to it. One runner for the life of the app, so it never changes. + readonly screenshot?: ScreenshotRunner | null readonly overviewRenderCellLimit?: number | null // When overviewRenderCellLimit is null and every cell draws, the cells // drawn while the view moves, so pans and zooms do not draw them all on diff --git a/src/features/app-shell/appRuntimeModel.ts b/src/features/app-shell/appRuntimeModel.ts index 9dedab65..8b0e2a4d 100644 --- a/src/features/app-shell/appRuntimeModel.ts +++ b/src/features/app-shell/appRuntimeModel.ts @@ -27,6 +27,8 @@ export type LoadingTaskArea = | 'magic-lens' | 'selection' | 'cell' + // A screenshot being drawn (plan 27); no section shows it. + | 'screenshot' export interface LoadingTask { readonly id: string @@ -52,6 +54,7 @@ export type CancellableLoadingTaskId = | 'cell-transcripts' | 'roi-cells' | 'roi-genes' + | 'screenshot' const CANCELLABLE_LOADING_TASK_IDS: ReadonlySet = new Set([ @@ -64,6 +67,7 @@ const CANCELLABLE_LOADING_TASK_IDS: ReadonlySet = 'cell-transcripts', 'roi-cells', 'roi-genes', + 'screenshot', ]) export function isCancellableLoadingTaskId(id: string): id is CancellableLoadingTaskId { @@ -123,6 +127,10 @@ interface LoadingTaskStateInputs { readonly transcriptLoadProgress?: number | undefined // An image's imported segmentation being read, and what it has read. readonly segmentationLoading?: { readonly detail?: string } | undefined + // A screenshot being drawn: how far it has got (plan 27-D12). + readonly screenshotLoading?: + | { readonly detail: string; readonly progress?: number | undefined } + | undefined // An image's outlines are its imported segmentation's, in the // Segmentation section. readonly boundariesAreSegmentation?: boolean @@ -185,6 +193,7 @@ export function createLoadingTasks({ magicLensLoadingScopeLabel = 'Lens', transcriptLoadProgress, segmentationLoading, + screenshotLoading, boundariesAreSegmentation = false, }: LoadingTaskStateInputs): readonly LoadingTask[] { const tasks: LoadingTask[] = [] @@ -399,6 +408,18 @@ export function createLoadingTasks({ }) } + if (screenshotLoading !== undefined) { + tasks.push({ + id: 'screenshot', + area: 'screenshot', + label: 'Screenshot', + detail: screenshotLoading.detail, + ...(screenshotLoading.progress === undefined + ? {} + : { progress: screenshotLoading.progress }), + }) + } + if (autoContrastChannelCount > 0) { const channelNoun = autoContrastChannelCount === 1 ? 'channel' : 'channels' tasks.push({ diff --git a/src/features/screenshot/ScreenshotButton.test.tsx b/src/features/screenshot/ScreenshotButton.test.tsx new file mode 100644 index 00000000..990a8b46 --- /dev/null +++ b/src/features/screenshot/ScreenshotButton.test.tsx @@ -0,0 +1,286 @@ +import { act, fireEvent, render, screen, within } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import { imagePixels, micrometers } from '../../data/coords' +import type { ImagePyramidLoader } from '../../data/imagePyramid' +import { + testDatasetInfoModel, + testDatasetLibraryModel, + testTopBarModel, + testViewSettingsModel, +} from '../../test/sectionModels' +import { TopBar } from '../shell/TopBar' +import { ScreenshotButton } from './ScreenshotButton' +import type { ScreenshotModel } from './screenshotModel' +import type { DrawScreenshotOptions, ScreenshotSnapshot } from './screenshotRun' +import { ScreenshotRunner, type ScreenshotRunnerOptions } from './screenshotRunner' + +function loader(bytesPerTile: number | null): ImagePyramidLoader { + return { + url: 'https://example.test/dapi.ome.tif', + channels: [{ id: 'dapi', name: 'DAPI' }], + bestLevel: () => 0, + tilesForBbox: () => [ + { col: 0, row: 0 }, + { col: 1, row: 0 }, + ], + tileBounds: () => ({ + minX: micrometers(0), + maxX: micrometers(1), + minY: micrometers(0), + maxY: micrometers(1), + }), + tileSourceSize: () => ({ width: imagePixels(1), height: imagePixels(1) }), + tileReadBytes: (_level: number, tiles: readonly unknown[]) => + Promise.resolve(bytesPerTile === null ? null : bytesPerTile * tiles.length), + } as unknown as ImagePyramidLoader +} + +function snapshot( + overrides: Partial = {}, + bytesPerTile: number | null = 1_000_000, +): ScreenshotSnapshot { + const image = loader(bytesPerTile) + return { + viewState: { target: [0, 0, 0], zoom: 1, minZoom: -10, maxZoom: 10 }, + viewport: { width: 1500, height: 900 }, + image: { + channels: [{ id: 'dapi', loader: image, enabled: true, color: [0, 0, 255] }], + flatImage: null, + opacity: 1, + }, + layers: null, + overlays: { scaleBar: null, axes: null, legend: [], selections: [] }, + cells: { inView: 1_414_155, onScreen: 250_000 }, + unitLabel: 'µm', + maxConcurrentTileRequests: 4, + viewChangedAt: -1000, + ...overrides, + } +} + +function model( + view: ScreenshotSnapshot | null, + runnerOptions: ScreenshotRunnerOptions = {}, + overrides: Partial = {}, +): ScreenshotModel { + const runner = new ScreenshotRunner({ save: vi.fn(), now: () => 0, ...runnerOptions }) + if (view !== null) runner.connect(() => view) + + return { + runner, + available: true, + include: { scaleBar: true, legend: false, axes: true, selections: true }, + expressionSampled: false, + transcriptsAsDensity: false, + loadingLabels: [], + file: { + fileName: 'sob23-screenshot.png', + software: 'Spatial Omics Explorer', + source: 'https://example.test/sob23', + zPlane: null, + }, + ...overrides, + } +} + +function open() { + fireEvent.click(screen.getByRole('button', { name: 'Screenshot' })) + return screen.getByRole('dialog', { + name: 'Save the spatial view as a high-resolution PNG', + }) +} + +describe('Screenshot (plan 27, task H)', () => { + it('sits beside Share in the top bar, and is off without a dataset', () => { + const { rerender } = render( + , + ) + const screenshot = screen.getByRole('button', { name: 'Screenshot' }) + + const share = screen.getByRole('button', { name: /Share/ }) + expect( + screenshot.compareDocumentPosition(share) & Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy() + expect(screenshot).toBeEnabled() + + rerender( + , + ) + expect(screen.getByRole('button', { name: 'Screenshot' })).toBeDisabled() + }) + + it('gives the size, what it means in print, and the read (D3, D4)', async () => { + render() + const dialog = open() + + expect(within(dialog).getByRole('button', { name: '2×' })).toHaveAttribute( + 'aria-pressed', + 'true', + ) + expect( + within(dialog).getByText( + '3,000 × 1,800 px · 0.25 µm per pixel · 254 × 152 mm at 300 dpi', + ), + ).toBeInTheDocument() + expect( + await within(dialog).findByText('Reads 2 image tiles (2 MB).'), + ).toBeInTheDocument() + }) + + it('turns off scales past the size limit (D10)', () => { + render( + , + ) + const dialog = open() + const eight = within(dialog).getByRole('button', { name: '8×' }) + + // 16,800 px wide. + expect(eight).toBeDisabled() + expect(eight).toHaveAttribute('title', 'Over 16,384 px on a side: too large to draw') + expect(within(dialog).getByRole('button', { name: '4×' })).toBeEnabled() + }) + + it('notes the cells the screen samples and what is loading (D5, D7)', () => { + render( + , + ) + const dialog = open() + + expect( + within(dialog).getByText( + 'Draws all 1,414,155 cells in view; the screen shows about 250,000.', + ), + ).toBeInTheDocument() + expect( + within(dialog).getByText(/Still loading: Loading cell boundaries/), + ).toBeInTheDocument() + }) + + it('starts the screenshot with the options chosen', async () => { + const draw = vi.fn().mockResolvedValue(new Blob()) + const save = vi.fn() + render( + , + ) + const dialog = open() + + fireEvent.click(within(dialog).getByRole('button', { name: '4×' })) + fireEvent.click(within(dialog).getByRole('checkbox', { name: 'Legend' })) + fireEvent.click(within(dialog).getByRole('checkbox', { name: 'Axes' })) + fireEvent.click(within(dialog).getByRole('button', { name: 'White' })) + fireEvent.click(within(dialog).getByRole('button', { name: 'Save PNG' })) + + await vi.waitFor(() => { + expect(save).toHaveBeenCalledWith('sob23-screenshot.png', expect.any(Blob)) + }) + expect(draw.mock.calls[0]?.[1]).toEqual({ + scale: 4, + dpi: 300, + include: { scaleBar: true, legend: true, axes: false, selections: true }, + background: 'white', + }) + expect( + await within(dialog).findByText('Saved sob23-screenshot.png.'), + ).toBeInTheDocument() + }) + + it('asks before reading more than 512 MiB of tiles', async () => { + const draw = vi.fn().mockResolvedValue(new Blob()) + render( + , + ) + const dialog = open() + await within(dialog).findByText(/Reads 2 image tiles \(839 MB\)/) + + fireEvent.click(within(dialog).getByRole('button', { name: 'Save PNG' })) + expect(draw).not.toHaveBeenCalled() + expect(within(dialog).getByRole('alert')).toHaveTextContent( + 'This reads 839 MB of image tiles', + ) + + fireEvent.click(within(dialog).getByRole('button', { name: 'Read 839 MB and save' })) + await vi.waitFor(() => { + expect(draw).toHaveBeenCalledOnce() + }) + }) + + it('shows progress with Cancel, then Retry for a tile it could not read', async () => { + let fail: (error: Error) => void = () => undefined + let progress: NonNullable = () => undefined + const draw = vi.fn( + ( + _view: ScreenshotSnapshot, + _options: unknown, + _file: unknown, + run: DrawScreenshotOptions, + ) => + new Promise((_resolve, reject) => { + fail = reject + if (run.onProgress !== undefined) progress = run.onProgress + }), + ) + render() + const dialog = open() + + fireEvent.click(within(dialog).getByRole('button', { name: 'Save PNG' })) + await vi.waitFor(() => { + expect(draw).toHaveBeenCalled() + }) + act(() => { + progress({ stage: 'image', done: 1, total: 4 }) + }) + + expect(within(dialog).getByRole('status')).toHaveTextContent( + 'Reading image tiles · 25%', + ) + expect(within(dialog).getByRole('button', { name: 'Save PNG' })).toBeDisabled() + expect(within(dialog).getByRole('button', { name: 'Cancel' })).toBeEnabled() + + const { ScreenshotImageError } = await import('./screenshotImage') + await act(async () => { + fail(new ScreenshotImageError('DAPI', new Error('503'))) + await Promise.resolve() + }) + + expect(within(dialog).getByRole('alert')).toHaveTextContent( + 'The screenshot failed. A tile of DAPI could not be read: 503', + ) + expect(within(dialog).getByRole('button', { name: 'Retry' })).toBeInTheDocument() + }) + + it('says when the view has not drawn yet', () => { + render() + const dialog = open() + + expect(within(dialog).getByText(/The view has not drawn yet/)).toBeInTheDocument() + }) +}) diff --git a/src/features/screenshot/ScreenshotButton.tsx b/src/features/screenshot/ScreenshotButton.tsx new file mode 100644 index 00000000..58424ff7 --- /dev/null +++ b/src/features/screenshot/ScreenshotButton.tsx @@ -0,0 +1,409 @@ +import { useEffect, useState, useSyncExternalStore } from 'react' +import { + Button, + CameraIcon, + Checkbox, + NumberField, + Popover, + Segmented, +} from '../../components/ui' +import { formatBytes } from '../store-structure/storeStructureModel' +import type { ScreenshotModel } from './screenshotModel' +import type { ScreenshotBackground, ScreenshotInclude } from './screenshotOverlay' +import { + DEFAULT_SCREENSHOT_DPI, + DEFAULT_SCREENSHOT_SCALE, + formatUnitsPerPixel, + SCREENSHOT_ASK_BYTES, + SCREENSHOT_SCALES, + screenshotChannelRead, + screenshotFrame, + screenshotGrid, + screenshotNotes, + screenshotPixelSize, + screenshotPrintSize, + screenshotSizeLimitReason, + screenshotUnitsPerPixel, + type ScreenshotScale, +} from './screenshotPlan' +import type { ScreenshotSnapshot } from './screenshotRun' +import { screenshotProgressText } from './screenshotRunner' + +const TITLE = 'Save the spatial view as a high-resolution PNG' + +const BACKGROUNDS: readonly { + readonly value: ScreenshotBackground + readonly label: string + readonly title: string +}[] = [ + { value: 'canvas', label: 'Canvas', title: 'Black, as on screen' }, + { value: 'white', label: 'White', title: 'White, with white boxes and dark text' }, + { + value: 'transparent', + label: 'Transparent', + title: 'No background: the image and the cells over nothing', + }, +] + +const INCLUDE: readonly { + readonly key: keyof ScreenshotInclude + readonly label: string + readonly title: string +}[] = [ + { + key: 'scaleBar', + label: 'Scale bar', + title: 'Draw the scale bar at the bottom right', + }, + { key: 'legend', label: 'Legend', title: 'Draw the legend at the bottom left' }, + { key: 'axes', label: 'Axes', title: 'Draw the rulers along the top and left edges' }, + { + key: 'selections', + label: 'Selections', + title: 'Draw the outlines of the saved and active selections', + }, +] + +// Screenshot in the top bar (plan 27-D1), beside Share: a popover with the +// scale, what to include and the background, and Save PNG. A screenshot keeps +// running when the popover closes; the loading list shows it too. +export function ScreenshotButton({ + screenshot, + iconOnly, +}: { + readonly screenshot: ScreenshotModel + readonly iconOnly: boolean +}) { + return ( + + + {iconOnly ? null : Screenshot} + + } + triggerClassName={iconOnly ? 'ui-icon-button' : 'shell-screenshot-trigger'} + className="shell-screenshot" + > + + + ) +} + +// Mounted while the popover is open, so the view is read when it opens. +function ScreenshotPanel({ screenshot }: { readonly screenshot: ScreenshotModel }) { + const { runner } = screenshot + const state = useSyncExternalStore(runner.subscribe, runner.getState) + const [preview] = useState(() => runner.preview()) + const [scale, setScale] = useState(() => + preview === null ? DEFAULT_SCREENSHOT_SCALE : largestScaleWithin(preview), + ) + const [dpi, setDpi] = useState(DEFAULT_SCREENSHOT_DPI) + const [include, setInclude] = useState(screenshot.include) + const [background, setBackground] = useState('canvas') + const [askingToRead, setAskingToRead] = useState(false) + const read = useImageReadEstimate(preview, scale) + + if (preview === null) { + return ( +

+ The view has not drawn yet. Open the popover again once it has. +

+ ) + } + + const frame = screenshotFrame(preview.viewport) + const size = screenshotPixelSize(frame, scale) + const running = state.status === 'running' + const notes = screenshotNotes({ + cells: preview.cells, + expressionSampled: screenshot.expressionSampled, + transcriptsAsDensity: screenshot.transcriptsAsDensity, + loadingLabels: screenshot.loadingLabels, + }) + const needsAsk = read.bytes !== null && read.bytes > SCREENSHOT_ASK_BYTES + const save = () => { + if (needsAsk && !askingToRead) { + setAskingToRead(true) + return + } + setAskingToRead(false) + runner.start({ scale, dpi, include, background }, screenshot.file) + } + + return ( + <> +
+ Scale + { + const reason = screenshotSizeLimitReason(screenshotPixelSize(frame, option)) + return { + value: String(option) as `${ScreenshotScale}`, + label: `${option.toString()}×`, + title: + reason === null + ? `${option.toString()} times the size on screen` + : `${reason}: too large to draw`, + disabled: reason !== null, + } + })} + onChange={(value) => { + setScale(Number(value) as ScreenshotScale) + setAskingToRead(false) + }} + /> +
+

+ {`${size.width.toLocaleString()} × ${size.height.toLocaleString()} px · ${formatUnitsPerPixel( + screenshotUnitsPerPixel(preview.viewState.zoom, scale), + )} ${preview.unitLabel} per pixel · ${screenshotPrintSize(size, dpi)}`} +

+ { + setDpi(Math.round(value)) + }} + className="ui-field--inline" + /> +
+ Include + {INCLUDE.map((option) => ( + { + setInclude((current) => ({ ...current, [option.key]: checked })) + }} + /> + ))} +
+
+ Background + +
+ {read.tiles === 0 ? null : ( +

+ {`Reads ${read.tiles.toLocaleString()} image ${read.tiles === 1 ? 'tile' : 'tiles'}${ + read.bytes === null ? '' : ` (${formatBytes(read.bytes)})` + }.`} +

+ )} + {notes.length === 0 ? null : ( +
    + {notes.map((note) => ( +
  • {note}
  • + ))} +
+ )} + { + runner.cancel() + }} + onRetry={() => { + runner.retry() + }} + /> + {askingToRead && read.bytes !== null && !running ? ( +

+ {`This reads ${formatBytes(read.bytes)} of image tiles, which can take minutes on a slow host.`} +

+ ) : null} +
+ {askingToRead && !running ? ( + + ) : null} + +
+ + ) +} + +function ScreenshotStatus({ + state, + onCancel, + onRetry, +}: { + readonly state: ReturnType + readonly onCancel: () => void + readonly onRetry: () => void +}) { + if (state.status === 'running') { + const progress = state.progress + return ( +
+ + {screenshotProgressText(progress)} + +
+ ) + } + + if (state.status === 'error') { + return ( +
+

{`The screenshot failed. ${state.message}`}

+ {state.retryable ? ( + + ) : null} +
+ ) + } + + if (state.status === 'saved') { + return ( +

+ {`Saved ${state.fileName}.`} +

+ ) + } + + return null +} + +// D3: 2× to start, or the largest scale under the size limit below it. +function largestScaleWithin(preview: ScreenshotSnapshot): ScreenshotScale { + const frame = screenshotFrame(preview.viewport) + const fits = SCREENSHOT_SCALES.filter( + (scale) => + scale <= DEFAULT_SCREENSHOT_SCALE && + screenshotSizeLimitReason(screenshotPixelSize(frame, scale)) === null, + ) + return fits.at(-1) ?? 1 +} + +interface ImageReadEstimate { + // Reads of every tile of the frame, a tile under two of them counted twice. + readonly tiles: number + // The bytes of the image's tiles, where the file's tile index says. + readonly bytes: number | null +} + +// D4: the tiles the screenshot reads at a scale, and their size from the +// TIFF tile index where there is one. +function useImageReadEstimate( + preview: ScreenshotSnapshot | null, + scale: ScreenshotScale, +): ImageReadEstimate { + const channels = preview?.image.channels ?? [] + const reads = + preview === null + ? [] + : channels.map((channel) => { + const frame = screenshotFrame(preview.viewport) + return { + loader: channel.loader, + read: screenshotChannelRead( + channel.loader, + preview.viewState, + frame, + screenshotGrid(frame, scale), + scale, + ), + } + }) + const tiles = reads.reduce((count, { read }) => count + read.reads, 0) + const [bytes, setBytes] = useState<{ + readonly scale: ScreenshotScale + readonly bytes: number | null + } | null>(null) + + useEffect(() => { + if (preview === null) return + const controller = new AbortController() + const frame = screenshotFrame(preview.viewport) + const grid = screenshotGrid(frame, scale) + + void Promise.all( + preview.image.channels.map((channel) => { + const read = screenshotChannelRead( + channel.loader, + preview.viewState, + frame, + grid, + scale, + ) + return ( + channel.loader.tileReadBytes?.( + read.level, + read.frameTiles, + controller.signal, + ) ?? Promise.resolve(null) + ) + }), + ).then( + (sizes) => { + if (controller.signal.aborted) return + setBytes({ + scale, + bytes: + sizes.length === 0 || sizes.some((size) => size === null) + ? null + : sizes.reduce((total, size) => total + (size ?? 0), 0), + }) + }, + () => { + if (!controller.signal.aborted) setBytes({ scale, bytes: null }) + }, + ) + + return () => { + controller.abort() + } + }, [preview, scale]) + + return { tiles, bytes: bytes?.scale === scale ? bytes.bytes : null } +} diff --git a/src/features/screenshot/pngChunks.test.ts b/src/features/screenshot/pngChunks.test.ts new file mode 100644 index 00000000..b7ab943c --- /dev/null +++ b/src/features/screenshot/pngChunks.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from 'vitest' +import { + crc32, + insertPngChunks, + pngPhysChunk, + pngTextChunk, + pngTextEntries, + readPngChunks, +} from './pngChunks' + +// A 1×1 PNG: signature, IHDR, IDAT and IEND. +const ONE_PIXEL_PNG = Uint8Array.from( + atob( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', + ), + (char) => char.charCodeAt(0), +) + +describe('PNG chunks (plan 27-D11)', () => { + it('computes PNG’s CRC-32', () => { + expect(crc32(new TextEncoder().encode('IEND'))).toBe(0xae426082) + }) + + it('inserts chunks after IHDR, each with a good CRC', () => { + const png = insertPngChunks(ONE_PIXEL_PNG, [ + pngPhysChunk(300), + pngTextChunk('Software', 'Spatial Omics Explorer'), + ]) + const chunks = readPngChunks(png) + + expect(chunks.map((chunk) => chunk.type)).toEqual([ + 'IHDR', + 'pHYs', + 'tEXt', + 'IDAT', + 'IEND', + ]) + expect(png.length).toBe(ONE_PIXEL_PNG.length + 21 + 12 + 'Software'.length + 1 + 22) + }) + + it('writes dpi as pixels per metre', () => { + const data = pngPhysChunk(300).data + const view = new DataView(data.buffer) + + expect(view.getUint32(0)).toBe(11811) + expect(view.getUint32(4)).toBe(11811) + expect(data[8]).toBe(1) + }) + + it('reads text back, in tEXt for Latin-1 and iTXt otherwise', () => { + const png = insertPngChunks(ONE_PIXEL_PNG, [ + pngTextChunk('Description', 'x 0 to 10 µm; 0.5 µm per pixel'), + pngTextChunk('Source', 'https://example.test/腦.h5ad'), + ]) + + expect(readPngChunks(png).map((chunk) => chunk.type)).toContain('iTXt') + expect(pngTextEntries(png)).toEqual({ + Description: 'x 0 to 10 µm; 0.5 µm per pixel', + Source: 'https://example.test/腦.h5ad', + }) + }) + + it('refuses a file that is not a PNG', () => { + expect(() => insertPngChunks(new Uint8Array(16), [])).toThrow(/Not a PNG/) + }) + + it('finds a damaged chunk', () => { + const png = insertPngChunks(ONE_PIXEL_PNG, [pngTextChunk('Software', 'x')]) + // The first byte of the text chunk's data, after the signature and IHDR. + const first = 8 + 25 + 8 + png[first] = (png[first] ?? 0) ^ 1 + + expect(() => readPngChunks(png)).toThrow(/CRC/) + }) +}) diff --git a/src/features/screenshot/pngChunks.ts b/src/features/screenshot/pngChunks.ts new file mode 100644 index 00000000..32fb6766 --- /dev/null +++ b/src/features/screenshot/pngChunks.ts @@ -0,0 +1,204 @@ +// PNG chunks a screenshot adds to what the canvas writes (plan 27-D11): its +// dpi in `pHYs`, and where it came from in text chunks with the PNG +// specification's keywords. + +export interface PngChunk { + // Four ASCII letters, such as 'tEXt'. + readonly type: string + readonly data: Uint8Array +} + +const PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10] +const METRES_PER_INCH = 0.0254 + +// Chunks go after IHDR, which the specification puts first; pHYs must come +// before the image data, and text chunks may come anywhere. +export function insertPngChunks( + png: Uint8Array, + chunks: readonly PngChunk[], +): Uint8Array { + if (!hasPngSignature(png)) throw new Error('Not a PNG file.') + + const ihdrLength = readUint32(png, 8) + const ihdrEnd = 8 + 12 + ihdrLength + if (chunkType(png, 8) !== 'IHDR' || ihdrEnd > png.length) { + throw new Error('The PNG file has no header chunk.') + } + + const encoded = chunks.map(encodeChunk) + const out = new Uint8Array( + png.length + encoded.reduce((total, chunk) => total + chunk.length, 0), + ) + out.set(png.subarray(0, ihdrEnd), 0) + let offset = ihdrEnd + for (const chunk of encoded) { + out.set(chunk, offset) + offset += chunk.length + } + out.set(png.subarray(ihdrEnd), offset) + return out +} + +// Pixels per metre on both axes, which is how PNG records dpi. +export function pngPhysChunk(dpi: number): PngChunk { + const perMetre = Math.round(dpi / METRES_PER_INCH) + const data = new Uint8Array(9) + writeUint32(data, 0, perMetre) + writeUint32(data, 4, perMetre) + data[8] = 1 + return { type: 'pHYs', data } +} + +// A Latin-1 `tEXt` chunk, or an `iTXt` (UTF-8) one when the text has other +// characters. +export function pngTextChunk(keyword: string, text: string): PngChunk { + const latin1 = isLatin1(text) + const key = latin1Bytes(keyword) + + if (latin1) { + return { type: 'tEXt', data: concat([key, [0], latin1Bytes(text)]) } + } + + // Keyword, null, no compression (flag and method), empty language tag and + // translated keyword, each ended by a null, then the text. + return { + type: 'iTXt', + data: concat([key, [0, 0, 0, 0, 0], new TextEncoder().encode(text)]), + } +} + +export interface ReadPngChunk { + readonly type: string + readonly data: Uint8Array +} + +// Every chunk of a PNG, in order; for tests and checks. +export function readPngChunks(png: Uint8Array): readonly ReadPngChunk[] { + if (!hasPngSignature(png)) throw new Error('Not a PNG file.') + + const chunks: ReadPngChunk[] = [] + let offset = 8 + + while (offset + 12 <= png.length) { + const length = readUint32(png, offset) + const type = chunkType(png, offset) + const data = png.subarray(offset + 8, offset + 8 + length) + const crc = readUint32(png, offset + 8 + length) + if (crc !== crc32(png.subarray(offset + 4, offset + 8 + length))) { + throw new Error(`The PNG's ${type} chunk fails its CRC.`) + } + chunks.push({ type, data }) + offset += 12 + length + if (type === 'IEND') break + } + + return chunks +} + +// A text chunk's keyword and text, for tests and checks. +export function pngTextEntries(png: Uint8Array): Readonly> { + const entries: Record = {} + + for (const chunk of readPngChunks(png)) { + const nul = chunk.data.indexOf(0) + if (nul < 0) continue + const keyword = String.fromCharCode(...chunk.data.subarray(0, nul)) + + if (chunk.type === 'tEXt') { + entries[keyword] = String.fromCharCode(...chunk.data.subarray(nul + 1)) + } else if (chunk.type === 'iTXt') { + // Skip the compression flag and method, then the language tag and + // translated keyword, each ended by a null. + let offset = nul + 3 + for (let ended = 0; ended < 2; ended += 1) { + offset = chunk.data.indexOf(0, offset) + 1 + } + entries[keyword] = new TextDecoder().decode(chunk.data.subarray(offset)) + } + } + + return entries +} + +function encodeChunk(chunk: PngChunk): Uint8Array { + if (!/^[A-Za-z]{4}$/.test(chunk.type)) + throw new Error(`Bad PNG chunk type ${chunk.type}`) + + const out = new Uint8Array(12 + chunk.data.length) + writeUint32(out, 0, chunk.data.length) + for (let index = 0; index < 4; index += 1) { + out[4 + index] = chunk.type.charCodeAt(index) + } + out.set(chunk.data, 8) + writeUint32(out, 8 + chunk.data.length, crc32(out.subarray(4, 8 + chunk.data.length))) + return out +} + +let crcTable: Uint32Array | null = null + +// CRC-32 as PNG computes it, over a chunk's type and data. +export function crc32(bytes: Uint8Array): number { + crcTable ??= makeCrcTable() + let crc = 0xffffffff + + for (const byte of bytes) { + crc = (crcTable[(crc ^ byte) & 0xff] ?? 0) ^ (crc >>> 8) + } + + return (crc ^ 0xffffffff) >>> 0 +} + +function makeCrcTable(): Uint32Array { + const table = new Uint32Array(256) + + for (let n = 0; n < 256; n += 1) { + let c = n + for (let k = 0; k < 8; k += 1) { + c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1 + } + table[n] = c >>> 0 + } + + return table +} + +function hasPngSignature(png: Uint8Array): boolean { + return PNG_SIGNATURE.every((byte, index) => png[index] === byte) +} + +function chunkType(png: Uint8Array, offset: number): string { + return String.fromCharCode(...png.subarray(offset + 4, offset + 8)) +} + +function readUint32(bytes: Uint8Array, offset: number): number { + return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(offset) +} + +function writeUint32(bytes: Uint8Array, offset: number, value: number): void { + new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).setUint32(offset, value) +} + +function isLatin1(text: string): boolean { + for (let index = 0; index < text.length; index += 1) { + if (text.charCodeAt(index) > 0xff) return false + } + return true +} + +function latin1Bytes(text: string): Uint8Array { + const bytes = new Uint8Array(text.length) + for (let index = 0; index < text.length; index += 1) { + bytes[index] = text.charCodeAt(index) & 0xff + } + return bytes +} + +function concat(parts: readonly (Uint8Array | readonly number[])[]): Uint8Array { + const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0)) + let offset = 0 + for (const part of parts) { + out.set(part, offset) + offset += part.length + } + return out +} diff --git a/src/features/screenshot/screenshotDeck.test.ts b/src/features/screenshot/screenshotDeck.test.ts new file mode 100644 index 00000000..e9fe329d --- /dev/null +++ b/src/features/screenshot/screenshotDeck.test.ts @@ -0,0 +1,259 @@ +import { ScatterplotLayer } from '@deck.gl/layers' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { OverviewViewState } from '../../rendering/deckLayerTypes' +import { + ScreenshotDeckError, + ScreenshotDeckRenderer, + screenshotLayerOptions, + unpickableLayers, + type ScreenshotDeckProps, +} from './screenshotDeck' + +const viewState: OverviewViewState = { + target: [0, 0, 0], + zoom: 0, + minZoom: -10, + maxZoom: 10, +} + +// A Deck that loads when told, records its props, and draws into a canvas +// whose WebGL drawing buffer is the size asked for unless told otherwise. +function fakeDeck(options: { readonly bufferWidth?: number } = {}) { + const decks: { + props: ScreenshotDeckProps + setProps: ReturnType + redraw: ReturnType + finalize: ReturnType + animationLoop: { redraw: ReturnType } + canvas: HTMLCanvasElement + load: () => void + fail: (error: Error) => void + lose: () => void + }[] = [] + const createDeck = (props: ScreenshotDeckProps) => { + const canvas = document.createElement('canvas') + props.parent?.append(canvas) + const device = { isLost: false } + const width = (props.width as number) * (props.useDevicePixels as number) + const height = (props.height as number) * (props.useDevicePixels as number) + vi.spyOn(canvas, 'getContext').mockReturnValue({ + drawingBufferWidth: options.bufferWidth ?? width, + drawingBufferHeight: height, + } as unknown as RenderingContext) + const deck = { + props, + setProps: vi.fn(), + redraw: vi.fn(), + finalize: vi.fn(), + animationLoop: { redraw: vi.fn() }, + canvas, + load: () => { + props.onDeviceInitialized?.(device as never) + props.onLoad?.() + }, + fail: (error: Error) => { + props.onError?.(error) + }, + lose: () => { + device.isLost = true + }, + getCanvas: () => canvas, + } + decks.push(deck) + return deck + } + + return { decks, createDeck } +} + +function target() { + const drawImage = vi.fn() + return { context: { drawImage } as unknown as CanvasRenderingContext2D, drawImage } +} + +afterEach(() => { + document.body.replaceChildren() +}) + +describe('screenshot deck (plan 27, task D)', () => { + it('draws every loaded cell and nothing pickable (D5)', () => { + const packing = { + geometry: {} as never, + colors: new Uint8Array(4), + filterValues: new Float32Array(1), + sampleFraction: 0.18, + } + const options = screenshotLayerOptions({ + cellPointPickable: true, + cellBoundaryPickable: true, + cellPointPacking: packing, + transcriptOpacity: 0.5, + }) + + expect(options).toEqual({ + cellPointPickable: false, + cellBoundaryPickable: false, + cellPointPacking: { ...packing, sampleFraction: 1 }, + transcriptOpacity: 0.5, + }) + }) + + it('clones every layer without picking', () => { + const layers = unpickableLayers([ + new ScatterplotLayer({ id: 'a', data: [], pickable: true }), + [new ScatterplotLayer({ id: 'b', data: [], pickable: true })], + null, + ]) + const flat = layers.flat() as ScatterplotLayer[] + + expect(flat[0]?.props.pickable).toBe(false) + expect(flat[1]?.props.pickable).toBe(false) + expect(flat[2]).toBeNull() + }) + + it('draws at the screenshot’s pixel density in a hidden canvas in the page', async () => { + const { decks, createDeck } = fakeDeck() + const creating = ScreenshotDeckRenderer.create({ + layers: [], + tileWidth: 512, + tileHeight: 256, + scale: 4, + viewState, + signal: new AbortController().signal, + createDeck, + }) + const deck = decks[0] + deck?.load() + const renderer = await creating + const host = document.querySelector('.screenshot-deck-host') + + expect(deck?.props).toMatchObject({ + width: 512, + height: 256, + useDevicePixels: 4, + controller: false, + }) + expect(host?.style.visibility).toBe('hidden') + expect(host?.getAttribute('aria-hidden')).toBe('true') + expect(deck?.setProps).toHaveBeenCalledWith({ useDevicePixels: 4 }) + // The layers given before the device was ready are applied at once, not + // in an animation frame a hidden tab never has. + expect(deck?.animationLoop.redraw).toHaveBeenCalledOnce() + + const { context, drawImage } = target() + const tileView = { ...viewState, target: [10, 20, 0] as [number, number, number] } + renderer.drawTile(context, tileView, { width: 300, height: 256 }, { x: 2048, y: 0 }) + + expect(deck?.setProps).toHaveBeenCalledWith({ viewState: tileView }) + expect(deck?.redraw).toHaveBeenCalledWith('screenshot') + expect(drawImage).toHaveBeenCalledWith( + deck?.canvas, + 0, + 0, + 1200, + 1024, + 2048, + 0, + 1200, + 1024, + ) + }) + + it('leaves the page and finalizes its Deck, so it loses its context', async () => { + const { decks, createDeck } = fakeDeck() + const creating = ScreenshotDeckRenderer.create({ + layers: [], + tileWidth: 100, + tileHeight: 100, + scale: 2, + viewState, + signal: new AbortController().signal, + createDeck, + }) + decks[0]?.load() + const renderer = await creating + const canvas = decks[0]?.canvas + + renderer.destroy() + + expect(document.querySelector('.screenshot-deck-host')).toBeNull() + expect(canvas?.isConnected).toBe(false) + expect(decks[0]?.finalize).toHaveBeenCalledOnce() + }) + + it('fails rather than stretch a drawing buffer the GPU shrank (D9)', async () => { + const { decks, createDeck } = fakeDeck({ bufferWidth: 2048 }) + const creating = ScreenshotDeckRenderer.create({ + layers: [], + tileWidth: 1024, + tileHeight: 1024, + scale: 4, + viewState, + signal: new AbortController().signal, + createDeck, + }) + decks[0]?.load() + const renderer = await creating + const { context, drawImage } = target() + + expect(() => { + renderer.drawTile(context, viewState, { width: 1024, height: 1024 }, { x: 0, y: 0 }) + }).toThrow(ScreenshotDeckError) + expect(drawImage).not.toHaveBeenCalled() + }) + + it('fails when its context is lost', async () => { + const { decks, createDeck } = fakeDeck() + const creating = ScreenshotDeckRenderer.create({ + layers: [], + tileWidth: 100, + tileHeight: 100, + scale: 1, + viewState, + signal: new AbortController().signal, + createDeck, + }) + decks[0]?.load() + const renderer = await creating + decks[0]?.lose() + const { context } = target() + + expect(() => { + renderer.drawTile(context, viewState, { width: 100, height: 100 }, { x: 0, y: 0 }) + }).toThrow(/interrupted/) + }) + + it('cleans up when cancelled or when the Deck fails before it loads', async () => { + const cancelled = fakeDeck() + const controller = new AbortController() + const creating = ScreenshotDeckRenderer.create({ + layers: [], + tileWidth: 100, + tileHeight: 100, + scale: 1, + viewState, + signal: controller.signal, + createDeck: cancelled.createDeck, + }) + controller.abort() + + await expect(creating).rejects.toThrow(/abort/i) + expect(cancelled.decks[0]?.finalize).toHaveBeenCalledOnce() + expect(document.querySelector('.screenshot-deck-host')).toBeNull() + + const failing = fakeDeck() + const failed = ScreenshotDeckRenderer.create({ + layers: [], + tileWidth: 100, + tileHeight: 100, + scale: 1, + viewState, + signal: new AbortController().signal, + createDeck: failing.createDeck, + }) + failing.decks[0]?.fail(new Error('WebGL2 is not available')) + + await expect(failed).rejects.toThrow('WebGL2 is not available') + expect(failing.decks[0]?.finalize).toHaveBeenCalledOnce() + }) +}) diff --git a/src/features/screenshot/screenshotDeck.ts b/src/features/screenshot/screenshotDeck.ts new file mode 100644 index 00000000..96b15373 --- /dev/null +++ b/src/features/screenshot/screenshotDeck.ts @@ -0,0 +1,229 @@ +import type { DeckProps, LayersList, OrthographicView } from '@deck.gl/core' +import { ReleasingDeck } from '../../components/releasingDeck' +import { spatialOverviewView } from '../../rendering/deckLayers' +import type { + OverviewLayerOptions, + OverviewViewState, +} from '../../rendering/deckLayerTypes' +import { abortError } from '../../utils/abort' +import type { ScreenshotScale } from './screenshotPlan' + +// The cells, outlines, transcripts and annotations of a screenshot (plan 27, +// task D), drawn by a deck.gl Deck of its own, one tile of the frame at a +// time at the screenshot's pixel density. Its canvas sits in the page, +// hidden, only so that its size is measured; the live view is never resized +// or read. Each tile is copied out in the same task it is drawn in, before +// the browser can clear the drawing buffer. The Deck loses its WebGL context +// as soon as the screenshot ends, so it holds one of Chromium's 16 only +// while it runs. + +// D5: every loaded cell, not the render cap's sample, and nothing pickable. +export function screenshotLayerOptions( + options: OverviewLayerOptions, +): OverviewLayerOptions { + return { + ...options, + cellPointPickable: false, + cellBoundaryPickable: false, + ...(options.cellPointPacking === undefined + ? {} + : { cellPointPacking: { ...options.cellPointPacking, sampleFraction: 1 } }), + } +} + +// The layers' other kinds are pickable for hovers and clicks, which an +// off-screen Deck never gets. +export function unpickableLayers(layers: LayersList): LayersList { + return layers.map((layer) => + Array.isArray(layer) + ? unpickableLayers(layer) + : layer + ? layer.clone({ pickable: false }) + : layer, + ) +} + +// What one of deck.gl's animation frames does, now: apply new layers, +// update the canvas size and draw if anything changed. +function runAnimationFrame(deck: ScreenshotDeck): void { + const { animationLoop } = deck as { animationLoop?: { redraw(): unknown } | null } + animationLoop?.redraw() +} + +export class ScreenshotDeckError extends Error { + constructor(message: string) { + super(message) + this.name = 'ScreenshotDeckError' + } +} + +export type ScreenshotDeckProps = DeckProps + +// What the renderer needs of a Deck; tests give a fake. +export interface ScreenshotDeck { + setProps(props: Partial): void + redraw(reason?: string): void + getCanvas(): HTMLCanvasElement | null + finalize(): void +} + +export type CreateScreenshotDeck = (props: ScreenshotDeckProps) => ScreenshotDeck + +export interface ScreenshotDeckOptions { + readonly layers: LayersList + // The size every tile is drawn at, in CSS pixels. + readonly tileWidth: number + readonly tileHeight: number + readonly scale: ScreenshotScale + readonly viewState: OverviewViewState + readonly signal: AbortSignal + readonly createDeck?: CreateScreenshotDeck +} + +interface DeckDevice { + readonly isLost: boolean +} + +export class ScreenshotDeckRenderer { + private device: DeckDevice | null = null + private failure: Error | null = null + + private constructor( + private readonly host: HTMLElement, + private deck: ScreenshotDeck | null, + private readonly options: ScreenshotDeckOptions, + ) {} + + static async create(options: ScreenshotDeckOptions): Promise { + options.signal.throwIfAborted() + const host = document.createElement('div') + host.className = 'screenshot-deck-host' + host.setAttribute('aria-hidden', 'true') + Object.assign(host.style, { + position: 'fixed', + left: '0', + top: '0', + width: `${options.tileWidth.toString()}px`, + height: `${options.tileHeight.toString()}px`, + overflow: 'hidden', + visibility: 'hidden', + pointerEvents: 'none', + zIndex: '-1', + }) + document.body.append(host) + + const createDeck = + options.createDeck ?? ((props) => new ReleasingDeck(props)) + let loaded!: () => void + let failed!: (error: Error) => void + const ready = new Promise((resolve, reject) => { + loaded = resolve + failed = reject + }) + const renderer = new ScreenshotDeckRenderer(host, null, options) + const onAbort = () => { + failed(abortError(options.signal)) + } + options.signal.addEventListener('abort', onAbort, { once: true }) + + try { + renderer.deck = createDeck({ + parent: host, + width: options.tileWidth, + height: options.tileHeight, + useDevicePixels: options.scale, + views: spatialOverviewView, + viewState: options.viewState, + controller: false, + layers: options.layers, + style: { pointerEvents: 'none' }, + onDeviceInitialized: (device) => { + renderer.device = device + }, + onLoad: () => { + loaded() + }, + onError: (error) => { + renderer.failure ??= error + failed(error) + }, + }) + await ready + // A numeric useDevicePixels sizes the drawing buffer now, rather than + // when the resize observer next reports. + renderer.deck?.setProps({ useDevicePixels: options.scale }) + // deck.gl takes layers given before its device was ready only in its + // next animation frame, and a hidden tab has none: without this the + // first tiles came out with no cells, and every tile in a hidden tab. + if (renderer.deck !== null) runAnimationFrame(renderer.deck) + return renderer + } catch (error) { + renderer.destroy() + throw error + } finally { + options.signal.removeEventListener('abort', onAbort) + } + } + + // Draws the view of one tile and copies its top-left `width` × `height` + // CSS pixels to (x, y) of the target, in the target's pixels. + drawTile( + target: CanvasRenderingContext2D, + viewState: OverviewViewState, + source: { readonly width: number; readonly height: number }, + destination: { readonly x: number; readonly y: number }, + ): void { + const deck = this.deck + const canvas = deck?.getCanvas() ?? null + if (deck === null || canvas === null) + throw new ScreenshotDeckError('The cells could not be drawn.') + + deck.setProps({ viewState }) + deck.redraw('screenshot') + this.throwIfLost() + + const { scale, tileWidth, tileHeight } = this.options + const gl = canvas.getContext('webgl2') + const width = tileWidth * scale + const height = tileHeight * scale + // WebGL shrinks a drawing buffer past its limit without a word; a tile + // drawn small would be stretched (27-D9). + if ( + gl !== null && + (gl.drawingBufferWidth !== width || gl.drawingBufferHeight !== height) + ) { + throw new ScreenshotDeckError( + `The GPU drew the cells at ${gl.drawingBufferWidth.toString()} × ${gl.drawingBufferHeight.toString()} px, not ${width.toString()} × ${height.toString()}.`, + ) + } + + target.drawImage( + canvas, + 0, + 0, + source.width * scale, + source.height * scale, + destination.x, + destination.y, + source.width * scale, + source.height * scale, + ) + } + + // The Deck is finalized once its canvas has left the page, so + // ReleasingDeck loses its context. + destroy(): void { + this.host.remove() + const deck = this.deck + this.deck = null + deck?.finalize() + } + + private throwIfLost(): void { + if (this.device?.isLost === true || this.failure !== null) { + throw new ScreenshotDeckError( + 'Drawing the cells was interrupted (the GPU was reset, or too many tabs are using it).', + ) + } + } +} diff --git a/src/features/screenshot/screenshotImage.test.ts b/src/features/screenshot/screenshotImage.test.ts new file mode 100644 index 00000000..6ee3fd8e --- /dev/null +++ b/src/features/screenshot/screenshotImage.test.ts @@ -0,0 +1,354 @@ +import { describe, expect, it, vi } from 'vitest' +import { imagePixels, micrometers, type BBox, type TileIndex } from '../../data/coords' +import type { ImagePyramidLoader } from '../../data/imagePyramid' +import type { MorphologyCanvasChannel } from '../../components/MorphologyCanvas' +import { MorphologyTileStore } from '../../rendering/morphologyTileStore' +import type { OverviewViewState } from '../../rendering/deckLayerTypes' +import { TILE_RETRY_DELAYS_MS } from '../../tiff/tileCache' +import { ScreenshotImageComposer, ScreenshotImageError } from './screenshotImage' + +// A two-level pyramid of 100 µm tiles at level 0 and 200 µm tiles at level 1, +// 4 × 4 tiles at level 0, with its origin at `origin`. +function fakeLoader( + options: { + readonly origin?: { readonly x: number; readonly y: number } + readonly placement?: ImagePyramidLoader['placement'] + readonly failing?: (level: number, col: number, row: number) => boolean + readonly name?: string + } = {}, +) { + const origin = options.origin ?? { x: 0, y: 0 } + const reads: string[] = [] + const size = (level: number) => 100 * 2 ** level + const loader = { + url: `https://example.test/${options.name ?? 'dapi'}.ome.tif`, + channels: [{ id: options.name ?? 'dapi', name: options.name ?? 'DAPI' }], + ...(options.placement === undefined ? {} : { placement: options.placement }), + bestLevel: (deckScale: number) => (deckScale >= 1 ? 0 : 1), + tilesForBbox: (level: number, bbox: BBox): readonly TileIndex[] => { + const tiles: TileIndex[] = [] + const step = size(level) + const count = 4 / 2 ** level + for (let row = 0; row < count; row += 1) { + for (let col = 0; col < count; col += 1) { + const minX = origin.x + col * step + const minY = origin.y + row * step + if ( + minX < bbox.maxX && + minX + step > bbox.minX && + minY < bbox.maxY && + minY + step > bbox.minY + ) { + tiles.push({ col, row }) + } + } + } + return tiles + }, + tileBounds: (level: number, col: number, row: number): BBox => ({ + minX: micrometers(origin.x + col * size(level)), + maxX: micrometers(origin.x + (col + 1) * size(level)), + minY: micrometers(origin.y + row * size(level)), + maxY: micrometers(origin.y + (row + 1) * size(level)), + }), + tileSourceSize: () => ({ width: imagePixels(100), height: imagePixels(100) }), + loadTile: vi.fn((level: number, col: number, row: number) => { + const key = `${level.toString()}:${col.toString()}:${row.toString()}` + reads.push(key) + if (options.failing?.(level, col, row) === true) { + return Promise.reject(new Error(`503 for ${key}`)) + } + return Promise.resolve({ + bitmap: { key, close: vi.fn() } as unknown as ImageBitmap, + width: 100, + height: 100, + lo: 0, + hi: 255, + }) + }), + } + + return { loader: loader as unknown as ImagePyramidLoader, reads } +} + +function channel( + loader: ImagePyramidLoader, + color: readonly [number, number, number] = [0, 0, 255], +): MorphologyCanvasChannel { + return { + id: loader.channels[0]?.id ?? 'dapi', + loader, + enabled: true, + color, + contrast: { lo: 0, hi: 255 }, + } +} + +// The image drawn by a context: each drawImage's bitmap, operation and +// target rect. +function recordingContext() { + const draws: { + readonly key: string + readonly operation: string + readonly alpha: number + readonly target: readonly number[] + readonly transformed: boolean + }[] = [] + let transformed = false + const context = { + globalAlpha: 1, + globalCompositeOperation: 'source-over', + imageSmoothingQuality: 'low', + setTransform: vi.fn(), + clearRect: vi.fn(), + save: vi.fn(() => { + transformed = true + }), + restore: vi.fn(() => { + transformed = false + }), + translate: vi.fn(), + transform: vi.fn(), + drawImage: vi.fn(function ( + this: { globalCompositeOperation: string; globalAlpha: number }, + image: { key?: string }, + ...args: number[] + ) { + draws.push({ + key: image.key ?? 'flat', + operation: this.globalCompositeOperation, + alpha: this.globalAlpha, + target: args.slice(-4), + transformed, + }) + }), + } + + return { context: context as unknown as CanvasRenderingContext2D, draws } +} + +// The frame is 200 × 100 CSS px at zoom 0 over x 0–200, y 0–100 µm. +const viewState: OverviewViewState = { + target: [100, -50, 0], + zoom: 0, + minZoom: -10, + maxZoom: 10, +} +const frame = { width: 200, height: 100 } +const whole = { x: 0, y: 0, width: 200, height: 100 } + +function composer( + channels: readonly MorphologyCanvasChannel[], + options: Partial[1]> = {}, +) { + return new ScreenshotImageComposer( + { channels, flatImage: null, opacity: 1 }, + { + viewState, + frame, + scale: 2, + maxConcurrentRequests: 2, + signal: new AbortController().signal, + waitUntil: () => Promise.resolve(), + ...options, + }, + ) +} + +describe('screenshot image (plan 27, task C)', () => { + it('reads each channel at the level its pixel size needs, and adds channels', async () => { + const dapi = fakeLoader() + const cd3 = fakeLoader({ name: 'cd3' }) + const { context, draws } = recordingContext() + const image = composer([channel(dapi.loader), channel(cd3.loader, [255, 0, 0])], { + scale: 1, + viewState: { ...viewState, zoom: -1 }, + }) + + expect(image.tileCount(whole)).toBe(2 + 2) + await image.drawTile(context, whole) + + // Zoom −1 at 1× reads level 1; the frame spans x 0–400, y 0–200 µm. + expect(dapi.reads.sort()).toEqual(['1:0:0', '1:1:0']) + expect(cd3.reads.sort()).toEqual(['1:0:0', '1:1:0']) + expect(new Set(draws.map((draw) => draw.operation))).toEqual(new Set(['lighter'])) + }) + + it('reads the finer level at a larger scale (D4)', async () => { + const dapi = fakeLoader() + const { context, draws } = recordingContext() + const image = composer([channel(dapi.loader)], { + scale: 2, + viewState: { ...viewState, target: [200, -100, 0], zoom: -1 }, + }) + + await image.drawTile(context, whole) + + expect(dapi.reads.every((key) => key.startsWith('0:'))).toBe(true) + // At 2× the frame, x 0–400 and y 0–200 µm, is 400 × 200 PNG pixels: one + // per µm, on 4 × 2 tiles of 100. + expect( + draws.map((draw) => draw.target[0]).sort((a, b) => (a ?? 0) - (b ?? 0)), + ).toEqual([0, 0, 100, 100, 200, 200, 300, 300]) + expect(draws.every((draw) => draw.target[2] === 100 && draw.target[3] === 100)).toBe( + true, + ) + }) + + it('draws a tile of the frame at its own place', async () => { + const dapi = fakeLoader() + const { context, draws } = recordingContext() + const image = composer([channel(dapi.loader)], { scale: 2 }) + + // The right half of the frame, x 100–200 µm, 200 PNG pixels wide. + await image.drawTile(context, { x: 100, y: 0, width: 100, height: 100 }) + + expect(dapi.reads.sort()).toEqual(['0:1:0']) + expect(draws[0]?.target).toEqual([0, 0, 200, 200]) + }) + + it('places an image whose origin is not the data origin (MERSCOPE)', async () => { + const dapi = fakeLoader({ origin: { x: 150, y: 0 } }) + const { context, draws } = recordingContext() + const image = composer([channel(dapi.loader)], { scale: 1 }) + + await image.drawTile(context, whole) + + expect(dapi.reads).toEqual(['0:0:0']) + expect(draws[0]?.target).toEqual([150, 0, 100, 100]) + }) + + it('turns a flipped image as the canvas does', async () => { + const dapi = fakeLoader({ + placement: { a: 1, b: 0, c: micrometers(0), d: 0, e: -1, f: micrometers(100) }, + }) + const { context, draws } = recordingContext() + const image = composer([channel(dapi.loader)], { scale: 1 }) + + await image.drawTile(context, whole) + + expect(draws.length).toBeGreaterThan(0) + expect(draws.every((draw) => draw.transformed)).toBe(true) + }) + + it('draws a flat image (Visium) over the frame', async () => { + const { context, draws } = recordingContext() + const image = new ScreenshotImageComposer( + { + channels: [], + flatImage: { + url: 'https://example.test/hires.png', + scaleFactor: 0.5, + micrometersPerPixel: 1, + }, + opacity: 0.6, + }, + { + viewState, + frame, + scale: 2, + maxConcurrentRequests: 2, + signal: new AbortController().signal, + loadFlatImage: () => + Promise.resolve({ image: {} as CanvasImageSource, naturalSize: [100, 50] }), + }, + ) + + await image.drawTile(context, whole) + + // 100 px at 0.5 of full resolution: 200 µm, 400 PNG pixels at 2×. + expect(draws).toEqual([ + expect.objectContaining({ key: 'flat', target: [0, 0, 400, 200] }), + ]) + }) + + it('reads a failed tile again after each delay, then fails naming the channel', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + try { + const dapi = fakeLoader({ failing: (_level, col) => col === 1 }) + const waits: number[] = [] + const { context } = recordingContext() + const start = Date.now() + const image = composer([channel(dapi.loader)], { + scale: 1, + waitUntil: (time) => { + waits.push(time - start) + vi.setSystemTime(time) + return Promise.resolve() + }, + }) + + const drawing = image.drawTile(context, whole) + await expect(drawing).rejects.toBeInstanceOf(ScreenshotImageError) + await expect(drawing).rejects.toThrow( + /A tile of DAPI could not be read: 503 for 0:1:0/, + ) + expect(dapi.reads.filter((key) => key === '0:1:0')).toHaveLength( + 1 + TILE_RETRY_DELAYS_MS.length, + ) + expect(waits).toEqual([1_000, 3_000, 7_000]) + } finally { + vi.useRealTimers() + } + }) + + it('reads a spent tile again on Retry, with new caches', async () => { + let failing = true + const dapi = fakeLoader({ failing: (_level, col) => failing && col === 1 }) + const { context } = recordingContext() + + await expect( + composer([channel(dapi.loader)], { scale: 1 }).drawTile(context, whole), + ).rejects.toBeInstanceOf(ScreenshotImageError) + + failing = false + const before = dapi.reads.length + await composer([channel(dapi.loader)], { scale: 1 }).drawTile(context, whole) + + expect(dapi.reads.slice(before).sort()).toEqual(['0:0:0', '0:1:0']) + }) + + it('leaves the canvas’s tile caches as they were', async () => { + const dapi = fakeLoader() + const store = new MorphologyTileStore() + const [held] = store.use('canvas', [ + { + key: 'dapi', + cacheOptions: () => ({ maxTiles: 4, displayWindow: { lo: 0, hi: 255 } }), + }, + ]) + await held?.cache.request(dapi.loader, 0, 0, 0) + const before = held?.cache.readyTiles({ + minX: micrometers(-1e6), + maxX: micrometers(1e6), + minY: micrometers(-1e6), + maxY: micrometers(1e6), + }) + const { context } = recordingContext() + + const image = composer([channel(dapi.loader)], { scale: 8 }) + await image.drawTile(context, whole) + image.dispose() + + expect( + held?.cache.readyTiles({ + minX: micrometers(-1e6), + maxX: micrometers(1e6), + minY: micrometers(-1e6), + maxY: micrometers(1e6), + }), + ).toEqual(before) + }) + + it('stops reading when cancelled', async () => { + const dapi = fakeLoader() + const controller = new AbortController() + const { context } = recordingContext() + const image = composer([channel(dapi.loader)], { signal: controller.signal }) + + controller.abort() + + await expect(image.drawTile(context, whole)).rejects.toThrow(/abort/i) + expect(dapi.reads).toEqual([]) + }) +}) diff --git a/src/features/screenshot/screenshotImage.ts b/src/features/screenshot/screenshotImage.ts new file mode 100644 index 00000000..492b92d1 --- /dev/null +++ b/src/features/screenshot/screenshotImage.ts @@ -0,0 +1,338 @@ +import type { TileIndex } from '../../data/coords' +import type { ImagePyramidLoader } from '../../data/imagePyramid' +import type { + FlatMorphologyCanvasImage, + MorphologyCanvasChannel, +} from '../../components/MorphologyCanvas' +import { normalizeLayerOpacity } from '../../rendering/layerOpacity' +import { + addMorphologyTileChannels, + drawFlatImage, + type MorphologyChannelTileBatch, +} from '../../rendering/morphologyCanvas' +import { MorphologyTileStore } from '../../rendering/morphologyTileStore' +import type { OverviewViewState } from '../../rendering/deckLayerTypes' +import { + TileCache, + TILE_RETRY_DELAYS_MS, + type TileReadyEntry, +} from '../../tiff/tileCache' +import type { TileBitmapDecoder } from '../../workers/tileDecodePool' +import { abortError, isAbortError, throwIfAborted } from '../../utils/abort' +import { + scaledViewState, + screenshotImageLevel, + screenshotImageTiles, + screenshotTileViewState, + type ScreenshotRect, + type ScreenshotScale, + type ScreenshotSize, +} from './screenshotPlan' + +// The image under a screenshot (plan 27, task C): every channel's tiles at the +// level the screenshot's pixel size needs, drawn tile by tile of the frame. +// +// The screenshot keeps its own tile caches (27-D4), so a read of hundreds of +// tiles at another level does not push the canvas's tiles out of its cache, +// and `Retry` reads again a tile whose retries were spent. Tiles are drawn as +// they arrive and the caches hold few of them, so memory stays small however +// large the screenshot. Reads leave the byte-range cache as it is +// (`persist: false`). + +export interface ScreenshotImageSource { + // The channels the canvas draws, in its colours and contrast. + readonly channels: readonly MorphologyCanvasChannel[] + readonly flatImage: FlatMorphologyCanvasImage | null + // The image layer's opacity, as the canvas's CSS opacity. + readonly opacity: number +} + +export interface FlatImageElement { + readonly image: CanvasImageSource + readonly naturalSize: readonly [number, number] | null +} + +export interface ScreenshotImageOptions { + readonly viewState: OverviewViewState + readonly frame: ScreenshotSize + readonly scale: ScreenshotScale + // Requests in flight over every channel: the budget's limit. + readonly maxConcurrentRequests: number + readonly signal: AbortSignal + // After each tile is drawn. + readonly onTileDrawn?: () => void + readonly decodeTile?: TileBitmapDecoder + readonly loadFlatImage?: (url: string) => Promise + // Waits for a time in Date.now() ms; tests pass one that does not wait. + readonly waitUntil?: (time: number, signal: AbortSignal) => Promise +} + +// A tile that could not be read once its retries were spent. The screenshot +// fails rather than saving with a hole in it. +export class ScreenshotImageError extends Error { + readonly channelName: string + + constructor(channelName: string, cause: Error) { + super(`A tile of ${channelName} could not be read: ${cause.message}`, { cause }) + this.name = 'ScreenshotImageError' + this.channelName = channelName + } +} + +// Tiles named as coming next to each read, which a TIFF loader reads in the +// same request when they are stored beside it. +const UPCOMING_TILES = 8 + +interface ChannelRead { + readonly channel: MorphologyCanvasChannel + readonly cache: TileCache + readonly level: number +} + +interface TileRead { + readonly channelIndex: number + readonly tile: TileIndex +} + +export class ScreenshotImageComposer { + private readonly reads: readonly ChannelRead[] + private flatImage: Promise | null = null + + constructor( + private readonly source: ScreenshotImageSource, + private readonly options: ScreenshotImageOptions, + ) { + const cacheTiles = options.maxConcurrentRequests * 2 + 8 + this.reads = source.channels.map((channel) => ({ + channel, + level: screenshotImageLevel(channel.loader, options.viewState.zoom, options.scale), + cache: new TileCache({ + maxTiles: cacheTiles, + color: channel.color, + alphaFromIntensity: channel.alphaFromIntensity ?? true, + ...(channel.contrast === undefined ? {} : { displayWindow: channel.contrast }), + ...(options.decodeTile === undefined ? {} : { decodeTile: options.decodeTile }), + }), + })) + } + + get hasImage(): boolean { + return this.reads.length > 0 || this.source.flatImage !== null + } + + // The tiles every channel reads under a rect of the frame. + tileCount(rect: ScreenshotRect): number { + return this.reads.reduce( + (count, read) => count + this.tilesUnder(read, rect).length, + 0, + ) + } + + // Draws the image under a rect of the frame into a context the size of + // the rect in the screenshot's pixels, which it clears first. + async drawTile(context: CanvasRenderingContext2D, rect: ScreenshotRect): Promise { + const { scale, signal } = this.options + const viewport = { width: rect.width * scale, height: rect.height * scale } + const viewState = scaledViewState( + screenshotTileViewState(this.options.viewState, this.options.frame, rect), + scale, + ) + + context.setTransform(1, 0, 0, 1, 0, 0) + context.clearRect(0, 0, viewport.width, viewport.height) + throwIfAborted(signal) + + if (this.reads.length === 0) { + await this.drawFlatImage(context, viewState, viewport) + return + } + + const queue: TileRead[] = this.reads.flatMap((read, channelIndex) => + this.tilesUnder(read, rect).map((tile) => ({ channelIndex, tile })), + ) + let next = 0 + const work = async () => { + while (next < queue.length) { + const index = next + next += 1 + const item = queue[index] + if (item === undefined) return + const upcoming = queue + .slice(index + 1, index + 1 + UPCOMING_TILES) + .filter((other) => other.channelIndex === item.channelIndex) + .map((other) => other.tile) + const ready = await this.readTile(item, upcoming) + throwIfAborted(signal) + addMorphologyTileChannels( + context, + this.batches(item, ready), + viewState, + viewport, + 1, + ) + this.options.onTileDrawn?.() + } + } + const workers = Math.max( + 1, + Math.min(this.options.maxConcurrentRequests, queue.length), + ) + + await Promise.all(Array.from({ length: workers }, work)) + } + + dispose(): void { + for (const read of this.reads) { + read.cache.clear() + } + this.flatImage = null + } + + private tilesUnder(read: ChannelRead, rect: ScreenshotRect): readonly TileIndex[] { + return screenshotImageTiles( + read.channel.loader, + read.level, + this.options.viewState, + this.options.frame, + rect, + ) + } + + // Each channel in its colour, with only this tile: the canvas's rules for + // one channel or many. + private batches( + item: TileRead, + entry: TileReadyEntry, + ): readonly MorphologyChannelTileBatch[] { + return this.reads.map((read, index) => { + const { placement } = read.channel.loader + + return { + color: read.channel.color, + opacity: normalizeLayerOpacity(read.channel.opacity ?? 1), + tiles: + index === item.channelIndex + ? [ + { + id: read.cache.key(entry.level, item.tile.col, item.tile.row), + level: entry.level, + image: entry.bitmap, + bounds: entry.bounds, + sourceWidth: entry.sourceWidth, + sourceHeight: entry.sourceHeight, + }, + ] + : [], + ...(placement === undefined ? {} : { placement }), + } + }) + } + + // A tile read through the screenshot's cache, read again after each of + // TILE_RETRY_DELAYS_MS as the canvas's tiles are. + private async readTile( + item: TileRead, + upcoming: readonly TileIndex[], + ): Promise { + const read = this.reads[item.channelIndex] + if (read === undefined) throw new Error('No such channel.') + const { signal } = this.options + const loader: ImagePyramidLoader = read.channel.loader + const waitUntil = this.options.waitUntil ?? waitUntilTime + + for (let failures = 0; ; ) { + const entry = await read.cache.request( + loader, + read.level, + item.tile.col, + item.tile.row, + signal, + { upcoming, persist: false }, + ) + throwIfAborted(signal) + + if (entry.state === 'ready') return entry + if (entry.state === 'loading') continue + if (isAbortError(entry.error)) throw abortError(signal) + + failures += 1 + if (entry.retryAt === undefined || failures > TILE_RETRY_DELAYS_MS.length) { + throw new ScreenshotImageError(channelName(read.channel), entry.error) + } + await waitUntil(entry.retryAt, signal) + } + } + + private async drawFlatImage( + context: CanvasRenderingContext2D, + viewState: OverviewViewState, + viewport: { readonly width: number; readonly height: number }, + ): Promise { + const flat = this.source.flatImage + if (flat === null) return + + this.flatImage ??= (this.options.loadFlatImage ?? loadFlatImageElement)(flat.url) + const element = await this.flatImage + throwIfAborted(this.options.signal) + const size = flat.size ?? element.naturalSize + if (size === null) return + + drawFlatImage( + context, + { + image: element.image, + size, + scaleFactor: flat.scaleFactor, + micrometersPerPixel: flat.micrometersPerPixel, + }, + viewState, + viewport, + ) + this.options.onTileDrawn?.() + } +} + +function channelName(channel: MorphologyCanvasChannel): string { + return ( + channel.loader.channels.find((info) => info.id === channel.id)?.name ?? channel.id + ) +} + +async function loadFlatImageElement(url: string): Promise { + const image = await new MorphologyTileStore().flatImage(url) + return { + image, + naturalSize: + image.naturalWidth > 0 && image.naturalHeight > 0 + ? [image.naturalWidth, image.naturalHeight] + : null, + } +} + +// Resolves once Date.now() reaches the time. A timer can fire a moment +// before Date.now() does, so it waits again until it has (PR #426). +export function waitUntilTime(time: number, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + let timer: ReturnType | undefined + const onAbort = () => { + clearTimeout(timer) + reject(abortError(signal)) + } + const check = () => { + const left = time - Date.now() + if (left <= 0) { + signal.removeEventListener('abort', onAbort) + resolve() + return + } + timer = setTimeout(check, left) + } + + if (signal.aborted) { + reject(abortError(signal)) + return + } + signal.addEventListener('abort', onAbort, { once: true }) + check() + }) +} diff --git a/src/features/screenshot/screenshotModel.ts b/src/features/screenshot/screenshotModel.ts new file mode 100644 index 00000000..6ed824a2 --- /dev/null +++ b/src/features/screenshot/screenshotModel.ts @@ -0,0 +1,51 @@ +import { plotFileName } from '../plots/plotExport' +import { buildCommit, buildRelease } from '../shell/docLinks' +import { urlWithoutCredentials } from '../../utils/urlCredentials' +import type { ScreenshotInclude } from './screenshotOverlay' +import type { ScreenshotFileInfo } from './screenshotRun' +import type { ScreenshotRunner } from './screenshotRunner' + +// What the top bar's Screenshot popover (plan 27, task H) gets from App: the +// runner, and what only App knows of the view. +export interface ScreenshotModel { + readonly runner: ScreenshotRunner + // A dataset is open; the popover says when its view has not drawn yet. + readonly available: boolean + // D6: Include starts from Settings' switches, and selections on. + readonly include: ScreenshotInclude + // D7: the view's samples and loads, which the popover notes. + readonly expressionSampled: boolean + readonly transcriptsAsDensity: boolean + readonly loadingLabels: readonly string[] + readonly file: ScreenshotFileInfo +} + +export const SCREENSHOT_SOFTWARE_NAME = 'Spatial Omics Explorer' + +// The app's name, with its release and commit where the build has them. +export function screenshotSoftware( + release = buildRelease(), + commit = buildCommit(), +): string { + const parts = [SCREENSHOT_SOFTWARE_NAME] + if (release !== null) parts.push(release.tag) + if (commit !== null) parts.push(`(${commit.short})`) + return parts.join(' ') +} + +// 27-D11: `{dataset}-screenshot.png`, named as plot exports are, with the +// dataset's address as ROI exports write it. +export function screenshotFileInfo( + datasetUrl: string, + zPlane: number | null, + software = screenshotSoftware(), +): ScreenshotFileInfo { + const source = urlWithoutCredentials(datasetUrl).url + + return { + fileName: plotFileName(source, 'screenshot', null, 'png'), + software, + source: source.trim() === '' ? null : source, + zPlane, + } +} diff --git a/src/features/screenshot/screenshotOverlay.test.ts b/src/features/screenshot/screenshotOverlay.test.ts new file mode 100644 index 00000000..054c89e9 --- /dev/null +++ b/src/features/screenshot/screenshotOverlay.test.ts @@ -0,0 +1,204 @@ +import { describe, expect, it } from 'vitest' +import { micrometers } from '../../data/coords' +import type { ViewerLegendSection } from '../../components/viewerLegendTypes' +import type { OverviewViewState } from '../../rendering/deckLayerTypes' +import { + cssGradientStops, + estimateTextWidth, + fitText, + screenshotOverlayPaint, + screenshotOverlaySvg, + screenshotSelectionPaths, + type ScreenshotInclude, + type ScreenshotOverlayModels, +} from './screenshotOverlay' + +const frame = { width: 800, height: 600 } +const ALL: ScreenshotInclude = { + scaleBar: true, + legend: true, + axes: true, + selections: true, +} +const NONE: ScreenshotInclude = { + scaleBar: false, + legend: false, + axes: false, + selections: false, +} +const paint = screenshotOverlayPaint('canvas', null) +const measure = estimateTextWidth + +const categories: ViewerLegendSection = { + kind: 'categories', + id: 'clusters', + title: 'Clusters', + items: [ + { id: 'a', label: 'Astrocytes', color: '#ff0000', count: 1200, visible: true }, + { id: 'b', label: 'Neurons ', color: '#00ff00', count: 30, visible: true }, + { id: 'c', label: 'Hidden class', color: '#0000ff', count: 9, visible: false }, + ], + moreCount: 4, +} +const expression: ViewerLegendSection = { + kind: 'continuous', + id: 'expression', + title: 'SNAP25', + detail: 'Counts per cell', + gradient: + 'linear-gradient(90deg, rgba(0, 0, 4, 1) 0%, rgba(187, 55, 84, 1) 50%, #fcfdbf 100%)', + min: '0', + max: '12', +} +const models: ScreenshotOverlayModels = { + scaleBar: { label: '50 µm', widthPixels: 80 }, + axes: { + x: [{ position: 120, label: '1,000' }], + y: [{ position: 300, label: '2,000' }], + unitLabel: 'µm', + }, + legend: [expression, categories], + selections: [ + { d: 'M0 0L10 10Z', color: '#f0c84b', saved: false }, + { d: 'M5 5L20 20Z', color: '#58a6ff', saved: true }, + ], +} + +describe('screenshot overlays (plan 27, task E)', () => { + it('draws nothing when nothing is included', () => { + expect(screenshotOverlaySvg(frame, models, NONE, paint, measure)).toBeNull() + }) + + it('draws the frame’s marks in CSS pixels', () => { + const svg = screenshotOverlaySvg(frame, models, ALL, paint, measure) ?? '' + + expect(svg).toMatch(/^]*width="800" height="600" viewBox="0 0 800 600"/) + expect(svg).toContain('>50 µm') + expect(svg).toContain('>1,000') + expect(svg).toContain('rotate(-90)') + expect(svg).toContain('>SNAP25') + expect(svg).toContain('>Counts per cell') + expect(svg).toContain('') + expect(svg).toContain('>Astrocytes') + expect(svg).toContain('>1,200') + }) + + it('leaves hidden classes out of the legend and counts the rest as more', () => { + const svg = screenshotOverlaySvg(frame, models, ALL, paint, measure) ?? '' + + expect(svg).not.toContain('Hidden class') + expect(svg).toContain('>+4 more') + }) + + it('escapes text and colours', () => { + const svg = screenshotOverlaySvg(frame, models, ALL, paint, measure) ?? '' + + expect(svg).toContain('Neurons <deep>') + expect(svg).not.toContain('') + }) + + it('dashes saved selections and fills the active one', () => { + const svg = + screenshotOverlaySvg( + frame, + models, + { ...NONE, selections: true }, + paint, + measure, + ) ?? '' + + expect(svg).toContain( + ' { + const scaleBar = + screenshotOverlaySvg(frame, models, { ...NONE, scaleBar: true }, paint, measure) ?? + '' + const legend = + screenshotOverlaySvg(frame, models, { ...NONE, legend: true }, paint, measure) ?? '' + const box = (svg: string) => { + const match = / { + const white = screenshotOverlayPaint('white', null) + + expect(white.background).toBe('#ffffff') + expect(white.box).toBe('#ffffff') + expect(white.text).not.toBe(paint.text) + expect(screenshotOverlayPaint('transparent', null).background).toBeNull() + expect(paint.background).toBe('#000') + }) + + it('reads the stops of the app’s gradients', () => { + expect( + cssGradientStops('linear-gradient(90deg, rgba(1, 2, 3, 0.5) 0%, #fff 100%)'), + ).toEqual([ + { offset: 0, color: 'rgba(1, 2, 3, 0.5)' }, + { offset: 1, color: '#fff' }, + ]) + expect(cssGradientStops('linear-gradient(to right, red, green, blue)')).toEqual([ + { offset: 0, color: 'red' }, + { offset: 0.5, color: 'green' }, + { offset: 1, color: 'blue' }, + ]) + }) + + it('cuts text to fit with an ellipsis', () => { + const font = '400 10px sans-serif' + + expect(fitText('Astrocytes', 100, font, measure)).toBe('Astrocytes') + expect(fitText('Oligodendrocyte precursors', 60, font, measure)).toBe('Oligodend…') + }) + + it('draws saved selections dashed and the card’s own as it is drawn', () => { + const viewState: OverviewViewState = { + target: [50, -50, 0], + zoom: 0, + minZoom: -10, + maxZoom: 10, + } + const box = { + kind: 'box' as const, + bbox: { + minX: micrometers(10), + maxX: micrometers(20), + minY: micrometers(10), + maxY: micrometers(20), + }, + } + const paths = screenshotSelectionPaths( + [ + { id: 'saved', color: '#58a6ff', active: false, selection: box }, + { id: 'active', color: '#f0c84b', active: true, selection: box }, + ], + box, + '#f0c84b', + viewState, + { width: 100, height: 100 }, + ) + + expect(paths.map((path) => [path.color, path.saved])).toEqual([ + ['#58a6ff', true], + ['#f0c84b', false], + ]) + expect(paths[0]?.d).toBe('M 10.00 10.00 L 20.00 10.00 L 20.00 20.00 L 10.00 20.00 Z') + }) +}) diff --git a/src/features/screenshot/screenshotOverlay.ts b/src/features/screenshot/screenshotOverlay.ts new file mode 100644 index 00000000..cb87b3ff --- /dev/null +++ b/src/features/screenshot/screenshotOverlay.ts @@ -0,0 +1,589 @@ +import type { AxesModel } from '../../components/viewerAxesModel' +import { AXIS_BAND_PIXELS } from '../../components/viewerAxesModel' +import { + LEGEND_CATEGORY_LIMIT, + type CategoryLegendSection, + type ContinuousLegendSection, + type ViewerLegendSection, +} from '../../components/viewerLegendTypes' +import type { ScaleBarModel } from '../../components/viewerMeasurements' +import type { ViewerSelectionOutline } from '../../components/viewerCoreTypes' +import { roiSelectionToScreenPath } from '../../components/viewerRoiInteraction' +import type { RoiSelection } from '../../data/roiSelection' +import type { OverviewViewState } from '../../rendering/deckLayerTypes' +import type { ScreenshotSize } from './screenshotPlan' + +// The marks over the map (plan 27, task E): the scale bar, the legend, the +// axes and the selections, as one SVG over the frame in CSS pixels. It is +// drawn on the PNG at its scale, so they are as sharp as the rest, and laid +// out as the screen lays them out. It holds no external fonts or images, so +// the canvas it is drawn on can still be read. + +export type ScreenshotBackground = 'canvas' | 'white' | 'transparent' + +export interface ScreenshotInclude { + readonly scaleBar: boolean + readonly legend: boolean + readonly axes: boolean + readonly selections: boolean +} + +export interface ScreenshotSelectionPath { + // In the frame's CSS pixels. + readonly d: string + // Null takes the selection colour. + readonly color: string | null + // A saved selection other than the card's is dashed (15.4-A). + readonly saved: boolean +} + +// The saved selections, dashed, then the card's own (`active`), as the +// screen draws them, in the frame's CSS pixels. +export function screenshotSelectionPaths( + outlines: readonly ViewerSelectionOutline[], + active: RoiSelection | null, + activeColor: string | null, + viewState: OverviewViewState, + frame: ScreenshotSize, +): readonly ScreenshotSelectionPath[] { + const paths: ScreenshotSelectionPath[] = [] + + for (const outline of outlines) { + if (outline.active) continue + const d = roiSelectionToScreenPath(outline.selection, viewState, frame) + if (d !== null) paths.push({ d, color: outline.color, saved: true }) + } + + if (active !== null) { + const d = roiSelectionToScreenPath(active, viewState, frame) + if (d !== null) paths.push({ d, color: activeColor, saved: false }) + } + + return paths +} + +export interface ScreenshotOverlayModels { + readonly scaleBar: ScaleBarModel | null + readonly axes: AxesModel | null + readonly legend: readonly ViewerLegendSection[] + readonly selections: readonly ScreenshotSelectionPath[] +} + +export interface ScreenshotOverlayPaint { + // The fill under the map; null leaves it transparent. + readonly background: string | null + // The scale bar's and the legend's boxes. + readonly box: string + readonly border: string + readonly swatchBorder: string + readonly text: string + readonly muted: string + readonly axisBand: string + // Under gradients, as the screen's canvas. + readonly gradientBase: string + readonly selection: string + readonly shade: string + readonly halo: string + readonly font: string +} + +export type MeasureText = (text: string, font: string) => number + +const DARK = { + canvas: '#000', + box: '#161614', + axisBand: 'rgb(12 12 11 / 0.78)', + border: '#3a3934', + swatchBorder: '#6e6b62', + text: '#f0ede5', + muted: '#c9c4b8', + selection: '#f0c84b', +} + +// D8: on White the boxes turn white with dark text. +const LIGHT = { + box: '#ffffff', + axisBand: 'rgb(255 255 255 / 0.78)', + border: '#c9c6bd', + swatchBorder: '#8a867c', + text: '#1b1a17', + muted: '#4c4943', +} + +const SHADE = 'rgb(0 0 0 / 0.7)' +const HALO = 'rgb(255 253 247 / 0.55)' +const FALLBACK_FONT = "'Avenir Next', 'DIN Alternate', 'Segoe UI', system-ui, sans-serif" + +// The theme's colours for a background, read from the CSS tokens where the +// document has them. +export function screenshotOverlayPaint( + background: ScreenshotBackground, + root: Element | null = typeof document === 'undefined' + ? null + : document.documentElement, +): ScreenshotOverlayPaint { + const styles = root === null ? null : getComputedStyle(root) + const token = (name: string, fallback: string) => + styles?.getPropertyValue(name).trim() || fallback + const bodyFont = + typeof document === 'undefined' ? '' : getComputedStyle(document.body).fontFamily + const dark = background !== 'white' + + return { + background: + background === 'canvas' + ? token('--canvas', DARK.canvas) + : background === 'white' + ? '#ffffff' + : null, + box: dark ? token('--surface-1', DARK.box) : LIGHT.box, + border: dark ? token('--border', DARK.border) : LIGHT.border, + swatchBorder: dark ? token('--border-strong', DARK.swatchBorder) : LIGHT.swatchBorder, + text: dark ? token('--text-1', DARK.text) : LIGHT.text, + muted: dark ? token('--text-2', DARK.muted) : LIGHT.muted, + axisBand: dark ? DARK.axisBand : LIGHT.axisBand, + gradientBase: dark ? token('--canvas', DARK.canvas) : LIGHT.box, + selection: token('--overlay-selection', DARK.selection), + shade: SHADE, + halo: HALO, + font: bodyFont.trim() === '' ? FALLBACK_FONT : bodyFont.trim(), + } +} + +// Text widths from a 2D canvas, made on the first measure, or a rough guess +// where there is none. +export function canvasMeasureText(): MeasureText { + let context: CanvasRenderingContext2D | null | undefined + + return (text, font) => { + context ??= + typeof document === 'undefined' + ? null + : document.createElement('canvas').getContext('2d') + if (context === null) return estimateTextWidth(text, font) + context.font = font + return context.measureText(text).width + } +} + +export function estimateTextWidth(text: string, font: string): number { + const size = Number(/(\d+(?:\.\d+)?)px/.exec(font)?.[1] ?? 11) + return text.length * size * 0.6 +} + +// The whole overlay, or null when there is nothing to draw. +export function screenshotOverlaySvg( + frame: ScreenshotSize, + models: ScreenshotOverlayModels, + include: ScreenshotInclude, + paint: ScreenshotOverlayPaint, + measure: MeasureText, +): string | null { + const parts: string[] = [] + + if (include.selections) parts.push(...selectionMarks(models.selections, paint)) + if (include.axes && models.axes !== null) + parts.push(...axesMarks(frame, models.axes, paint)) + if (include.scaleBar && models.scaleBar !== null) { + parts.push(...scaleBarMarks(frame, models.scaleBar, paint, measure)) + } + if (include.legend && models.legend.length > 0) { + parts.push(...legendMarks(frame, models.legend, paint, measure)) + } + + if (parts.length === 0) return null + + return [ + ``, + ...parts, + '', + ].join('') +} + +function selectionMarks( + selections: readonly ScreenshotSelectionPath[], + paint: ScreenshotOverlayPaint, +): string[] { + return selections.map((selection) => { + const color = escapeXml(selection.color ?? paint.selection) + const d = escapeXml(selection.d) + // A dark casing with a light halo under the stroke, as on screen, so the + // outline shows over bright and dark images (EXP-311). + const casing = + `` + + `` + const line = selection.saved + ? `` + : `` + return `${casing}${line}` + }) +} + +const CAPTION_FONT_SIZE = 11 +const CONTROL_FONT_SIZE = 12 + +function font(paint: ScreenshotOverlayPaint, size: number, weight: number): string { + return `${weight.toString()} ${size.toString()}px ${paint.font}` +} + +function text( + x: number, + y: number, + value: string, + attributes: { + readonly fill: string + readonly size: number + readonly weight?: number + readonly anchor?: 'start' | 'middle' | 'end' + readonly transform?: string + }, +): string { + const transform = + attributes.transform === undefined ? '' : ` transform="${attributes.transform}"` + return `${escapeXml(value)}` +} + +// The rulers along the top and left edges (15.4-E), as ViewerAxes draws them. +function axesMarks( + frame: ScreenshotSize, + axes: AxesModel, + paint: ScreenshotOverlayPaint, +): string[] { + const band = AXIS_BAND_PIXELS + const labelCentre = band - 6 - CAPTION_FONT_SIZE / 2 + const marks = [ + ``, + ``, + ``, + ] + + for (const tick of axes.x) { + marks.push( + ``, + text(tick.position, labelCentre, tick.label, { + fill: paint.muted, + size: CAPTION_FONT_SIZE, + anchor: 'middle', + }), + ) + } + + for (const tick of axes.y) { + marks.push( + ``, + // Read bottom to top, as on a plot's y axis. + text(0, 0, tick.label, { + fill: paint.muted, + size: CAPTION_FONT_SIZE, + anchor: 'middle', + transform: `translate(${round(labelCentre)} ${round(tick.position)}) rotate(-90)`, + }), + ) + } + + marks.push( + ``, + ``, + text(frame.width - 8, 4 + CAPTION_FONT_SIZE / 2, axes.unitLabel, { + fill: paint.muted, + size: CAPTION_FONT_SIZE, + weight: 700, + anchor: 'end', + }), + ) + + return marks +} + +// The scale bar in the bottom-right corner, as ViewerCore's ScaleBar. +function scaleBarMarks( + frame: ScreenshotSize, + model: ScaleBarModel, + paint: ScreenshotOverlayPaint, + measure: MeasureText, +): string[] { + const labelFont = font(paint, CAPTION_FONT_SIZE, 800) + const contentWidth = Math.max(measure(model.label, labelFont), model.widthPixels) + const width = Math.max(70, Math.ceil(contentWidth) + 16) + const height = 1 + 5 + CAPTION_FONT_SIZE + 4 + 7 + 6 + 1 + const right = frame.width - 12 + const left = right - width + const top = frame.height - 12 - height + const trackTop = top + 1 + 5 + CAPTION_FONT_SIZE + 4 + const trackRight = right - 8 + const trackLeft = trackRight - model.widthPixels + + return [ + ``, + text(trackRight, top + 1 + 5 + CAPTION_FONT_SIZE / 2, model.label, { + fill: paint.text, + size: CAPTION_FONT_SIZE, + weight: 800, + anchor: 'end', + }), + ``, + ] +} + +const LEGEND_PADDING = 8 +const LEGEND_SECTION_GAP = 12 +const LEGEND_ROW_GAP = 4 +const LEGEND_TITLE_HEIGHT = 16 +const LEGEND_CAPTION_HEIGHT = 14 +const LEGEND_CATEGORY_HEIGHT = 20 +const LEGEND_GRADIENT_HEIGHT = 10 + +// The legend in the bottom-left corner, as the screen's stack places it. It +// leaves out its controls, and the classes hidden on the map. +function legendMarks( + frame: ScreenshotSize, + sections: readonly ViewerLegendSection[], + paint: ScreenshotOverlayPaint, + measure: MeasureText, +): string[] { + const width = Math.max(120, Math.min(260, frame.width - 36)) + const inner = width - LEGEND_PADDING * 2 + const blocks = sections.map((section, index) => + section.kind === 'continuous' + ? continuousLegend( + section, + `legend-gradient-${index.toString()}`, + inner, + paint, + measure, + ) + : categoryLegend(section, inner, paint, measure), + ) + const height = + LEGEND_PADDING * 2 + + blocks.reduce((total, block) => total + block.height, 0) + + LEGEND_SECTION_GAP * Math.max(0, blocks.length - 1) + const left = 12 + const top = frame.height - 12 - height + const marks = [ + ``, + ] + let y = top + LEGEND_PADDING + + blocks.forEach((block, index) => { + marks.push( + `${block.svg}`, + ) + y += block.height + (index < blocks.length - 1 ? LEGEND_SECTION_GAP : 0) + }) + + return marks +} + +interface LegendBlock { + readonly svg: string + readonly height: number +} + +function continuousLegend( + section: ContinuousLegendSection, + id: string, + width: number, + paint: ScreenshotOverlayPaint, + measure: MeasureText, +): LegendBlock { + const parts: string[] = [] + let y = 0 + + parts.push(legendTitle(section.title, width, y, paint, measure)) + y += LEGEND_TITLE_HEIGHT + LEGEND_ROW_GAP + + if (section.detail !== undefined) { + parts.push(legendCaption(section.detail, 0, y, width, paint, measure)) + y += LEGEND_CAPTION_HEIGHT + LEGEND_ROW_GAP + } + + const stops = cssGradientStops(section.gradient) + parts.push( + `${stops + .map( + (stop) => + ``, + ) + .join('')}`, + ``, + ``, + ) + y += LEGEND_GRADIENT_HEIGHT + LEGEND_ROW_GAP + + const rangeY = y + LEGEND_CAPTION_HEIGHT / 2 + parts.push( + text(0, rangeY, section.min, { fill: paint.muted, size: CAPTION_FONT_SIZE }), + text(width, rangeY, section.max, { + fill: paint.muted, + size: CAPTION_FONT_SIZE, + anchor: 'end', + }), + ) + y += LEGEND_CAPTION_HEIGHT + + return { svg: parts.join(''), height: y } +} + +function categoryLegend( + section: CategoryLegendSection, + width: number, + paint: ScreenshotOverlayPaint, + measure: MeasureText, +): LegendBlock { + const visible = section.items.filter((item) => item.visible) + const shown = visible.slice(0, LEGEND_CATEGORY_LIMIT) + const moreCount = visible.length - shown.length + (section.moreCount ?? 0) + const captionFont = font(paint, CAPTION_FONT_SIZE, 400) + const parts: string[] = [legendTitle(section.title, width, 0, paint, measure)] + let y = LEGEND_TITLE_HEIGHT + LEGEND_ROW_GAP + + for (const item of shown) { + const count = item.count.toLocaleString() + const countWidth = measure(count, captionFont) + const middle = y + LEGEND_CATEGORY_HEIGHT / 2 + parts.push( + ``, + text( + 18, + middle, + fitText(item.label, width - 18 - countWidth - 6, captionFont, measure), + { + fill: paint.text, + size: CAPTION_FONT_SIZE, + }, + ), + text(width, middle, count, { + fill: paint.muted, + size: CAPTION_FONT_SIZE, + anchor: 'end', + }), + ) + y += LEGEND_CATEGORY_HEIGHT + } + + if (moreCount > 0) { + parts.push( + legendCaption( + `+${moreCount.toLocaleString()} more`, + 0, + y + 2, + width, + paint, + measure, + ), + ) + y += 2 + LEGEND_CAPTION_HEIGHT + } + + return { svg: parts.join(''), height: y } +} + +function legendTitle( + title: string, + width: number, + y: number, + paint: ScreenshotOverlayPaint, + measure: MeasureText, +): string { + return text( + 0, + y + LEGEND_TITLE_HEIGHT / 2, + fitText(title, width, font(paint, CONTROL_FONT_SIZE, 650), measure), + { fill: paint.text, size: CONTROL_FONT_SIZE, weight: 650 }, + ) +} + +function legendCaption( + caption: string, + x: number, + y: number, + width: number, + paint: ScreenshotOverlayPaint, + measure: MeasureText, +): string { + return text( + x, + y + LEGEND_CAPTION_HEIGHT / 2, + fitText(caption, width, font(paint, CAPTION_FONT_SIZE, 400), measure), + { fill: paint.muted, size: CAPTION_FONT_SIZE }, + ) +} + +// The text cut with an ellipsis to fit, as the screen's labels are. +export function fitText( + value: string, + maxWidth: number, + textFont: string, + measure: MeasureText, +): string { + if (measure(value, textFont) <= maxWidth) return value + + let low = 0 + let high = value.length + while (low < high) { + const middle = Math.ceil((low + high) / 2) + if (measure(`${value.slice(0, middle)}…`, textFont) <= maxWidth) low = middle + else high = middle - 1 + } + + return `${value.slice(0, low).trimEnd()}…` +} + +export interface GradientStop { + readonly offset: number + readonly color: string +} + +// The stops of a left-to-right CSS gradient, as `colorsGradient` writes it: +// `linear-gradient(90deg, rgba(…) 0%, …)`. A stop without a position is +// spaced evenly. +export function cssGradientStops(gradient: string): readonly GradientStop[] { + const body = /linear-gradient\((.*)\)\s*$/s.exec(gradient.trim())?.[1] ?? '' + const parts = splitTopLevel(body) + .map((part) => part.trim()) + .filter((part) => part !== '' && !/^(?:-?[\d.]+deg|to\s)/.test(part)) + const last = Math.max(1, parts.length - 1) + + return parts.map((part, index) => { + const match = /^(.*?)(?:\s+(-?[\d.]+)%)?$/s.exec(part) + const color = match?.[1]?.trim() ?? part + const percent = match?.[2] + + return { + offset: percent === undefined ? index / last : Number(percent) / 100, + color, + } + }) +} + +function splitTopLevel(value: string): string[] { + const parts: string[] = [] + let depth = 0 + let start = 0 + + for (let index = 0; index < value.length; index += 1) { + const char = value[index] + if (char === '(') depth += 1 + else if (char === ')') depth -= 1 + else if (char === ',' && depth === 0) { + parts.push(value.slice(start, index)) + start = index + 1 + } + } + + parts.push(value.slice(start)) + return parts +} + +function round(value: number): string { + return Number(value.toFixed(2)).toString() +} + +function escapeXml(value: string): string { + return value + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') +} diff --git a/src/features/screenshot/screenshotPlan.test.ts b/src/features/screenshot/screenshotPlan.test.ts new file mode 100644 index 00000000..368ad8ec --- /dev/null +++ b/src/features/screenshot/screenshotPlan.test.ts @@ -0,0 +1,238 @@ +import fc from 'fast-check' +import { describe, expect, it } from 'vitest' +import { micrometers, type BBox, type TileIndex } from '../../data/coords' +import { rawDataPointToScreen } from '../../components/viewerMeasurements' +import type { OverviewViewState } from '../../rendering/deckLayerTypes' +import { + SCREENSHOT_SCALES, + scaledViewState, + screenshotChannelRead, + screenshotFrame, + screenshotGrid, + screenshotImageLevel, + screenshotImageTiles, + screenshotNotes, + screenshotPixelSize, + screenshotPrintSize, + screenshotSizeLimitReason, + screenshotTileViewState, + screenshotUnitsPerPixel, +} from './screenshotPlan' + +const view = (target: [number, number], zoom: number): OverviewViewState => ({ + target: [target[0], target[1], 0], + zoom, + minZoom: -10, + maxZoom: 10, +}) + +// The level whose pixel is at most 1.5 screen pixels, as the loaders pick it, +// for a pyramid of halving levels. +const loader = { + bestLevel: (deckScale: number) => + Math.max(0, Math.min(6, Math.floor(Math.log2(1.5 / deckScale)))), +} + +describe('screenshot plan (plan 27, task B)', () => { + it('takes the frame in whole CSS pixels', () => { + expect(screenshotFrame({ width: 1234.4, height: 800.6 })).toEqual({ + width: 1234, + height: 801, + }) + expect(screenshotFrame({ width: 0.2, height: 0 })).toEqual({ width: 1, height: 1 }) + }) + + it('refuses sizes over 16,384 px a side or 128 megapixels (D10)', () => { + expect(screenshotSizeLimitReason({ width: 16_384, height: 8_192 })).toBeNull() + expect(screenshotSizeLimitReason({ width: 16_385, height: 10 })).toMatch(/16,384 px/) + expect(screenshotSizeLimitReason({ width: 12_000, height: 12_000 })).toMatch( + /128 megapixels/, + ) + expect(screenshotPixelSize({ width: 1500, height: 900 }, 4)).toEqual({ + width: 6000, + height: 3600, + }) + }) + + it('covers the frame with tiles exactly, without overlap, on whole pixels (D9)', () => { + fc.assert( + fc.property( + fc.integer({ min: 1, max: 5000 }), + fc.integer({ min: 1, max: 5000 }), + fc.constantFrom(...SCREENSHOT_SCALES), + (width, height, scale) => { + const grid = screenshotGrid({ width, height }, scale) + let area = 0 + + for (const tile of grid.tiles) { + expect(Number.isInteger(tile.x) && Number.isInteger(tile.y)).toBe(true) + expect(Number.isInteger(tile.width) && Number.isInteger(tile.height)).toBe( + true, + ) + expect(tile.width * scale).toBeLessThanOrEqual(4096) + expect(tile.height * scale).toBeLessThanOrEqual(4096) + expect(tile.x + tile.width).toBeLessThanOrEqual(width) + expect(tile.y + tile.height).toBeLessThanOrEqual(height) + expect(tile.width).toBeLessThanOrEqual(grid.tileWidth) + area += tile.width * tile.height + } + + // Tiles inside the frame whose areas sum to the frame's cannot + // overlap or leave a gap, as they lie on a grid. + expect(area).toBe(width * height) + for (const [index, tile] of grid.tiles.entries()) { + for (const other of grid.tiles.slice(index + 1)) { + const overlaps = + tile.x < other.x + other.width && + other.x < tile.x + tile.width && + tile.y < other.y + other.height && + other.y < tile.y + tile.height + expect(overlaps).toBe(false) + } + } + }, + ), + { numRuns: 60 }, + ) + }) + + it('places a point at the same PNG pixel in its tile as in the frame', () => { + fc.assert( + fc.property( + fc.integer({ min: 200, max: 3000 }), + fc.integer({ min: 200, max: 3000 }), + fc.constantFrom(...SCREENSHOT_SCALES), + fc.double({ min: -3, max: 4, noNaN: true }), + fc.double({ min: 0, max: 1, noNaN: true }), + fc.double({ min: 0, max: 1, noNaN: true }), + (width, height, scale, zoom, u, v) => { + const frame = { width, height } + const viewState = view([1200, -900], zoom) + const screen = { x: u * width, y: v * height } + // The data point under that frame pixel. + const k = 2 ** zoom + const point = { + x: micrometers(viewState.target[0] + (screen.x - width / 2) / k), + y: micrometers(-viewState.target[1] + (screen.y - height / 2) / k), + } + expect(rawDataPointToScreen(point, viewState, frame).x).toBeCloseTo(screen.x, 6) + const grid = screenshotGrid(frame, scale) + const rect = grid.tiles.find( + (tile) => + screen.x >= tile.x && + screen.x <= tile.x + tile.width && + screen.y >= tile.y && + screen.y <= tile.y + tile.height, + ) + if (rect === undefined) return + const inTile = rawDataPointToScreen( + point, + scaledViewState(screenshotTileViewState(viewState, frame, rect), scale), + { width: rect.width * scale, height: rect.height * scale }, + ) + + expect(inTile.x + rect.x * scale).toBeCloseTo(screen.x * scale, 5) + expect(inTile.y + rect.y * scale).toBeCloseTo(screen.y * scale, 5) + }, + ), + { numRuns: 200 }, + ) + }) + + it('reads the level a frame N times larger reads at 1× (D4)', () => { + for (const zoom of [-4, -2.5, -1, 0, 0.75, 2]) { + for (const scale of SCREENSHOT_SCALES) { + expect(screenshotImageLevel(loader, zoom, scale)).toBe( + screenshotImageLevel(loader, zoom + Math.log2(scale), 1), + ) + } + } + expect(screenshotImageLevel(loader, -3, 1)).toBe(3) + expect(screenshotImageLevel(loader, -3, 4)).toBe(1) + }) + + it('finds tiles in the loader’s frame for a flipped image', () => { + const asked: BBox[] = [] + const flipped = { + // y flipped about 0: the loader's frame runs the other way. + placement: { a: 1, b: 0, c: micrometers(0), d: 0, e: -1, f: micrometers(0) }, + tilesForBbox: (_level: number, bbox: BBox): readonly TileIndex[] => { + asked.push(bbox) + return [{ col: 0, row: 0 }] + }, + } + + screenshotImageTiles( + flipped, + 0, + view([50, -25], 0), + { width: 100, height: 50 }, + { x: 0, y: 0, width: 100, height: 50 }, + ) + + expect(asked[0]).toEqual({ minX: 0, maxX: 100, minY: -50, maxY: 0 }) + }) + + it('counts each grid tile’s reads, and the frame’s tiles once', () => { + const tiles = (bbox: BBox): readonly TileIndex[] => { + const out: TileIndex[] = [] + for (let col = Math.floor(bbox.minX / 100); col * 100 < bbox.maxX; col += 1) { + for (let row = Math.floor(bbox.minY / 100); row * 100 < bbox.maxY; row += 1) { + out.push({ col, row }) + } + } + return out + } + const grid = { tileWidth: 150, tileHeight: 200, tiles: [] as never[] } + const frame = { width: 300, height: 200 } + const read = screenshotChannelRead( + { ...loader, tilesForBbox: (_level, bbox) => tiles(bbox) }, + view([150, -100], 0), + frame, + { + ...grid, + tiles: [ + { x: 0, y: 0, width: 150, height: 200 }, + { x: 150, y: 0, width: 150, height: 200 }, + ], + }, + 1, + ) + + // Columns 0–2 over the frame; column 1 lies under both grid tiles. + expect(read.frameTiles).toHaveLength(6) + expect(read.reads).toBe(8) + }) + + it('gives µm per PNG pixel and the print size', () => { + expect(screenshotUnitsPerPixel(0, 2)).toBe(0.5) + expect(screenshotUnitsPerPixel(-2, 1)).toBe(4) + expect(screenshotPrintSize({ width: 3000, height: 1800 }, 300)).toBe( + '254 × 152 mm at 300 dpi', + ) + }) + + it('notes what the screen samples and what is still loading (D5, D7)', () => { + expect( + screenshotNotes({ + cells: { inView: 1_414_155, onScreen: 250_000 }, + expressionSampled: true, + transcriptsAsDensity: true, + loadingLabels: ['Loading cell boundaries'], + }), + ).toEqual([ + 'Draws all 1,414,155 cells in view; the screen shows about 250,000.', + 'Expression is a sample at this zoom. Set Expression detail to All cells to colour every cell.', + 'Transcripts are density squares at this zoom. Set Detail to Exact, or zoom in, for points.', + 'Still loading: Loading cell boundaries. The screenshot shows what has loaded.', + ]) + expect( + screenshotNotes({ + cells: { inView: 500, onScreen: 500 }, + expressionSampled: false, + transcriptsAsDensity: false, + loadingLabels: [], + }), + ).toEqual([]) + }) +}) diff --git a/src/features/screenshot/screenshotPlan.ts b/src/features/screenshot/screenshotPlan.ts new file mode 100644 index 00000000..9f1779f1 --- /dev/null +++ b/src/features/screenshot/screenshotPlan.ts @@ -0,0 +1,262 @@ +import { + scaleFromZoom, + unplaceFrameBbox, + type BBox, + type TileIndex, +} from '../../data/coords' +import type { ImagePyramidLoader } from '../../data/imagePyramid' +import { morphologyViewportBbox } from '../../rendering/morphologyCanvas' +import type { CssViewportSize } from '../../rendering/morphologyCanvas' +import type { OverviewViewState } from '../../rendering/deckLayerTypes' + +// The screenshot's plan (plan 27, task B): its size, the grid of tiles it is +// drawn in, and the image tiles each channel reads. Everything here is pure. + +export const SCREENSHOT_SCALES = [1, 2, 4, 8] as const +export type ScreenshotScale = (typeof SCREENSHOT_SCALES)[number] +export const DEFAULT_SCREENSHOT_SCALE: ScreenshotScale = 2 +export const DEFAULT_SCREENSHOT_DPI = 300 + +// D10: Chromium draws 2D canvases up to 16,384 px a side, and encoding holds +// the RGBA pixels (512 MiB at 128 megapixels) beside the canvas. +export const SCREENSHOT_MAX_SIDE_PIXELS = 16_384 +export const SCREENSHOT_MAX_PIXELS = 128 * 1024 ** 2 +// D9: WebGL silently shrinks a drawing buffer past its limit, so deck.gl +// draws the screenshot in tiles of at most this many pixels a side. +export const SCREENSHOT_TILE_MAX_PIXELS = 4_096 +// D4: a larger image read asks first, as Cell Query does (26-D7). +export const SCREENSHOT_ASK_BYTES = 512 * 1024 ** 2 +// Image requests in flight where the viewer is given no limit, as +// MorphologyCanvas's default. +export const SCREENSHOT_DEFAULT_TILE_REQUESTS = 4 + +export interface ScreenshotRect { + // In the frame's CSS pixels. + readonly x: number + readonly y: number + readonly width: number + readonly height: number +} + +export interface ScreenshotSize { + readonly width: number + readonly height: number +} + +// The frame in whole CSS pixels: the canvas can measure a fraction of one. +export function screenshotFrame(viewport: CssViewportSize): ScreenshotSize { + return { + width: Math.max(1, Math.round(viewport.width)), + height: Math.max(1, Math.round(viewport.height)), + } +} + +export function screenshotPixelSize( + frame: ScreenshotSize, + scale: ScreenshotScale, +): ScreenshotSize { + return { width: frame.width * scale, height: frame.height * scale } +} + +// Why a size cannot be drawn, or null when it can. +export function screenshotSizeLimitReason(size: ScreenshotSize): string | null { + if (Math.max(size.width, size.height) > SCREENSHOT_MAX_SIDE_PIXELS) { + return `Over ${SCREENSHOT_MAX_SIDE_PIXELS.toLocaleString()} px on a side` + } + + if (size.width * size.height > SCREENSHOT_MAX_PIXELS) { + return `Over ${(SCREENSHOT_MAX_PIXELS / 1024 ** 2).toLocaleString()} megapixels` + } + + return null +} + +export interface ScreenshotGrid { + // Every tile has this size, in CSS pixels; those at the right and bottom + // edges are drawn at it and cut to the frame. + readonly tileWidth: number + readonly tileHeight: number + // Row by row, each cut to the frame. + readonly tiles: readonly ScreenshotRect[] +} + +// D9: tiles of whole CSS pixels, and so of whole device pixels at a whole +// scale, at most SCREENSHOT_TILE_MAX_PIXELS device pixels a side. +export function screenshotGrid( + frame: ScreenshotSize, + scale: ScreenshotScale, + maxTilePixels = SCREENSHOT_TILE_MAX_PIXELS, +): ScreenshotGrid { + const maxTileCss = Math.max(1, Math.floor(maxTilePixels / scale)) + const tileWidth = Math.min(frame.width, maxTileCss) + const tileHeight = Math.min(frame.height, maxTileCss) + const tiles: ScreenshotRect[] = [] + + for (let y = 0; y < frame.height; y += tileHeight) { + for (let x = 0; x < frame.width; x += tileWidth) { + tiles.push({ + x, + y, + width: Math.min(tileWidth, frame.width - x), + height: Math.min(tileHeight, frame.height - y), + }) + } + } + + return { tileWidth, tileHeight, tiles } +} + +// The view of one tile of the frame: the same zoom, centred on the tile. +export function screenshotTileViewState( + viewState: OverviewViewState, + frame: ScreenshotSize, + rect: ScreenshotRect, +): OverviewViewState { + const scale = scaleFromZoom(viewState.zoom) + + return { + ...viewState, + target: [ + viewState.target[0] + (rect.x + rect.width / 2 - frame.width / 2) / scale, + viewState.target[1] + (frame.height / 2 - rect.y - rect.height / 2) / scale, + viewState.target[2] ?? 0, + ], + } +} + +// The same view drawn `scale` times larger: a CSS pixel of the view becomes +// `scale` pixels, so a 2D canvas can draw it with one pixel per pixel. +export function scaledViewState( + viewState: OverviewViewState, + scale: ScreenshotScale, +): OverviewViewState { + return { ...viewState, zoom: viewState.zoom + Math.log2(scale) } +} + +// D4: the level a view `scale` times larger reads. +export function screenshotImageLevel( + loader: Pick, + zoom: number, + scale: ScreenshotScale, +): number { + return loader.bestLevel(scaleFromZoom(zoom) * scale) +} + +// The image tiles under a rect of the frame, in the loader's frame. +export function screenshotImageTiles( + loader: Pick, + level: number, + viewState: OverviewViewState, + frame: ScreenshotSize, + rect: ScreenshotRect, +): readonly TileIndex[] { + const bbox = morphologyViewportBbox(screenshotTileViewState(viewState, frame, rect), { + width: rect.width, + height: rect.height, + }) + + return loader.tilesForBbox(level, loaderFrameBbox(loader, bbox)) +} + +function loaderFrameBbox( + loader: Pick, + bbox: BBox, +): BBox { + return loader.placement === undefined ? bbox : unplaceFrameBbox(loader.placement, bbox) +} + +export interface ScreenshotChannelRead { + readonly level: number + // The tiles of the whole frame, each once, for the byte estimate. + readonly frameTiles: readonly TileIndex[] + // The reads of every grid tile; a tile under two grid tiles is read twice. + readonly reads: number +} + +export function screenshotChannelRead( + loader: Pick, + viewState: OverviewViewState, + frame: ScreenshotSize, + grid: ScreenshotGrid, + scale: ScreenshotScale, +): ScreenshotChannelRead { + const level = screenshotImageLevel(loader, viewState.zoom, scale) + const whole = { x: 0, y: 0, width: frame.width, height: frame.height } + + return { + level, + frameTiles: screenshotImageTiles(loader, level, viewState, frame, whole), + reads: grid.tiles.reduce( + (count, rect) => + count + screenshotImageTiles(loader, level, viewState, frame, rect).length, + 0, + ), + } +} + +// µm (or the dataset's unit) per pixel of the PNG. +export function screenshotUnitsPerPixel(zoom: number, scale: ScreenshotScale): number { + return 1 / (scaleFromZoom(zoom) * scale) +} + +// "254 × 152 mm at 300 dpi". +export function screenshotPrintSize(size: ScreenshotSize, dpi: number): string { + const mm = (pixels: number) => Math.round((pixels / dpi) * 25.4).toLocaleString() + return `${mm(size.width)} × ${mm(size.height)} mm at ${dpi.toLocaleString()} dpi` +} + +// "0.85", "12.5", "0.0213": three significant digits. +export function formatUnitsPerPixel(value: number): string { + return Number(value.toPrecision(3)).toLocaleString(undefined, { + maximumSignificantDigits: 3, + }) +} + +export interface ScreenshotCellCounts { + // Cells in the frame. + readonly inView: number + // About how many of them the screen draws, after the render cap. + readonly onScreen: number +} + +// D5 and D7: what the PNG shows that the screen does not, or that is a +// sample. Each note says what would change it. +export function screenshotNotes({ + cells, + expressionSampled, + transcriptsAsDensity, + loadingLabels, +}: { + readonly cells: ScreenshotCellCounts | null + readonly expressionSampled: boolean + readonly transcriptsAsDensity: boolean + readonly loadingLabels: readonly string[] +}): readonly string[] { + const notes: string[] = [] + + if (cells !== null && cells.onScreen < cells.inView) { + notes.push( + `Draws all ${cells.inView.toLocaleString()} cells in view; the screen shows about ${cells.onScreen.toLocaleString()}.`, + ) + } + + if (expressionSampled) { + notes.push( + 'Expression is a sample at this zoom. Set Expression detail to All cells to colour every cell.', + ) + } + + if (transcriptsAsDensity) { + notes.push( + 'Transcripts are density squares at this zoom. Set Detail to Exact, or zoom in, for points.', + ) + } + + if (loadingLabels.length > 0) { + notes.push( + `Still loading: ${loadingLabels.join(', ')}. The screenshot shows what has loaded.`, + ) + } + + return notes +} diff --git a/src/features/screenshot/screenshotRun.test.ts b/src/features/screenshot/screenshotRun.test.ts new file mode 100644 index 00000000..e77d0488 --- /dev/null +++ b/src/features/screenshot/screenshotRun.test.ts @@ -0,0 +1,317 @@ +import { describe, expect, it, vi } from 'vitest' +import { imagePixels, micrometers, type BBox } from '../../data/coords' +import type { ImagePyramidLoader } from '../../data/imagePyramid' +import type { OverviewViewState } from '../../rendering/deckLayerTypes' +import { pngTextEntries, readPngChunks } from './pngChunks' +import { screenshotOverlayPaint, type ScreenshotInclude } from './screenshotOverlay' +import { + drawScreenshot, + screenshotDescription, + type ScreenshotProgress, + type ScreenshotSnapshot, +} from './screenshotRun' +import type { ScreenshotDeckProps } from './screenshotDeck' + +const ONE_PIXEL_PNG = Uint8Array.from( + atob( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', + ), + (char) => char.charCodeAt(0), +) +const NONE: ScreenshotInclude = { + scaleBar: false, + legend: false, + axes: false, + selections: false, +} +const viewState: OverviewViewState = { + target: [100, -50, 0], + zoom: 0, + minZoom: -10, + maxZoom: 10, +} + +// Canvases whose contexts record what is drawn on them, in order. +function fakeCanvases() { + const log: string[] = [] + const canvases: { width: number; height: number; name: string }[] = [] + const createCanvas = (width: number, height: number) => { + const name = canvases.length === 0 ? 'png' : 'scratch' + const canvas = { + width, + height, + name, + getContext: () => context, + toBlob: (callback: (blob: Blob | null) => void) => { + callback(new Blob([ONE_PIXEL_PNG], { type: 'image/png' })) + }, + } + const context = { + canvas, + globalAlpha: 1, + globalCompositeOperation: 'source-over', + fillStyle: '', + imageSmoothingQuality: 'low', + setTransform: vi.fn(), + clearRect: vi.fn(), + fillRect: vi.fn(function (this: { fillStyle: string }) { + log.push(`${name} fill ${this.fillStyle}`) + }), + drawImage: vi.fn(function ( + this: { globalAlpha: number }, + image: { name?: string; key?: string }, + ...args: number[] + ) { + log.push( + `${name} draw ${image.name ?? image.key ?? 'image'} at ${args.slice(-4).join(',')} alpha ${this.globalAlpha.toString()}`, + ) + }), + } + canvases.push(canvas) + return canvas as unknown as HTMLCanvasElement + } + + return { log, canvases, createCanvas } +} + +function fakeDeck(log: string[]) { + return (props: ScreenshotDeckProps) => { + const canvas = { name: 'deck', getContext: () => null } + queueMicrotask(() => { + props.onLoad?.() + }) + return { + setProps: vi.fn(), + redraw: () => { + log.push('deck redraw') + }, + getCanvas: () => canvas as unknown as HTMLCanvasElement, + finalize: () => { + log.push('deck finalize') + }, + } + } +} + +function loader(): ImagePyramidLoader { + return { + url: 'https://example.test/dapi.ome.tif', + channels: [{ id: 'dapi', name: 'DAPI' }], + bestLevel: () => 0, + tilesForBbox: () => [{ col: 0, row: 0 }], + tileBounds: (): BBox => ({ + minX: micrometers(0), + maxX: micrometers(100), + minY: micrometers(0), + maxY: micrometers(100), + }), + tileSourceSize: () => ({ width: imagePixels(100), height: imagePixels(100) }), + loadTile: () => + Promise.resolve({ + bitmap: { key: 'tile', close: vi.fn() } as unknown as ImageBitmap, + width: 100, + height: 100, + lo: 0, + hi: 255, + }), + } as unknown as ImagePyramidLoader +} + +function snapshot(overrides: Partial = {}): ScreenshotSnapshot { + const image = loader() + return { + viewState, + viewport: { width: 200, height: 100 }, + image: { + channels: [ + { + id: 'dapi', + loader: image, + enabled: true, + color: [0, 0, 255], + contrast: { lo: 0, hi: 255 }, + }, + ], + flatImage: null, + opacity: 0.5, + }, + layers: () => [], + overlays: { scaleBar: null, axes: null, legend: [], selections: [] }, + cells: null, + unitLabel: 'µm', + maxConcurrentTileRequests: 4, + viewChangedAt: 0, + ...overrides, + } +} + +const file = { + fileName: 'run-screenshot.png', + software: 'Spatial Omics Explorer v1.0.0', + source: 'https://example.test/run.h5ad', + zPlane: 3, +} + +describe('drawing a screenshot (plan 27, steps 2–6)', () => { + it('fills the background, lays the image at its opacity, then the cells', async () => { + const { log, createCanvas } = fakeCanvases() + + await drawScreenshot( + snapshot(), + { scale: 2, dpi: 300, include: NONE, background: 'white' }, + file, + { + signal: new AbortController().signal, + createCanvas, + createDeck: fakeDeck(log), + paint: screenshotOverlayPaint('white', null), + }, + ) + + expect(log).toEqual([ + 'png fill #ffffff', + 'scratch draw tile at 0,0,200,200 alpha 1', + 'png draw scratch at 0,0,400,200 alpha 0.5', + 'deck redraw', + 'png draw deck at 0,0,400,200 alpha 1', + 'deck finalize', + ]) + }) + + it('writes the dpi and where the PNG came from (D11)', async () => { + const { log, createCanvas } = fakeCanvases() + + const blob = await drawScreenshot( + snapshot(), + { scale: 2, dpi: 600, include: NONE, background: 'transparent' }, + file, + { + signal: new AbortController().signal, + createCanvas, + createDeck: fakeDeck(log), + paint: screenshotOverlayPaint('transparent', null), + now: () => new Date('2026-11-24T12:00:00Z'), + }, + ) + const png = new Uint8Array(await blob.arrayBuffer()) + + expect(blob.type).toBe('image/png') + expect(log[0]).not.toMatch(/fill/) + expect(readPngChunks(png).map((chunk) => chunk.type)).toEqual([ + 'IHDR', + 'pHYs', + 'tEXt', + 'tEXt', + 'tEXt', + 'tEXt', + 'IDAT', + 'IEND', + ]) + expect(pngTextEntries(png)).toEqual({ + Software: 'Spatial Omics Explorer v1.0.0', + Source: 'https://example.test/run.h5ad', + Description: 'x 0 to 200 µm, y 0 to 100 µm; 0.5 µm per pixel; 2× scale; z plane 3', + 'Creation Time': '2026-11-24T12:00:00.000Z', + }) + }) + + it('reports progress, and empties its canvases when done', async () => { + const { log, canvases, createCanvas } = fakeCanvases() + const progress: ScreenshotProgress[] = [] + + await drawScreenshot( + snapshot(), + { scale: 1, dpi: 300, include: NONE, background: 'canvas' }, + file, + { + signal: new AbortController().signal, + createCanvas, + createDeck: fakeDeck(log), + paint: screenshotOverlayPaint('canvas', null), + onProgress: (step) => progress.push(step), + }, + ) + + expect(progress.at(-1)).toEqual({ stage: 'writing', done: 2, total: 3 }) + expect(progress.map((step) => step.stage)).toEqual([ + 'image', + 'image', + 'cells', + 'writing', + ]) + expect(canvases.every((canvas) => canvas.width === 0 && canvas.height === 0)).toBe( + true, + ) + }) + + it('draws no cells where the view has no layers', async () => { + const { log, createCanvas } = fakeCanvases() + + await drawScreenshot( + snapshot({ layers: null }), + { scale: 1, dpi: 300, include: NONE, background: 'canvas' }, + file, + { + signal: new AbortController().signal, + createCanvas, + createDeck: fakeDeck(log), + paint: screenshotOverlayPaint('canvas', null), + }, + ) + + expect(log.some((line) => line.startsWith('deck'))).toBe(false) + }) + + it('refuses a PNG over the size limit (D10)', async () => { + const { createCanvas } = fakeCanvases() + + await expect( + drawScreenshot( + snapshot({ viewport: { width: 4000, height: 3000 } }), + { scale: 8, dpi: 300, include: NONE, background: 'canvas' }, + file, + { signal: new AbortController().signal, createCanvas }, + ), + ).rejects.toThrow(/too large/) + }) + + it('stops, and lets the Deck go, when cancelled', async () => { + const { log, canvases, createCanvas } = fakeCanvases() + const controller = new AbortController() + + const drawing = drawScreenshot( + snapshot(), + { scale: 1, dpi: 300, include: NONE, background: 'canvas' }, + file, + { + signal: controller.signal, + createCanvas, + createDeck: fakeDeck(log), + paint: screenshotOverlayPaint('canvas', null), + onProgress: (step) => { + if (step.stage === 'cells') controller.abort() + }, + }, + ) + + await expect(drawing).rejects.toThrow(/abort/i) + expect(log.at(-1)).toBe('deck finalize') + expect(canvases.every((canvas) => canvas.width === 0)).toBe(true) + }) + + it('describes the view without its locale’s separators', () => { + expect( + screenshotDescription( + { + viewState: { ...viewState, target: [12_345.67, -2_000, 0], zoom: -2 }, + unitLabel: 'units', + }, + { width: 1000, height: 400 }, + { scale: 4 }, + null, + ), + ).toBe( + 'x 10345.7 to 14345.7 units, y 1200 to 2800 units; 1 units per pixel; 4× scale', + ) + }) +}) diff --git a/src/features/screenshot/screenshotRun.ts b/src/features/screenshot/screenshotRun.ts new file mode 100644 index 00000000..381e5e3f --- /dev/null +++ b/src/features/screenshot/screenshotRun.ts @@ -0,0 +1,335 @@ +import type { LayersList } from '@deck.gl/core' +import type { CssViewportSize } from '../../rendering/morphologyCanvas' +import { morphologyViewportBbox } from '../../rendering/morphologyCanvas' +import type { OverviewViewState } from '../../rendering/deckLayerTypes' +import { throwIfAborted } from '../../utils/abort' +import { insertPngChunks, pngPhysChunk, pngTextChunk, type PngChunk } from './pngChunks' +import { + ScreenshotDeckRenderer, + unpickableLayers, + type CreateScreenshotDeck, +} from './screenshotDeck' +import { + ScreenshotImageComposer, + type FlatImageElement, + type ScreenshotImageSource, +} from './screenshotImage' +import { + canvasMeasureText, + screenshotOverlayPaint, + screenshotOverlaySvg, + type MeasureText, + type ScreenshotBackground, + type ScreenshotInclude, + type ScreenshotOverlayModels, + type ScreenshotOverlayPaint, +} from './screenshotOverlay' +import { + screenshotFrame, + screenshotGrid, + screenshotPixelSize, + screenshotSizeLimitReason, + screenshotTileViewState, + screenshotUnitsPerPixel, + type ScreenshotCellCounts, + type ScreenshotScale, + type ScreenshotSize, +} from './screenshotPlan' + +// What the view holds when `Save PNG` is pressed (plan 27, step 1). Pans, +// zooms and loads after it do not change the screenshot. It stays out of +// React props, in the runner, as its layers' data can be large typed arrays. +export interface ScreenshotSnapshot { + readonly viewState: OverviewViewState + readonly viewport: CssViewportSize + readonly image: ScreenshotImageSource + // New layers with every loaded cell; null where the view draws no layers. + readonly layers: (() => LayersList) | null + readonly overlays: ScreenshotOverlayModels + readonly cells: ScreenshotCellCounts | null + // The data's unit: µm, or "units" without a known physical size. + readonly unitLabel: string + readonly maxConcurrentTileRequests: number + // When the view last moved (performance.now() ms). + readonly viewChangedAt: number +} + +export interface ScreenshotOptions { + readonly scale: ScreenshotScale + readonly dpi: number + readonly include: ScreenshotInclude + readonly background: ScreenshotBackground +} + +// Where the PNG came from, for its text chunks (27-D11). +export interface ScreenshotFileInfo { + readonly fileName: string + readonly software: string + // The dataset URL without a presigned URL's signature. + readonly source: string | null + // The z-stack plane shown, counted from 1; null for a single plane. + readonly zPlane: number | null +} + +export type ScreenshotStage = 'image' | 'cells' | 'writing' + +export interface ScreenshotProgress { + readonly stage: ScreenshotStage + readonly done: number + readonly total: number +} + +export interface DrawScreenshotOptions { + readonly signal: AbortSignal + readonly onProgress?: (progress: ScreenshotProgress) => void + readonly createCanvas?: (width: number, height: number) => HTMLCanvasElement + readonly paint?: ScreenshotOverlayPaint + readonly measure?: MeasureText + readonly createDeck?: CreateScreenshotDeck + readonly loadFlatImage?: (url: string) => Promise + readonly now?: () => Date +} + +// Draws the snapshot as a PNG, with its dpi and text chunks. +export async function drawScreenshot( + snapshot: ScreenshotSnapshot, + options: ScreenshotOptions, + file: ScreenshotFileInfo, + run: DrawScreenshotOptions, +): Promise { + const { scale } = options + const { signal } = run + const frame = screenshotFrame(snapshot.viewport) + const size = screenshotPixelSize(frame, scale) + const limit = screenshotSizeLimitReason(size) + if (limit !== null) throw new Error(`The PNG would be too large: ${limit}.`) + + const createCanvas = run.createCanvas ?? createCanvasElement + const paint = run.paint ?? screenshotOverlayPaint(options.background) + const grid = screenshotGrid(frame, scale) + let imageDone = 0 + let cellsDone = 0 + let total = 1 + const report = (stage: ScreenshotStage) => { + run.onProgress?.({ stage, done: imageDone + cellsDone, total }) + } + const composer = new ScreenshotImageComposer(snapshot.image, { + viewState: snapshot.viewState, + frame, + scale, + maxConcurrentRequests: snapshot.maxConcurrentTileRequests, + signal, + onTileDrawn: () => { + imageDone += 1 + report('image') + }, + ...(run.loadFlatImage === undefined ? {} : { loadFlatImage: run.loadFlatImage }), + }) + const imageTotal = + snapshot.image.channels.length > 0 + ? grid.tiles.reduce((count, rect) => count + composer.tileCount(rect), 0) + : snapshot.image.flatImage === null + ? 0 + : grid.tiles.length + total = imageTotal + (snapshot.layers === null ? 0 : grid.tiles.length) + 1 + + const canvas = createCanvas(size.width, size.height) + const scratch = composer.hasImage + ? createCanvas(grid.tileWidth * scale, grid.tileHeight * scale) + : null + let deck: ScreenshotDeckRenderer | null = null + + try { + const context = canvas.getContext('2d') + const scratchContext = scratch?.getContext('2d') ?? null + if (context === null || (scratch !== null && scratchContext === null)) { + throw new Error('This browser cannot draw a canvas this large.') + } + + if (paint.background !== null) { + context.fillStyle = paint.background + context.fillRect(0, 0, size.width, size.height) + } + report('image') + + if (snapshot.layers !== null) { + deck = await ScreenshotDeckRenderer.create({ + layers: unpickableLayers(snapshot.layers()), + tileWidth: grid.tileWidth, + tileHeight: grid.tileHeight, + scale, + viewState: snapshot.viewState, + signal, + ...(run.createDeck === undefined ? {} : { createDeck: run.createDeck }), + }) + } + + for (const rect of grid.tiles) { + if (scratch !== null && scratchContext !== null) { + await composer.drawTile(scratchContext, rect) + context.globalAlpha = Math.max(0, Math.min(1, snapshot.image.opacity)) + context.drawImage( + scratch, + 0, + 0, + rect.width * scale, + rect.height * scale, + rect.x * scale, + rect.y * scale, + rect.width * scale, + rect.height * scale, + ) + context.globalAlpha = 1 + } + + throwIfAborted(signal) + + if (deck !== null) { + // Every tile is drawn at the grid's size, centred on its own middle; + // tiles at the right and bottom edges are cut to the frame. + const tileView = screenshotTileViewState(snapshot.viewState, frame, { + x: rect.x, + y: rect.y, + width: grid.tileWidth, + height: grid.tileHeight, + }) + deck.drawTile(context, tileView, rect, { x: rect.x * scale, y: rect.y * scale }) + cellsDone += 1 + report('cells') + // Lets the page take input between tiles. + await nextTask() + throwIfAborted(signal) + } + } + + deck?.destroy() + deck = null + + const svg = screenshotOverlaySvg( + frame, + snapshot.overlays, + options.include, + paint, + run.measure ?? canvasMeasureText(), + ) + if (svg !== null) { + await drawSvg(context, svg, frame, size) + throwIfAborted(signal) + } + + report('writing') + const png = await canvasPng(canvas) + throwIfAborted(signal) + + return new Blob( + [ + insertPngChunks( + png, + screenshotChunks( + snapshot, + frame, + options, + file, + (run.now ?? (() => new Date()))(), + ), + ) as Uint8Array, + ], + { type: 'image/png' }, + ) + } finally { + deck?.destroy() + composer.dispose() + canvas.width = 0 + canvas.height = 0 + if (scratch !== null) { + scratch.width = 0 + scratch.height = 0 + } + } +} + +// 27-D11: pHYs from the dpi, and text chunks with the PNG specification's +// keywords. +export function screenshotChunks( + snapshot: Pick, + frame: ScreenshotSize, + options: Pick, + file: Omit, + createdAt: Date, +): readonly PngChunk[] { + return [ + pngPhysChunk(options.dpi), + pngTextChunk('Software', file.software), + ...(file.source === null ? [] : [pngTextChunk('Source', file.source)]), + pngTextChunk( + 'Description', + screenshotDescription(snapshot, frame, options, file.zPlane), + ), + pngTextChunk('Creation Time', createdAt.toISOString()), + ] +} + +// "x 1200 to 3400 µm, y 800 to 2100 µm; 0.085 µm per pixel; 2× scale", in +// Latin-1 so it fits a tEXt chunk. +export function screenshotDescription( + snapshot: Pick, + frame: ScreenshotSize, + options: Pick, + zPlane: number | null, +): string { + const bbox = morphologyViewportBbox(snapshot.viewState, frame) + const unit = snapshot.unitLabel + const value = (number: number) => + number.toLocaleString('en', { maximumFractionDigits: 1, useGrouping: false }) + const parts = [ + `x ${value(bbox.minX)} to ${value(bbox.maxX)} ${unit}, y ${value(bbox.minY)} to ${value(bbox.maxY)} ${unit}`, + `${String(Number(screenshotUnitsPerPixel(snapshot.viewState.zoom, options.scale).toPrecision(3)))} ${unit} per pixel`, + `${options.scale.toString()}× scale`, + ] + if (zPlane !== null) parts.push(`z plane ${zPlane.toString()}`) + return parts.join('; ') +} + +function createCanvasElement(width: number, height: number): HTMLCanvasElement { + const canvas = document.createElement('canvas') + canvas.width = width + canvas.height = height + return canvas +} + +// The SVG drawn over the whole PNG through an image, as svgPngBlob does. +async function drawSvg( + context: CanvasRenderingContext2D, + svg: string, + frame: ScreenshotSize, + size: ScreenshotSize, +): Promise { + const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' })) + + try { + const image = new Image() + image.width = frame.width + image.height = frame.height + image.src = url + await image.decode() + context.drawImage(image, 0, 0, size.width, size.height) + } finally { + URL.revokeObjectURL(url) + } +} + +async function canvasPng(canvas: HTMLCanvasElement): Promise { + const blob = await new Promise((resolve, reject) => { + canvas.toBlob((result) => { + if (result === null) reject(new Error('The PNG could not be written.')) + else resolve(result) + }, 'image/png') + }) + return new Uint8Array(await blob.arrayBuffer()) +} + +function nextTask(): Promise { + return new Promise((resolve) => { + setTimeout(resolve, 0) + }) +} diff --git a/src/features/screenshot/screenshotRunner.test.ts b/src/features/screenshot/screenshotRunner.test.ts new file mode 100644 index 00000000..1cbbf4d6 --- /dev/null +++ b/src/features/screenshot/screenshotRunner.test.ts @@ -0,0 +1,220 @@ +import { describe, expect, it, vi } from 'vitest' +import { ScreenshotImageError } from './screenshotImage' +import type { ScreenshotInclude } from './screenshotOverlay' +import type { ScreenshotSnapshot } from './screenshotRun' +import { + SCREENSHOT_SETTLE_MS, + ScreenshotRunner, + screenshotProgressText, + screenshotStageText, + type ScreenshotRunState, +} from './screenshotRunner' + +const include: ScreenshotInclude = { + scaleBar: true, + legend: true, + axes: false, + selections: true, +} +const options = { scale: 2 as const, dpi: 300, include, background: 'canvas' as const } +const file = { + fileName: 'run-screenshot.png', + software: 'Spatial Omics Explorer', + source: null, + zPlane: null, +} + +function snapshot(viewChangedAt = -1000): ScreenshotSnapshot { + return { + viewState: { target: [0, 0, 0], zoom: 0, minZoom: -10, maxZoom: 10 }, + viewport: { width: 100, height: 100 }, + image: { channels: [], flatImage: null, opacity: 1 }, + layers: null, + overlays: { scaleBar: null, axes: null, legend: [], selections: [] }, + cells: null, + unitLabel: 'µm', + maxConcurrentTileRequests: 4, + viewChangedAt, + } +} + +function deferred() { + let resolve!: (value: T) => void + let reject!: (error: unknown) => void + const promise = new Promise((onResolve, onReject) => { + resolve = onResolve + reject = onReject + }) + return { promise, resolve, reject } +} + +function states(runner: ScreenshotRunner): ScreenshotRunState[] { + const seen: ScreenshotRunState[] = [] + runner.subscribe(() => { + seen.push(runner.getState()) + }) + return seen +} + +describe('screenshot runner (plan 27, task G)', () => { + it('draws the connected view and saves the PNG', async () => { + const blob = new Blob(['png']) + const draw = vi.fn().mockResolvedValue(blob) + const save = vi.fn() + const runner = new ScreenshotRunner({ draw, save, now: () => 0 }) + const view = snapshot() + runner.connect(() => view) + const seen = states(runner) + + runner.start(options, file) + await vi.waitFor(() => { + expect(runner.getState()).toEqual({ + status: 'saved', + fileName: 'run-screenshot.png', + }) + }) + + expect(draw).toHaveBeenCalledWith(view, options, file, expect.anything()) + expect(save).toHaveBeenCalledWith('run-screenshot.png', blob) + expect(seen[0]).toEqual({ status: 'running', progress: null }) + }) + + it('takes one at a time (D12)', async () => { + const drawing = deferred() + const draw = vi.fn().mockReturnValue(drawing.promise) + const runner = new ScreenshotRunner({ draw, save: vi.fn(), now: () => 0 }) + runner.connect(() => snapshot()) + + runner.start(options, file) + runner.start(options, file) + await vi.waitFor(() => { + expect(draw).toHaveBeenCalledOnce() + }) + drawing.resolve(new Blob()) + }) + + it('waits for the view to keep still before taking it', async () => { + let now = 50 + const sleeps: number[] = [] + const draw = vi.fn().mockResolvedValue(new Blob()) + const runner = new ScreenshotRunner({ + draw, + save: vi.fn(), + now: () => now, + sleep: (ms) => { + sleeps.push(ms) + now += ms + return Promise.resolve() + }, + }) + runner.connect(() => snapshot(0)) + + runner.start(options, file) + await vi.waitFor(() => { + expect(draw).toHaveBeenCalled() + }) + + expect(sleeps).toEqual([SCREENSHOT_SETTLE_MS - 50]) + }) + + it('cancels, and saves nothing', async () => { + const drawing = deferred() + let signal: AbortSignal | undefined + const draw = vi.fn((_view, _options, _file, run: { signal: AbortSignal }) => { + signal = run.signal + return drawing.promise + }) + const save = vi.fn() + const runner = new ScreenshotRunner({ draw, save, now: () => 0 }) + runner.connect(() => snapshot()) + + runner.start(options, file) + await vi.waitFor(() => { + expect(draw).toHaveBeenCalled() + }) + runner.cancel() + drawing.resolve(new Blob()) + await Promise.resolve() + + expect(signal?.aborted).toBe(true) + expect(runner.getState()).toEqual({ status: 'idle' }) + expect(save).not.toHaveBeenCalled() + }) + + it('offers Retry for a tile it could not read, and runs again', async () => { + const draw = vi + .fn() + .mockRejectedValueOnce(new ScreenshotImageError('DAPI', new Error('503'))) + .mockResolvedValueOnce(new Blob()) + const runner = new ScreenshotRunner({ draw, save: vi.fn(), now: () => 0 }) + runner.connect(() => snapshot()) + + runner.start(options, file) + await vi.waitFor(() => { + expect(runner.getState()).toEqual({ + status: 'error', + message: 'A tile of DAPI could not be read: 503', + retryable: true, + }) + }) + + runner.retry() + await vi.waitFor(() => { + expect(runner.getState().status).toBe('saved') + }) + expect(draw).toHaveBeenCalledTimes(2) + }) + + it('fails without Retry for other errors, and when there is no view', async () => { + const draw = vi + .fn() + .mockRejectedValue(new Error('This browser cannot draw a canvas this large.')) + const runner = new ScreenshotRunner({ draw, save: vi.fn(), now: () => 0 }) + + runner.start(options, file) + await vi.waitFor(() => { + expect(runner.getState()).toEqual({ + status: 'error', + message: 'There is no view to save.', + retryable: false, + }) + }) + + runner.connect(() => snapshot()) + runner.start(options, file) + await vi.waitFor(() => { + expect(runner.getState()).toMatchObject({ status: 'error', retryable: false }) + }) + runner.dismiss() + expect(runner.getState()).toEqual({ status: 'idle' }) + }) + + it('cancels when the viewer disconnects', async () => { + const drawing = deferred() + const runner = new ScreenshotRunner({ + draw: vi.fn().mockReturnValue(drawing.promise), + save: vi.fn(), + now: () => 0, + }) + const disconnect = runner.connect(() => snapshot()) + + runner.start(options, file) + disconnect() + + expect(runner.connected).toBe(false) + expect(runner.getState()).toEqual({ status: 'idle' }) + }) + + it('says how far it has got', () => { + expect(screenshotStageText({ stage: 'cells', done: 3, total: 4 })).toBe( + 'Drawing cells', + ) + expect(screenshotProgressText(null)).toBe('Starting') + expect(screenshotProgressText({ stage: 'image', done: 30, total: 120 })).toBe( + 'Reading image tiles · 25%', + ) + expect(screenshotProgressText({ stage: 'writing', done: 119, total: 120 })).toBe( + 'Writing the PNG · 99%', + ) + }) +}) diff --git a/src/features/screenshot/screenshotRunner.ts b/src/features/screenshot/screenshotRunner.ts new file mode 100644 index 00000000..22454570 --- /dev/null +++ b/src/features/screenshot/screenshotRunner.ts @@ -0,0 +1,199 @@ +import { downloadBlob } from '../app-shell/appRuntimeModel' +import { isAbortError } from '../../utils/abort' +import { ScreenshotImageError } from './screenshotImage' +import { + drawScreenshot, + type DrawScreenshotOptions, + type ScreenshotFileInfo, + type ScreenshotOptions, + type ScreenshotProgress, + type ScreenshotSnapshot, +} from './screenshotRun' + +// Runs screenshots (plan 27, task G), one at a time. App makes one runner +// and hands it to ViewerCore, which connects the snapshot of its view, and to +// the top bar's popover, which starts, cancels and retries it. The snapshot +// and the PNG stay in the runner's fields, out of React props. + +export type ScreenshotRunState = + | { readonly status: 'idle' } + | { readonly status: 'running'; readonly progress: ScreenshotProgress | null } + | { + readonly status: 'error' + readonly message: string + // A tile that could not be read: Retry reads it again. + readonly retryable: boolean + } + | { readonly status: 'saved'; readonly fileName: string } + +export type ScreenshotSource = () => ScreenshotSnapshot | null + +const IDLE: ScreenshotRunState = { status: 'idle' } +// The view has kept still this long before its snapshot is taken (27, +// step 1), as the render cap waits before it draws the settled view. +export const SCREENSHOT_SETTLE_MS = 200 + +interface ScreenshotRequest { + readonly options: ScreenshotOptions + readonly file: ScreenshotFileInfo +} + +export interface ScreenshotRunnerOptions { + readonly draw?: typeof drawScreenshot + readonly drawOptions?: Omit + readonly save?: (fileName: string, blob: Blob) => void + readonly now?: () => number + readonly sleep?: (ms: number) => Promise +} + +export class ScreenshotRunner { + private source: ScreenshotSource | null = null + private state: ScreenshotRunState = IDLE + private readonly listeners = new Set<() => void>() + private controller: AbortController | null = null + private lastRequest: ScreenshotRequest | null = null + + constructor(private readonly runnerOptions: ScreenshotRunnerOptions = {}) {} + + // ViewerCore's view; the returned function disconnects it. + connect(source: ScreenshotSource): () => void { + this.source = source + this.notify() + return () => { + if (this.source !== source) return + this.source = null + this.cancel() + this.notify() + } + } + + get connected(): boolean { + return this.source !== null + } + + // The view as it is now, for the popover's size line and notes. + preview(): ScreenshotSnapshot | null { + return this.source?.() ?? null + } + + readonly subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener) + return () => { + this.listeners.delete(listener) + } + } + + readonly getState = (): ScreenshotRunState => this.state + + start(options: ScreenshotOptions, file: ScreenshotFileInfo): void { + if (this.state.status === 'running') return + this.lastRequest = { options, file } + void this.run({ options, file }) + } + + // Starts the last screenshot again, with new tile caches. + retry(): void { + if (this.lastRequest === null || this.state.status === 'running') return + void this.run(this.lastRequest) + } + + cancel(): void { + if (this.controller === null) return + this.controller.abort() + this.controller = null + this.setState(IDLE) + } + + // Clears a message once it has been read. + dismiss(): void { + if (this.state.status === 'error' || this.state.status === 'saved') { + this.setState(IDLE) + } + } + + private async run(request: ScreenshotRequest): Promise { + const controller = new AbortController() + this.controller = controller + this.setState({ status: 'running', progress: null }) + const current = () => this.controller === controller + + try { + const snapshot = await this.settledSnapshot(controller.signal) + const blob = await (this.runnerOptions.draw ?? drawScreenshot)( + snapshot, + request.options, + request.file, + { + ...this.runnerOptions.drawOptions, + signal: controller.signal, + onProgress: (progress) => { + if (current()) this.setState({ status: 'running', progress }) + }, + }, + ) + if (!current()) return + ;(this.runnerOptions.save ?? downloadBlob)(request.file.fileName, blob) + this.controller = null + this.setState({ status: 'saved', fileName: request.file.fileName }) + } catch (error) { + if (!current()) return + this.controller = null + if (isAbortError(error)) { + this.setState(IDLE) + return + } + this.setState({ + status: 'error', + message: error instanceof Error ? error.message : String(error), + retryable: error instanceof ScreenshotImageError, + }) + } + } + + // The view once it has kept still for SCREENSHOT_SETTLE_MS. + private async settledSnapshot(signal: AbortSignal): Promise { + const now = this.runnerOptions.now ?? (() => performance.now()) + const sleep = this.runnerOptions.sleep ?? sleepMs + + for (;;) { + signal.throwIfAborted() + const snapshot = this.source?.() ?? null + if (snapshot === null) throw new Error('There is no view to save.') + const wait = SCREENSHOT_SETTLE_MS - (now() - snapshot.viewChangedAt) + if (wait <= 0) return snapshot + await sleep(wait) + } + } + + private setState(state: ScreenshotRunState): void { + this.state = state + this.notify() + } + + private notify(): void { + for (const listener of [...this.listeners]) listener() + } +} + +function sleepMs(ms: number): Promise { + return new Promise((resolve) => { + setTimeout(resolve, ms) + }) +} + +// "Reading image tiles", "Drawing cells" or "Writing the PNG", for the +// loading list, which shows how far it has got beside it. +export function screenshotStageText(progress: ScreenshotProgress | null): string { + if (progress === null) return 'Starting' + return progress.stage === 'image' + ? 'Reading image tiles' + : progress.stage === 'cells' + ? 'Drawing cells' + : 'Writing the PNG' +} + +// The stage and how far it has got, for the popover. +export function screenshotProgressText(progress: ScreenshotProgress | null): string { + if (progress === null) return 'Starting' + return `${screenshotStageText(progress)} · ${Math.floor((progress.done / Math.max(1, progress.total)) * 100).toString()}%` +} diff --git a/src/features/shell/TopBar.tsx b/src/features/shell/TopBar.tsx index 3374b9d5..2dde5373 100644 --- a/src/features/shell/TopBar.tsx +++ b/src/features/shell/TopBar.tsx @@ -29,6 +29,7 @@ import { Tooltip, } from '../../components/ui' import { withMicrometers } from '../../data/units' +import { ScreenshotButton } from '../screenshot/ScreenshotButton' import { isTextEntryTarget, type ActiveTool } from '../app-shell/activeToolModel' import { BoundaryLimitField, OpenDatasetForm } from '../sections/DatasetInfoBlocks' import type { DatasetInfoModel, OpenDatasetModel } from '../sections/datasetInfoModel' @@ -177,6 +178,9 @@ export function TopBar({ ) : ( )} + {model.screenshot === null ? null : ( + + )} void + // The Screenshot button's popover (plan 27); null hides the button. + readonly screenshot: ScreenshotModel | null } // The chip says what is open, and while a dataset loads, which one. It is @@ -174,6 +177,7 @@ export interface TopBarModelInput { readonly onReturnToPan: () => void readonly onRoiModeChange: (mode: RoiDrawMode) => void readonly platform: AppPlatformKind + readonly screenshot?: ScreenshotModel | null readonly setDebugMode: (enabled: boolean) => void } @@ -202,6 +206,7 @@ export function useTopBarModel({ onReturnToPan, onRoiModeChange, platform, + screenshot = null, setDebugMode, }: TopBarModelInput): TopBarModel { const options = toolOptions({ @@ -272,5 +277,6 @@ export function useTopBarModel({ setDebugMode(enabled) appendDebugEvent(enabled ? 'Debug info shown' : 'Debug info hidden') }, + screenshot, } } diff --git a/src/rendering/morphologyCanvas.ts b/src/rendering/morphologyCanvas.ts index 903454ef..6b6df839 100644 --- a/src/rendering/morphologyCanvas.ts +++ b/src/rendering/morphologyCanvas.ts @@ -59,7 +59,7 @@ export function drawMorphologyTiles( context.clearRect(0, 0, viewport.width, viewport.height) for (const tile of tiles) { - drawReadyTile(context, tile, viewState, viewport) + drawReadyTile(context, tile, viewState, viewport, globalThis.devicePixelRatio || 1) } } @@ -70,11 +70,24 @@ export function drawMorphologyTileChannels( viewport: CssViewportSize, ): void { context.clearRect(0, 0, viewport.width, viewport.height) + addMorphologyTileChannels(context, batches, viewState, viewport) +} +// Draws the batches' tiles over what the context holds. Channels add, and a +// single RGB channel's tiles do not overlap, so tiles can be drawn in any +// order, as a screenshot draws them as they arrive (plan 27). `pixelRatio` +// is device pixels per unit of `viewport`. +export function addMorphologyTileChannels( + context: CanvasRenderingContext2D, + batches: readonly MorphologyChannelTileBatch[], + viewState: OverviewViewState, + viewport: CssViewportSize, + pixelRatio = globalThis.devicePixelRatio || 1, +): void { if (batches.length === 1 && isWhite(batches[0]?.color)) { for (const tile of batches[0]?.tiles ?? []) { context.globalAlpha = batches[0]?.opacity ?? 1 - drawReadyTile(context, tile, viewState, viewport, batches[0]?.placement) + drawReadyTile(context, tile, viewState, viewport, pixelRatio, batches[0]?.placement) } context.globalAlpha = 1 return @@ -85,7 +98,7 @@ export function drawMorphologyTileChannels( context.globalCompositeOperation = 'lighter' for (const tile of batch.tiles) { - drawReadyTile(context, tile, viewState, viewport, batch.placement) + drawReadyTile(context, tile, viewState, viewport, pixelRatio, batch.placement) } } @@ -188,6 +201,7 @@ function drawReadyTile( tile: ReadyTile, viewState: OverviewViewState, viewport: CssViewportSize, + pixelRatio: number, placement?: ImageFramePlacement, ): void { const target = bboxTargetRect( @@ -201,11 +215,7 @@ function drawReadyTile( } if (placement === undefined || isUnflippedPlacement(placement)) { - context.imageSmoothingQuality = tileSmoothingQuality( - tile, - target, - globalThis.devicePixelRatio || 1, - ) + context.imageSmoothingQuality = tileSmoothingQuality(tile, target, pixelRatio) context.drawImage( tile.image, 0, @@ -230,7 +240,7 @@ function drawReadyTile( context.imageSmoothingQuality = tileSmoothingQuality( tile, { width, height }, - globalThis.devicePixelRatio || 1, + pixelRatio, ) context.save() context.translate(target.x + target.width / 2, target.y + target.height / 2) diff --git a/src/styles/shell.css b/src/styles/shell.css index f25d638a..89b724b7 100644 --- a/src/styles/shell.css +++ b/src/styles/shell.css @@ -1124,10 +1124,11 @@ color: var(--accent); } -/* The names take about 400 px with Share, Help and Settings, which the bar's - right side has from 1100 px, with the Measure options showing too; below - that only the icons show, and the names are still read. */ -@media (max-width: 1099.98px) { +/* The names take about 400 px with Screenshot's camera, Share, Help and + Settings, which the bar's right side has from 1180 px, with the Measure + options showing too and in a wide fallback font; below that only the + icons show, and the names are still read. */ +@media (max-width: 1179.98px) { .shell-panel-toggle.ui-button { width: 28px; padding: 0; @@ -1167,6 +1168,120 @@ display: none; } +/* Screenshot's name takes about 115 px more, which the bar has from 1340 px + beside the panel names; below that only the camera shows, and the name + is still read. */ +@media (max-width: 1339.98px) { + .shell-screenshot-trigger.ui-button { + width: 28px; + padding: 0; + } + + .shell-screenshot-label { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; + } +} + +/* Screenshot (plan 27-D1): its options, size and progress. */ +.shell-screenshot { + width: 320px; +} + +.shell-screenshot-row { + display: flex; + gap: var(--space-2); + align-items: center; + justify-content: space-between; +} + +/* Background's names need the popover's width. */ +.shell-screenshot-row.is-stacked { + display: grid; + gap: var(--space-1); +} + +.shell-screenshot-row.is-stacked .ui-segmented { + display: grid; +} + +.shell-screenshot-size, +.shell-screenshot-note { + margin: 0; + color: var(--text-2); + font-size: var(--font-control); + font-variant-numeric: tabular-nums; +} + +.shell-screenshot-include { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0 var(--space-2); + margin: 0; + padding: 0; + border: 0; +} + +.shell-screenshot-include legend { + margin-bottom: var(--space-1); + padding: 0; +} + +/* Rows 24 px high, so each box is a 24 px target (WCAG 2.5.8). */ +.shell-screenshot-include .ui-checkbox { + min-height: 24px; +} + +.shell-screenshot-notes { + display: grid; + gap: var(--space-1); + margin: 0; + padding: var(--space-2); + border: 1px solid var(--warning-border); + border-radius: var(--radius-2); + background: var(--warning-soft); + color: var(--text-1); + font-size: var(--font-control); + list-style: none; +} + +.shell-screenshot-progress { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: var(--space-1) var(--space-2); + align-items: center; + font-size: var(--font-control); +} + +.shell-screenshot-progress progress { + grid-column: 1 / -1; + width: 100%; + accent-color: var(--accent); +} + +.shell-screenshot-error { + display: grid; + gap: var(--space-1); + justify-items: start; +} + +.shell-screenshot-error p, +.shell-screenshot-ask { + margin: 0; + color: var(--danger); + font-size: var(--font-control); +} + +.shell-screenshot-actions { + display: flex; + gap: var(--space-2); + justify-content: flex-end; +} + .shell-shortcuts { display: grid; gap: var(--space-3); diff --git a/src/test/sectionModels.ts b/src/test/sectionModels.ts index e63c5351..0c23d866 100644 --- a/src/test/sectionModels.ts +++ b/src/test/sectionModels.ts @@ -420,6 +420,7 @@ export function testTopBarModel( return { datasetName: 'Sob23 brain', summary: { status: 'ready', text: 'Xenium · 1.41 M cells · 5,001 genes' }, + screenshot: null, magicLens: { radiusMicrometers: 80, onRadiusChange: vi.fn(), diff --git a/tests/e2e/app.spec.ts b/tests/e2e/app.spec.ts index e0b0c2ea..6e5845bb 100644 --- a/tests/e2e/app.spec.ts +++ b/tests/e2e/app.spec.ts @@ -544,6 +544,11 @@ test('has no accessibility violations beyond the axe baseline @smoke', async ({ }) await checkEachPlace('H5AD fixture with a gene selected') + // The Screenshot popover (plan 27). + await page.getByRole('button', { name: 'Screenshot' }).click() + await collectAxeFindings(page, 'H5AD fixture, screenshot', findings) + await page.keyboard.press('Escape') + // The dot plot and its table (plan 22-I). const clusters = await openControls(page, 'clusters') await clusters.getByLabel('Annotation set').selectOption({ label: 'cluster' }) @@ -2366,6 +2371,132 @@ test('draws an imported label mask and WKT outlines over an image @smoke', async await expect(page).toHaveURL(/segmentation=.*cells\.csv/) }) +// Plan 27: a 2× PNG of an image with outlines over it, with its dpi and text +// chunks, that looks as the screen does. +test('saves a 2× screenshot of the view that matches the screen @smoke', async ({ + page, + baseURL, +}) => { + const webglContexts = await trackWebglContexts(page) + await routeRangeFiles(page, '/screenshot-smoke', { + // Bright on the left, dark on the right, so a misplaced image shows. + 'slide.tif': tinyTiff(64, 64, 8, (x, y) => (x < 32 ? 200 : 20 + ((x + y) % 16))), + 'cells.csv': Buffer.from( + 'cell_id,geometry\na,"POLYGON ((8 8, 56 8, 56 56, 8 56, 8 8))"\n', + ), + }) + const folder = new URL('/screenshot-smoke/', baseURL).toString() + await page.goto( + `/#dataset=${encodeURIComponent(`${folder}slide.tif`)}&segmentation=${encodeURIComponent(`${folder}cells.csv`)}&panel=segmentation`, + ) + await expect(page.locator('[data-layer-section="segmentation"]')).toContainText( + '1 outline drawn.', + { timeout: H5AD_LOAD_TIMEOUT_MS }, + ) + // The view keeps still, with its image drawn. + await page.waitForTimeout(1_000) + const frame = page.getByRole('img', { name: 'Spatial viewer canvas area' }) + const box = await frame.boundingBox() + if (box === null) throw new Error('The view has no box.') + const screen = await frame.screenshot() + + await page.getByRole('button', { name: 'Screenshot' }).click() + const dialog = page.getByRole('dialog', { name: /high-resolution PNG/ }) + await expect(dialog.getByRole('button', { name: '2×' })).toHaveAttribute( + 'aria-pressed', + 'true', + ) + // Only the map, to compare with the screen. + for (const mark of ['Scale bar', 'Legend', 'Axes', 'Selections']) { + await dialog.getByRole('checkbox', { name: mark }).uncheck() + } + const downloading = page.waitForEvent('download') + await dialog.getByRole('button', { name: 'Save PNG' }).click() + const download = await downloading + expect(download.suggestedFilename()).toBe('slide-screenshot.png') + await expect(dialog.getByText('Saved slide-screenshot.png.')).toBeVisible() + // The screenshot's Deck gave its WebGL context back once it left the + // page, so the view keeps its own and counts no loss. + await expect.poll(async () => (await webglContexts()).live).toBe(1) + expect((await webglContexts()).lostOnPage).toBe(0) + const png = await readFile(await download.path()) + + const chunks = pngChunks(png) + expect(chunks.map((chunk) => chunk.type).slice(0, 2)).toEqual(['IHDR', 'pHYs']) + expect([chunks[0]?.data.readUInt32BE(0), chunks[0]?.data.readUInt32BE(4)]).toEqual([ + Math.round(box.width) * 2, + Math.round(box.height) * 2, + ]) + // 300 dpi is 11,811 pixels per metre. + expect(chunks[1]?.data.readUInt32BE(0)).toBe(11_811) + const text = Object.fromEntries( + chunks + .filter((chunk) => chunk.type === 'tEXt') + .map((chunk) => { + const nul = chunk.data.indexOf(0) + return [ + chunk.data.subarray(0, nul).toString('latin1'), + chunk.data.subarray(nul + 1).toString('latin1'), + ] + }), + ) + expect(text.Software).toMatch(/^Spatial Omics Explorer/) + expect(text.Source).toBe(`${folder}slide.tif`) + expect(text.Description).toMatch(/µm per pixel; 2× scale$/) + expect(text['Creation Time']).toMatch(/^\d{4}-\d\d-\d\dT/) + + // Halved, the PNG is the screen: the image in place and the outline over + // it. The middle of the view leaves out the readouts and the minimap. + const difference = await page.evaluate( + async ({ pngBase64, screenBase64 }) => { + const decode = (base64: string) => + createImageBitmap( + new Blob([Uint8Array.from(atob(base64), (char) => char.charCodeAt(0))]), + ) + const [saved, shown] = await Promise.all([decode(pngBase64), decode(screenBase64)]) + const pixels = (image: ImageBitmap) => { + const canvas = document.createElement('canvas') + canvas.width = shown.width + canvas.height = shown.height + const context = canvas.getContext('2d') + if (context === null) throw new Error('No 2D canvas.') + context.drawImage(image, 0, 0, shown.width, shown.height) + return context.getImageData( + Math.floor(shown.width * 0.25), + Math.floor(shown.height * 0.25), + Math.floor(shown.width * 0.5), + Math.floor(shown.height * 0.5), + ).data + } + const [a, b] = [pixels(saved), pixels(shown)] + let total = 0 + let largest = 0 + for (let index = 0; index < a.length; index += 4) { + for (let channel = 0; channel < 3; channel += 1) { + const delta = Math.abs((a[index + channel] ?? 0) - (b[index + channel] ?? 0)) + total += delta + largest = Math.max(largest, delta) + } + } + return { mean: total / ((a.length / 4) * 3), largest } + }, + { pngBase64: png.toString('base64'), screenBase64: screen.toString('base64') }, + ) + expect(difference.mean).toBeLessThan(6) +}) + +function pngChunks(png: Buffer): { readonly type: string; readonly data: Buffer }[] { + const chunks: { type: string; data: Buffer }[] = [] + for (let offset = 8; offset + 12 <= png.length; ) { + const length = png.readUInt32BE(offset) + const type = png.subarray(offset + 4, offset + 8).toString('latin1') + chunks.push({ type, data: png.subarray(offset + 8, offset + 8 + length) }) + offset += 12 + length + if (type === 'IEND') break + } + return chunks +} + test('loads a CELLxGENE Visium H5AD with uns/spatial as spots over its H&E @live', async ({ page, }) => { @@ -2857,6 +2988,42 @@ test('draws Xenium nucleus boundaries without reading cell outlines @live', asyn await expect(page.locator('.viewport-message-error')).toHaveCount(0) }) +// Plan 27: a 4× PNG of the whole slide draws every one of its 1.4 million +// cells, not the screen's sample, and reads the image at its scale. +test('saves a 4× screenshot of the whole Xenium slide @live', async ({ + page, +}, testInfo) => { + test.setTimeout(300_000) + + await page.goto(`/#xv=2&dataset=${encodeURIComponent(XENIUM_DEMO_URL)}`) + await expect( + page.getByRole('status').filter({ hasText: /Xenium · 1\.41 M cells/ }), + ).toBeVisible({ timeout: XENIUM_LOAD_TIMEOUT_MS }) + await page.getByRole('button', { name: 'Screenshot' }).click() + const dialog = page.getByRole('dialog', { name: /high-resolution PNG/ }) + await dialog.getByRole('button', { name: '4×' }).click() + await expect(dialog).toContainText(/Draws all 1,414,155 cells in view/) + + const startedAt = Date.now() + const downloading = page.waitForEvent('download', { timeout: 240_000 }) + await dialog.getByRole('button', { name: /Save PNG|and save/ }).click() + const download = await downloading + testInfo.annotations.push({ + type: 'Time to a 4× PNG', + description: `${((Date.now() - startedAt) / 1000).toFixed(1)} s from Save PNG`, + }) + const png = await readFile(await download.path()) + const box = await page + .getByRole('img', { name: 'Spatial viewer canvas area' }) + .boundingBox() + // IHDR's width and height. + expect([png.readUInt32BE(16), png.readUInt32BE(20)]).toEqual([ + Math.round(box?.width ?? 0) * 4, + Math.round(box?.height ?? 0) * 4, + ]) + await expect(page.locator('.screenshot-deck-host')).toHaveCount(0) +}) + test('draws STHELAR nuclei over its axis-swapped and flipped H&E @live', async ({ page, }) => {