From cf78bc0515fa38a6cc570afd7a7e0000bdcda09e Mon Sep 17 00:00:00 2001 From: citrons Date: Thu, 5 Jun 2025 14:56:22 -0500 Subject: clipboard support --- client/clipboard/shell_clipboard.go | 78 +++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 client/clipboard/shell_clipboard.go (limited to 'client/clipboard/shell_clipboard.go') diff --git a/client/clipboard/shell_clipboard.go b/client/clipboard/shell_clipboard.go new file mode 100644 index 0000000..9d8ecc8 --- /dev/null +++ b/client/clipboard/shell_clipboard.go @@ -0,0 +1,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 + } + } +} -- cgit v1.2.3