Skip to content

PNG export, clipboard copy and a right-click save menu - #67

Open
CSSFrancis wants to merge 1 commit into
mainfrom
feat/png-export
Open

PNG export, clipboard copy and a right-click save menu#67
CSSFrancis wants to merge 1 commit into
mainfrom
feat/png-export

Conversation

@CSSFrancis

@CSSFrancis CSSFrancis commented Sep 4, 2026

Copy link
Copy Markdown
Owner

Why

exportPNG has composited a full figure PNG for a while, but nothing could
reach it — it is exposed only on mount()'s handle, the postMessage protocol,
or Playwright, and anywidget discards render()'s return value. No Python entry
point, no UI, undocumented.

What

Hover a figure for a badge in its corner, or right-click any plot (gutters
and colourbar included — the overlay canvas does not cover those):

  • This panel — Copy image Ctrl+C, Save PNG, Save full view, Save at native resolution
  • Whole figure — Copy, Save PNG, Save full view
  • Theme — Current / Light / Dark, sticky per figure

The badge matters because JupyterLab, PyCharm and VS Code install their own
contextmenu and keyboard handlers and may swallow a right-click or Cmd+C
before the figure sees it. A test installs a capture-phase contextmenu
swallower, asserts right-click is dead, then asserts the badge still works.
The badge is revealed by real pointer movement, not mouseenter, so hover
chrome cannot leak into the visual baselines or the gallery thumbnails.

fig.savefig("paper.png", theme="light", scale=2)
fig.savefig("data.png", source="native", panel=plot)   # 1:1 with the data

Hosts add their own formats with handle.registerExportAction(...).

source Output
view As displayed — zoom, pan, contrast
full Whole data extent at panel resolution
native One output pixel per data pixel, decorations redrawn at that size

Two save entries. Save PNG… downloads with no permission prompt.
Save as… opens a real system dialog via showSaveFilePicker — listed only
where the browser supports it, because it hands the page a persistent writable
handle
and so costs Chrome's "this site can see edits you make" prompt. Too
much for a plain save; right when the user asked to choose a folder.

A dialog the user closed and one that never opened both reject with
AbortError, so the name cannot separate them — one that never rendered comes
back in well under 250 ms, which is the discriminator. Without that, Save would
silently do nothing in headless and in webviews that stub the API.

panelId changes only the origin and extent, so a panel export is exactly the
matching sub-rectangle of the figure export. Theme swap, view reset, native
resize, composite and restore all run in one synchronous task, so no
intermediate state paints.

Why native cannot come from the browser

tile='auto' is the default and TILE_THRESHOLD is 1024, so every image
large enough to want a native export is tiled
, and the page holds only a
downsampled overview. savefig re-encodes the backend at full resolution into
the snapshot; the menu disables that entry and says why. The test uses a
one-pixel stripe pattern the averaging overview renders flat — a ramp does not
discriminate, since at 1200 px it has only 256 grey levels.

Rasterising in Python was rejected once decorations became a requirement: the
LUT, gutter geometry and label engine would all have to be reimplemented, and
would drift.

Bugs fixed

  • Key handlers ignored modifiers: Ctrl+C toggled the colourbar, Cmd+S
    flipped the colour scale to symlog
    .
  • exportPNG mixed CSS-scaled rects with an unscaled extent, so a figure shrunk
    to fit a narrow cell composited into the top-left corner.
  • Browser view state was never read back into Python, so save_html,
    to_html and figure_state silently reset the reader's zoom and pan
    .

Notes

47 new Playwright tests, no new baselines — exact sizes, known-LUT probes and
the literal _makeTheme constants. No gallery example: a menu and a keystroke
do not show in a static thumbnail. At native resolution decorations keep their
normal point sizes, so an 11 px tick label is small against a 4096 px image;
decoration_scale is the obvious follow-up.

@codecov-commenter

codecov-commenter commented Sep 4, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.94161% with 22 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.86%. Comparing base (c1e8c36) to head (c682ca5).

Files with missing lines Patch % Lines
anyplotlib/_export.py 82.75% 20 Missing ⚠️
anyplotlib/figure/_figure.py 89.47% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #67      +/-   ##
==========================================
+ Coverage   90.85%   90.86%   +0.01%     
==========================================
  Files          40       41       +1     
  Lines        4603     4709     +106     
==========================================
+ Hits         4182     4279      +97     
- Misses        421      430       +9     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@CSSFrancis
CSSFrancis force-pushed the feat/png-export branch 4 times, most recently from 990d748 to f2f630a Compare September 4, 2026 15:48
The renderer already composited a complete figure PNG — `exportPNG` — but it
was reachable only from `mount()`'s handle, the standalone-HTML postMessage
protocol, or Playwright. Under plain anywidget nothing captures `render()`'s
return value, so a Jupyter kernel could not reach it at all, and there was no
Python entry point and no UI.

Right-clicking a plot now offers Copy image, Save PNG…, Save full view… and
Save at native resolution… for the clicked panel, the same for the whole
figure, and a sticky light/dark choice that applies to all of them. Ctrl/Cmd+C
copies the plot under the cursor, or the figure when none is hovered.
`Figure.savefig(path, source=, theme=, scale=, panel=)` does the same from
Python, rendering through the real JavaScript renderer in a headless browser so
the file is what the figure actually looks like — including the zoom and
contrast set interactively. Embedding hosts add their own formats through
`handle.registerExportAction({id, label, scope, handler})`.

`exportPNG` gained `panelId`, `source` and `theme`. `panelId` changes only the
origin and the extent, so a panel export is by construction the matching
sub-rectangle of the figure export. `source='full'` transiently resets the view
— and clears the detail tile, without which `_blit2d` stretches a sub-region
over the whole fit-rect. `source='native'` resizes the panel so its image area
is the data resolution and redraws the decorated stack, so the axes, colourbar,
title, markers and widgets come along with it; `p._dprOv = 1` keeps the backing
store in exact data pixels. The whole pipeline runs in one synchronous task, so
the browser never paints an intermediate state and nothing flickers.

Native export cannot work from the browser for a tiled plot: `tile='auto'` is
the default and `TILE_THRESHOLD` is 1024, so any image large enough to want it
holds only a downsampled overview plus one detail tile. The menu shows that
entry disabled with the reason; `savefig` re-encodes the backend at full
resolution into the snapshot and runs the same render headless, leaving the
live figure untouched.

Three pre-existing bugs are fixed here, because the menu makes each reachable:

- Panel key handlers matched bare letters without checking modifiers, so Ctrl+C
  toggled the colourbar and Cmd+S flipped the colour scale to symlog.
- `exportPNG` mixed CSS-scaled element rects with an unscaled extent, so a
  figure shrunk to fit a narrow cell composited into the top-left corner.
- Nothing read the browser's view state back into Python, so `save_html`,
  `to_html` and `figure_state` silently reset the reader's zoom and pan.

Does not add an `Examples/` gallery entry — a right-click menu and a keystroke
do not appear in a static thumbnail. At native resolution the decorations keep
their normal point sizes, so an 11 px tick label is small against a 4096 px
image; raising `title_size` / `tick_size` / `*_label_size` is the workaround.

47 new Playwright tests and no new golden baselines: assertions use exact
sizes, known-LUT pixel probes and the literal `_makeTheme` constants.

Assisted-by: Claude Opus 5 (1M context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants