package clipboard import ( "bytes" "context" "errors" "os" "os/exec" "strings" "time" ) const commandTimeout = 3 * time.Second // Linux has no clipboard API without a toolkit; the standard tools are used instead: // wl-clipboard on Wayland, xclip on X11. type linuxClipboard struct { listTypes []string read func(textType string) []string write []string } // New picks Wayland or X11 depending on the session and the installed tools. func New() (Clipboard, error) { if os.Getenv("WAYLAND_DISPLAY") != "" && hasCommand("wl-paste") && hasCommand("wl-copy") { return &linuxClipboard{ listTypes: []string{"wl-paste", "--list-types"}, read: func(t string) []string { return []string{"wl-paste", "--no-newline", "--type", t} }, write: []string{"wl-copy"}, }, nil } if os.Getenv("DISPLAY") != "" && hasCommand("xclip") { return &linuxClipboard{ listTypes: []string{"xclip", "-selection", "clipboard", "-t", "TARGETS", "-o"}, read: func(t string) []string { return []string{"xclip", "-selection", "clipboard", "-t", t, "-o"} }, write: []string{"xclip", "-selection", "clipboard", "-i"}, }, nil } return nil, errors.New("keine Zwischenablage gefunden: unter Wayland wl-clipboard, unter X11 xclip installieren") } func hasCommand(name string) bool { _, err := exec.LookPath(name) return err == nil } func run(args []string, stdin string) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), commandTimeout) defer cancel() cmd := exec.CommandContext(ctx, args[0], args[1:]...) if stdin != "" { cmd.Stdin = strings.NewReader(stdin) } var out bytes.Buffer cmd.Stdout = &out err := cmd.Run() return out.String(), err } func (c *linuxClipboard) Read() (Content, error) { output, err := run(c.listTypes, "") if err != nil { // Empty clipboard: the tools exit with an error; not worth reporting return Content{}, nil } types := parseTypes(output) if isConcealed(types) { return Content{Concealed: true}, nil } textType := textType(types) if textType == "" { return Content{}, nil } text, err := run(c.read(textType), "") if err != nil { return Content{}, err } return Content{Text: text}, nil } func (c *linuxClipboard) Write(text string) error { // xclip and wl-copy keep serving the selection in the background after we return cmd := exec.Command(c.write[0], c.write[1:]...) cmd.Stdin = strings.NewReader(text) return cmd.Run() }