Desktop

Clipboard

Copy and paste from Java: text first, then HTML, images and files, secrets that vanish after 30 seconds, and change events.

Available since 0.3.3. Copy and paste is how data moves between programs, so almost every desktop app ends up touching the clipboard: a "Copy link" button, a pasted screenshot, a password that should not stay around. Jolt gives your Java code the system clipboard without AWT (on Linux AWT would load a second toolkit next to GTK). This page starts with one line of text and ends with secrets and change events.

The clipboard is for your Java code, not for the page. A page's own navigator.clipboard is still decided by the SecurityPolicy, and the default refuses it. If the page needs to copy something, send Java a message and let your handler decide what may be copied.

1. Copy and paste text

Get the clipboard from the application. Every call returns a CompletableFuture at once and may be made from any thread:

Clipboard clipboard = app.clipboard();

clipboard.writeText("https://jolt.williamsolari.com");               // copy

clipboard.readText().thenAccept(text -> {                            // paste
    text.ifPresent(t -> System.out.println("Clipboard says: " + t)); // empty if there is no text
});
  • The futures complete on the UI thread. Never block that thread waiting for one (no .get() in a message listener). Keep the work inside thenAccept short.
  • clipboard.clear() empties the clipboard.

2. A "Copy" button in the page

The usual way to connect the two is a message: the page asks, Java copies and answers.

copyButton.onclick = () => jolt.postMessage('copy-link');
jolt.onMessage(m => { if (m === 'copied') copyButton.textContent = 'Copied'; });
window.onMessage(message -> {
    if (message.equals("copy-link")) {
        app.clipboard().writeText(currentLink())
                .thenRun(() -> window.postMessage("copied"));
    }
});

For anything beyond a couple of messages, use the call-style helper from Messaging. The handler decides what is copied; the page cannot put arbitrary data on the clipboard unless you write a handler that lets it.

3. More than text: HTML, images and files

The clipboard can hold several forms of the same copy, and the program that pastes picks the one it prefers. Clipboard.Format names them: TEXT, HTML, IMAGE and FILES.

clipboard.formats().thenAccept(formats -> {                  // Set<Clipboard.Format>
    if (formats.contains(Clipboard.Format.IMAGE)) {
        clipboard.readImage().thenAccept(png -> png.ifPresent(this::showPreview));   // PNG bytes
    } else if (formats.contains(Clipboard.Format.FILES)) {
        clipboard.readFiles().thenAccept(paths -> importAll(paths));                // absolute local paths
    }
});

To write more than one form at once, build a ClipboardContent. A rich-text editor would offer HTML for programs that can render it and plain text for the rest:

clipboard.write(ClipboardContent.html("<b>Hello</b> world", "Hello world"));     // HTML fragment + plain fallback

clipboard.write(ClipboardContent.image(pngBytes));                               // a PNG
clipboard.write(ClipboardContent.files(List.of(Path.of("C:\\Reports\\q3.pdf")))); // as if copied in the file manager

clipboard.write(ClipboardContent.text("Plain text")
        .withHtml("<i>Plain</i> text"));                                     // combine forms with with...
  • Images are PNG. On Windows Jolt also adds a bitmap form, so programs that only know bitmaps can still paste it.
  • Files are copied, not moved. Pasting in a file manager makes a copy of each path you gave.
  • On Linux, FILES is reported whenever a text/uri-list is offered, which browsers also do for plain links. readFiles() then returns an empty list, so always check the result.

4. Passwords and tokens

A copied password should not end up in the clipboard history, the cloud clipboard or a clipboard monitor, and should not sit there for an hour. ClipboardContent.secret does both:

clipboard.write(ClipboardContent.secret(password));                      // removed after 30 seconds
clipboard.write(ClipboardContent.secret(token, Duration.ofSeconds(10)));  // or choose how long
  • Kept out of history. Windows clipboard history, the cloud clipboard and monitors skip it. On Linux Jolt sets x-kde-passwordManagerHint, which Klipper and other managers honour.
  • Taken off again. After the time is up the clipboard is emptied, but only if it still holds your value. If the user copied something else in the meantime, that stays.
  • Removed at exit. A secret that is still there when the application ends is removed too.
  • It is a request, not a lock. Other programs the user runs can still read the clipboard while the value is on it. Pair this with the credential store for storage, and use the clipboard only for the moment the user needs to paste.
  • You can set the same behaviour yourself with withSensitive(true) and withClearAfter(duration) on any content.

5. Reacting to changes

Watch the clipboard to enable a "Paste" button only when there is something to paste, or to offer "Import the copied image":

Clipboard.Subscription watch = clipboard.onChange(formats -> {          // UI thread; return quickly
    window.postMessage(formats.contains(Clipboard.Format.IMAGE) ? "clipboard:image" : "clipboard:other");
});

// later, when you no longer care
watch.close();
  • The listener gets the formats only, never the content. Read what you need with the calls above.
  • It also fires for this application's own writes.
  • Wayland limit: GTK 3 does not report clipboard owner changes on Wayland. Your own writes and clears are announced (since 0.4.1), but what other programs copy cannot be seen there. Where the system reports them, as Windows does, copies made by other programs arrive too.

6. Treat what you read as hostile

The clipboard is shared with every program the user runs, so whatever is on it came from whoever copied last. Jolt validates what it can, and you handle the rest:

  • Limits. Content over 32 MB or more than 4096 files is refused. Lengths and offsets in data from other programs are checked against the data that is actually there, and text stops at the first NUL character.
  • Text and file names can be anything. Do not run them, use them to build commands, or open them without checking.
  • HTML from readHtml() may contain scripts and remote references. Never put it into a page without sanitizing it, and set text with textContent where you can.
  • Images are validated as PNG at the header only. Jolt hands out the bytes without decoding them, so a program that decodes the image should expect a damaged one.
  • File paths are always absolute and local. A network path such as \\server\share\x is dropped, because opening it would make Windows send the user's credentials to that server. Nothing is said about what is at a path.
  • Nothing is logged. Content never reaches the log, and ClipboardContent.toString() only says which forms are present.

Bad input to a write (an empty content, a relative path, text with a NUL) throws IllegalArgumentException when you build the ClipboardContent, before anything touches the clipboard.