summaryrefslogtreecommitdiff
path: root/client/clipboard/shell_clipboard.go
blob: 9d8ecc81aa1f3e1843d78d45d4df633c9f0dc8f8 (plain)
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
package clipboard

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

type ShellClipboard struct {
	copyCommand string
	pasteCommand string
	testCommand string
}

var try = []ShellClipboard {
	ShellClipboard {"wl-copy", "wl-paste -n", "wl-copy -h"},
	ShellClipboard {
		"xclip -selection clipboard", "xclip -selection clipboard -o",
		"xclip -h",
	},
	ShellClipboard {"pbcopy", "pbpaste", "pbcopy -help"},
}

func command(command string) *exec.Cmd {
	args := strings.Split(command, " ")
	return exec.Command(args[0], args[1:]...)
}

func (c ShellClipboard) Test() bool {
	cmd := command(c.testCommand)
	return cmd.Run() == nil
}

func (c ShellClipboard) Copy(text string) {
	cmd := command(c.copyCommand)
	pipe, err := cmd.StdinPipe()
	cmd.Start()
	go func() {
		if err != nil {
			return
		}
		defer pipe.Close()

		buf := bytes.NewBuffer([]byte(text))
		buf.WriteTo(pipe)
	}()
}

func (c ShellClipboard) Paste() <-chan string {
	cmd := command(c.pasteCommand)
	pipe, err := cmd.StdoutPipe()
	cmd.Start()
	ch := make(chan string, 1)
	go func() {
		if err != nil {
			return
		}
		defer pipe.Close()

		buf := bytes.NewBuffer(nil)
		_, err = buf.ReadFrom(pipe)
		if err != nil {
			return
		}
		ch <- buf.String()
		close(ch)
	}()
	return ch
}

func DiscoverCommand() {
	for _, c := range try {
		if c.Test() {
			Set(c)
			break
		}
	}
}