the clipboard
Unlike how it might seem at first glance, clipboards work in a much more complicated way than simply copying a chunk of data to memory.
In the Linux desktop world, the compositor/display server is responsible for implementing the clipboard mechanism. We’ll focus on Wayland here, but it’s more or less the same on X11.
First, let’s take a look at the structure of the clipboard.
You’ve probably noticed this before: you copy content from a webpage, paste it into a rich text editor or a document processor like LibreOffice Writer, and it keeps the styles, headings, links, and everything else that was there. But then you paste the same thing into a plain text editor or a terminal, and suddenly it’s just plain text; no styling, no markdown, nothing extra.
So which one is right? Is the plain text editor silently stripping the styling?
Actually, both versions are there the whole time. Your clipboard isn’t a single string, it’s an array of entries, and each entry has an associated MIME type. Applications can list the MIME types available in the clipboard and read whichever one they support.
Let’s see it in action. Copy something from your browser and run wl-paste -l in your terminal. Here’s what I got after copying something from a webpage in Firefox:
~ wl-paste -l
text/x-moz-url-priv
text/plain
text/plain;charset=utf-8
STRING
text/plain
TEXT
COMPOUND_TEXT
UTF8_STRING
text/plain;charset=utf-8
text/_moz_htmlinfo
text/_moz_htmlcontext
text/html
So all of that is sitting in my clipboard at once, in all these different formats, and each application picks whichever type suits it best when pasting.
But is all that content, in every one of those formats, actually written to memory the moment you copy it? Big fat NO.
And that’s the interesting part: the clipboard behaves a lot like a mutex; it has an owner, and only one owner at a time. When you copy something in an application, that app claims ownership of the clipboard and promises to provide all those content types on request. Then, when you paste into another app, the two applications communicate through a channel, and the owning app sends over the data, but only in the one MIME type the pasting app asked for.
I had a thought: every time you paste, it’s the owner app’s job to hand over the data, right? But who guarantees it hands over the same data every time?
No one.
Which means you could build an app that claims ownership of the clipboard and, every time you paste, returns something different, a random string, the current time, whatever you want.
I asked Claude to make a PoC of that, feel free to test it yourself. github.com/ahgilak/clipserv
There were some difficulties implementing this on GNOME, since GNOME tries to prevent clipboard hijacking by a process the user hasn’t directly interacted with. But a few tricks got it working :)