Skip to content

fix(macos): copying to the clipboard no longer keeps every image in memory - #18

Merged
CubityFirst merged 1 commit into
CubityFirst:mainfrom
Delitefully:fix/clipboard-memory-leak
Nov 24, 2026
Merged

CubityFirst merged 1 commit into
CubityFirst:mainfrom
Delitefully:fix/clipboard-memory-leak

Conversation

@Delitefully

Copy link
Copy Markdown
Contributor

On macOS, every image snapr copies to the clipboard stays in memory until snapr quits. With copy-to-clipboard on, that's about twice the screenshot's size per capture. A snapr 0.3.5 that had been running for 10 days was at a 1.7 GB footprint (2.4 GB at peak).

The cause is the output thread. It does every clipboard write for as long as snapr runs, but it has no run loop, so nothing ever drains its autorelease pool. arboard's set_image doesn't open a pool of its own; its reads do. So what AppKit autoreleases while writing the image piles up in that pool:

  • the NSBitmapImageRep / CGImage holding the pixels;
  • the pasteboard's encoded copy of the image, a dispatch_data_t in a Foundation VM region.

Now each clipboard write in output.rs (image, text and file) runs in its own pool on macOS. Other platforms are unchanged.

Proof:

  • The running app. leaks -autoreleasePools on that process shows one thread whose pool starts with the NSPasteboard, followed by 169 copied images. 512 MB of pixels is held only by that pool. leaks -referenceTree='VM:.*Foundation.*' roots another 692 MB of encoded pasteboard data in the same pool. leaks finds only 70 KB of true leaks, so this is memory still referenced, not memory forgotten.
  • A scratch repro. It runs arboard 3.6.1's set_image 20 times with a 2000×1500 image on a thread that stays alive, as the output thread does. Without a pool it reaches 494 MB and stays at 493 MB 15 s later. With one it settles to 40 MB, and it keeps falling as the allocator hands back freed memory. The repro was a scratch test, not committed.

cargo clippy --locked --all-targets -- -D warnings and cargo test --locked pass on macOS.

…emory

The output thread copies to the clipboard for as long as snapr runs, but
it has no run loop, so nothing drained its autorelease pool. Each image
copied left its pixels and the pasteboard's encoded copy in that pool
until snapr quit: about twice the screenshot's size per copy, over a
gigabyte after a few days of use. Each clipboard write now runs in its
own pool.
@CubityFirst
CubityFirst merged commit 538d226 into CubityFirst:main Nov 24, 2026
4 checks passed
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