8000 GitHub - jimpark/clipout: A cross-platform clipboard extraction tool. · GitHub
[go: up one dir, main page]

Skip to content
jimparkPublic

About

A cross-platform clipboard extraction tool.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

8 Commits

Folders and files

Repository files navigation

clipout

Enumerate the data flavors currently held on the system clipboard and extract the raw bytes of any one of them.

Clipboard contents are richer than any single application reveals. A paragraph copied from a word processor is typically present simultaneously as plain text, RTF, HTML, and one or more private application formats, each encoding different information. clipout makes that set inspectable and extractable.

It is read-only: it never writes to the clipboard, never becomes a clipboard owner, and never registers as a clipboard viewer.

The design is specified in docs/specification.md; section references throughout the source point back to it.

Status

Platform State
macOS Implemented and exercised against a live pasteboard
Windows Implemented and exercised against live clipboards on Windows 11
Linux Implemented, not yet run against a live selection — see Linux

Build

cargo build --release

Any backend can be type-checked from any host:

cargo check --target x86_64-pc-windows-msvc
cargo check --target x86_64-unknown-linux-gnu

Usage

clipout list [--json] [--item N | --all-items]
clipout get <flavor> [-o FILE] [--item N] [--if-sequence N]
clipout dump -d DIR [--if-sequence N]

list

$ clipout list
SEL  ALIAS  FLAVOR                              SIZE  STATE                       GROUP
@0   rtf    public.rtf                            89  available                   -
@1   -      public.utf16-external-plain-text       -  unavailable (promised)      -
@2   text   public.utf8-plain-text                 -  unavailable (promised)      -

SEL is the selector to pass to get for that row. ALIAS shows which row the short names rtf, html, and text select.

The table is for human consumption; its column widths and layout are not a stable interface. Scripts use --json, which emits the schema of §5.

--item N (default 0) restricts output to one item; --all-items shows every one. macOS pasteboards can hold several items — copying two files in Finder produces two. Windows and Linux always have exactly one.

An empty clipboard exits 0, printing nothing in text mode and an empty items array in JSON mode.

get

clipout get rtf -o paragraph.rtf      # the RTF flavor, on any platform
clipout get @2 -o out.bin             # row @2 of `clipout list`
clipout get 'HTML Format' | xxd       # by flavor ID
clipout get @1 --item 1

Bytes are written verbatim — no encoding conversion, no BOM handling, no line-ending translation, no trailing newline. Diagnostics always go to stderr, so piping stdout to a binary consumer is safe.

The <flavor> argument accepts these forms, tried in order:

  1. @N: the row shown as @N in the SEL column of clipout list.

  2. A native format ID, decimal or 0x-prefixed (Windows only). A bare 2 is format ID 2 (CF_BITMAP), not row 2. Use @2 for the row.

  3. A flavor ID, matched exactly.

  4. An alias: rtf, html, or text. Each selects the platform's own flavor for that content:

    Alias Windows macOS Linux (first present)
    rtf Rich Text Format public.rtf text/rtf, application/rtf, text/richtext
    html HTML Format public.html text/html
    text CF_UNICODETEXT public.utf8-plain-text text/plain;charset=utf-8, UTF8_STRING, text/plain

    text is UTF-16LE with a trailing NUL on Windows and UTF-8 elsewhere. Where several targets are present, an available one wins over an unavailable one.

  5. A flavor ID, matched ignoring case.

A selector matching more than one flavor fails with EAMBIGUOUS and lists the candidates with their @N selectors. It never silently picks the first.

dump

clipout dump -d ./clipboard-dump
clipboard-dump/
├── manifest.json
├── item0/
│   ├── 000-public.utf8-plain-text.bin
│   └── 001-public.html.bin
└── item1/
    └── 000-public.utf8-plain-text.bin

dump is the tool for exploratory work — finding out what an application actually puts on the clipboard — where repeated get invocations would race against clipboard changes. Filenames are sanitized and lossy; manifest.json is the sole authoritative record of the true flavor IDs, and it also records every unavailable flavor with the reason it could not be extracted.

Racing the clipboard

list and get are separate processes, so the clipboard can change between them. list --json reports the current sequence; pass it back to close the window:

seq=$(clipout list --json | jq .sequence)
clipout get public.rtf --if-sequence "$seq" -o out.rtf

Within a single invocation, clipout verifies the sequence before and after reading and fails with ESEQUENCE if the clipboard moved underneath it, so a dump never mixes bytes from two clipboard generations. This matters most on macOS, where nothing locks the pasteboard and every read races independently; on Windows the clipboard is held open across a read, which does most of the work already.

On Linux this guarantee is weaker, and --if-sequence does not exist. X11 and Wayland have no change counter to check, so clipout substitutes a weaker test that catches some changes and not others. See Linux.

Two consequences worth relying on:

  • dump retries. A capture spoiled by clipboard churn is retried up to three times before failing, since someone copying while a dump runs is ordinary. A --if-sequence mismatch is never retried — you asked for a specific generation, and a later one is not a better answer.
  • Races are reported as races. If a read fails and the sequence has moved, the failure is reported as ESEQUENCE rather than as whatever the underlying call complained about. Without this, an application that clears the pasteboard a moment before writing to it makes clipout blame your --item argument for its copy.
  • dump is atomic against clipboard failure. Every payload is read before any file is written, so a dump that fails for a clipboard reason leaves no directory behind. The guarantee does not cover I/O failures mid-write; there, the missing manifest.json — written last — is the signal.

The cost of that ordering is memory: dump holds every payload of every item at once. On Windows the synthesis groups make this worse than it looks, since a large image is typically resident as both CF_DIB and CF_DIBV5.

Linux

Linux has no clipboard API — it has two selection protocols, neither reachable without a connection to the display server. clipout reads them through wl-paste under Wayland and xclip under X11, so one of these must be installed:

sudo apt install wl-clipboard    # Wayland
sudo apt install xclip           # X11

WAYLAND_DISPLAY decides which is preferred, but not on its own: a Wayland session almost always runs XWayland, so if wl-clipboard is missing and xclip is present, clipout uses xclip against the bridged selection rather than refusing to work. With neither WAYLAND_DISPLAY nor DISPLAY set — a headless box, a cron job, an SSH session without forwarding — there is no clipboard, and clipout says so with ECLIPBOARD rather than reporting an empty one.

Only the CLIPBOARD selection is read. PRIMARY, the middle-click selection, is a separate clipboard clipout cannot currently see.

Flavor IDs are the advertised type names verbatim, so they look like MIME types under Wayland and like X11 atom names under X11:

$ clipout list
SEL  ALIAS  FLAVOR                            SIZE  STATE                       GROUP
@0   -      TIMESTAMP                            8  available                   -
@1   -      TARGETS                             40  available                   -
@2   -      MULTIPLE                             -  unavailable (not_rendered)  -
@3   text   UTF8_STRING                         89  available                   -
@4   html   text/html                          312  available                   -

In JSON, native.kind is mime or x11_target so you can tell an atom name from a real MIME type without parsing the string.

What is weaker here

No sequence number. Neither protocol has one. --if-sequence is rejected with EUSAGE, and sequence in the JSON output is always 0 — a constant, not a value to compare.

Internally clipout does check for change, using the list of advertised types as a proxy. That test is sound in one direction only: if it fires, the clipboard really did change, but if it does not fire, the clipboard may still have changed — copying a second paragraph from the same application advertises exactly the same types as the first. So a Linux dump is probably coherent, not provably so. Everything else in Racing the clipboard still holds; that one guarantee does not, and clipout does not publish the proxy as sequence precisely so that nothing can quietly come to depend on it.

One helper process per advertised type. A flavor's state cannot be known on Linux without trying to fetch it, so list, get, and dump all read every payload. A get of one small flavor from a clipboard that also holds a large image will pull the image. Payloads read during enumeration are reused rather than fetched twice, which is also what keeps a dump manifest's sizes in agreement with the files next to it.

Exit codes

Code Symbol Condition
0 — Success
1 EGENERAL Unclassified failure
2 EUSAGE Invalid arguments
3 ECLIPBOARD Clipboard could not be opened or read
4 ENOTFOUND Named flavor not present
5 EAMBIGUOUS Selector matched multiple flavors
6 EUNAVAILABLE Flavor present but not extractable
7 ESEQUENCE Clipboard changed, or --if-sequence mismatch
8 ERANGE Item index out of range
9 EPLATFORM Platform backend not implemented

Flavors that exist but cannot be read

Reported rather than hidden (goal G4), each with a machine-readable reason:

  • promised (macOS) — the owner advertised the flavor but has not materialized its bytes. Very common: copying rich text usually yields a real public.rtf alongside promised plain-text variants.
  • requires_ole (Windows) — offered only on TYMED_ISTREAM / TYMED_ISTORAGE, chiefly CFSTR_FILECONTENTS for virtual files such as mail attachments. v1 uses the raw Win32 API and does not initialize COM. Note that CFSTR_FILEDESCRIPTORW is an ordinary HGLOBAL, so the names of virtual files remain visible even when their contents are not.
  • not_rendered (Windows, Linux) — the flavor was advertised but nothing came back, and the platform does not say why. On Windows it may be OLE-only delivery, a delay-rendered format the owner declined to render, or a marker format that carries no payload at all — ExcludeClipboardContentFromMonitorProcessing, which asks clipboard history to skip the content, appears on every Excel copy. On Linux the owner may have refused the conversion, may have exited since advertising, or the target may be selection-protocol machinery rather than content, as MULTIPLE and SAVE_TARGETS are. Each platform reports its candidates identically, so clipout names the observation instead of guessing a cause.
  • non_global_handle (Windows) — CF_BITMAP, CF_PALETTE, CF_ENHMETAFILE and friends hand back GDI handles, not memory blocks. Little is lost in practice: an application placing a bitmap on the clipboard virtually always provides CF_DIB too, and Windows synthesizes one from the other regardless.
  • unknown_handle (Windows) — a private format (0x0200–0x02FF), whose handle type is defined by the owning application and cannot be discovered. Distinct from non_global_handle, and worth a second look: the payload may be an ordinary HGLOBAL, and --unsafe-private will attempt the read at the risk of crashing on a wrong guess.
  • owner_rendered (Windows) — CF_OWNERDISPLAY and the DSP* variants carry no transferable payload at all.

reason is an open set. New values may appear within schema version 1, so consumers must tolerate ones they do not recognize rather than failing on them.

Resolution of the specification's open decisions

The specification leaves nine decisions open (§11). Seven are settled here as follows; D8 and D9 were raised 68E6 by the Linux work and remain open.

  • D1 — is --if-sequence mandatory for get? Left optional, contrary to the spec's lean toward (c). Emitting a ready-to-paste get invocation from list --json would require a field that §5 does not define, and adding one silently is worse than documenting the idiom; the shell snippet above is in the README instead. The stronger half of the concern is handled without any new surface: a single invocation now verifies the sequence after reading, so get and dump fail loudly rather than returning mixed data.
  • D2 — macOS size reporting. Always fetch, per the spec's lean. list fetches each payload, records length(), and drops the buffer, so sizes are reported uniformly on both platforms.
  • D3 — Windows private formats (0x0200–0x02FF). Option (b): marked unavailable by default with reason unknown_handle, and --unsafe-private to opt into treating them as HGLOBAL. An earlier revision reused non_global_handle on the mistaken belief that adding a reason would break the schema; it does not, and the reuse asserted something false about the payload. reason is documented as an open set instead.
  • D4 — CF_DIB header synthesis in dump. Option (a): raw bytes only. Writing a sibling .bmp would be more convenient but would break goal G2's no-transformation rule, which is the property that makes dump output trustworthy.
  • D5 — dynamic UTI decoding. Deferred. dyn. identifiers pass through opaquely and select normally as strings.
  • D6 — duplicate flavor IDs within an item. list does not visually mark collisions; the @N column already disambiguates every row, and get raises EAMBIGUOUS with the candidates as §4.5 requires.
  • D7 — empty payloads. Exit 0, write nothing, per the spec's lean. A zero-byte flavor is reported as available with size: 0.
  • D8 — the X11 PRIMARY selection. Open. CLIPBOARD only for now. A --primary flag is the lean, and the hesitation is that it would be the first option on the command line that exists on one platform and not the others, which goal G3 exists to resist.
  • D9 — the other Unixes. Open. The BSDs and illumos run the same X11 and Wayland servers and would very likely work unmodified, but that is untested, and platform is currently one of exactly three values, none of them honest for FreeBSD. They stay on the EPLATFORM stub.

Layout

src/
├── main.rs            entry point, exit-code mapping, stderr reporting
├── cli.rs             clap surface (§4)
├── model.rs           the cross-platform data model (§3)
├── error.rs           error taxonomy and exit codes (§6)
├── select.rs          flavor selector grammar (§4.5)
├── json.rs            JSON document builder (§5)
├── sanitize.rs        dump filename derivation (§8.3)
├── timestamp.rs       ISO 8601 for the dump manifest
├── backend/
│   ├── mod.rs         Backend trait and the sequence guard (§3.4)
│   ├── macos.rs       NSPasteboard (§8)
│   ├── windows.rs     Win32 clipboard, handle classification (§7)
│   ├── linux.rs       wl-paste / xclip delegation (§9)
│   └── unsupported.rs EPLATFORM stub for the remaining platforms
└── commands/          list, get, dump

About

A cross-platform clipboard extraction tool.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0