1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
package main

import (
	"bytes"
	"fmt"
	"os/exec"
	"strings"
)

// clipboardTargets lists the formats the current CLIPBOARD owner can supply.
func clipboardTargets() ([]string, error) {
	out, err := exec.Command("xclip", "-selection", "clipboard", "-t", "TARGETS", "-o").Output()
	if err != nil {
		return nil, fmt.Errorf("xclip TARGETS: %w", err)
	}
	var targets []string
	for _, line := range strings.Split(string(out), "\n") {
		if line = strings.TrimSpace(line); line != "" {
			targets = append(targets, line)
		}
	}
	return targets, nil
}

// readImageFromClipboard pulls an image off the X11 CLIPBOARD selection.
//
// The available targets are consulted first rather than simply attempting each
// image type in turn: asking xclip for a target the owner does not provide does
// not fail, it hands back whatever the selection holds. With text on the
// clipboard, requesting image/png yields the *text* bytes, which then reach
// ImageMagick and produce a baffling "no decode delegate" error instead of the
// obvious "there is no image here".
func readImageFromClipboard() ([]byte, string, error) {
	targets, err := clipboardTargets()
	if err != nil {
		// An empty clipboard has no owner at all, so TARGETS fails outright.
		return nil, "", fmt.Errorf("clipboard is empty or unreadable: %w", err)
	}

	have := make(map[string]bool, len(targets))
	for _, t := range targets {
		have[t] = true
	}

	for _, mimeType := range []string{"image/png", "image/jpeg", "image/webp"} {
		if !have[mimeType] {
			continue
		}
		out, err := exec.Command("xclip", "-selection", "clipboard", "-t", mimeType, "-o").Output()
		if err != nil {
			return nil, "", fmt.Errorf("read %s from clipboard: %w", mimeType, err)
		}
		if len(out) > 0 {
			return out, mimeType, nil
		}
	}

	return nil, "", fmt.Errorf("no image in clipboard; it offers: %s", strings.Join(targets, ", "))
}

// convertToWebP shrinks the image before it goes over the wire. Screenshots are
// typically PNG, where webp is several times smaller for identical content, and
// upload time dominates the request.
func convertToWebP(imageBytes []byte) ([]byte, error) {
	cmd := exec.Command("magick", "-", "webp:-")
	cmd.Stdin = bytes.NewReader(imageBytes)
	var stderr bytes.Buffer
	cmd.Stderr = &stderr
	out, err := cmd.Output()
	if err != nil {
		msg := strings.TrimSpace(stderr.String())
		if msg != "" {
			return nil, fmt.Errorf("magick convert: %w: %s", err, msg)
		}
		return nil, fmt.Errorf("magick convert: %w", err)
	}
	return out, nil
}

// copyToSelections puts text on both PRIMARY (middle-click paste) and CLIPBOARD
// (ctrl-v).
//
// Each xclip invocation forks a process that keeps running to *own* the
// selection: X11 selections are not a buffer somewhere, they are a promise by a
// live client to hand over the data when another client asks. Killing that
// process reverts the selection to whatever held it before.
//
// This is why the systemd unit must set KillMode=process. With the default
// control-group mode systemd SIGKILLs the whole cgroup when the server exits,
// taking these xclip processes with it, and the copy silently un-does itself a
// minute later. autocutsel(1) running in the X session would incidentally
// rescue PRIMARY via CUTBUFFER0, but nothing rescues CLIPBOARD.
func copyToSelections(text string) error {
	var errs []string
	for _, sel := range []string{"primary", "clipboard"} {
		cmd := exec.Command("xclip", "-selection", sel)
		cmd.Stdin = strings.NewReader(text)
		if err := cmd.Run(); err != nil {
			errs = append(errs, fmt.Sprintf("%s: %s", sel, err))
		}
	}
	if len(errs) > 0 {
		return fmt.Errorf("xclip: %s", strings.Join(errs, "; "))
	}
	return nil
}