neko/internal/desktop/clipboard.go

89 lines
2.0 KiB
Go
Raw Normal View History

2020-11-02 04:09:48 +13:00
package desktop
import (
2021-01-29 09:19:31 +13:00
"fmt"
"bytes"
2021-01-29 09:12:35 +13:00
"os/exec"
"strings"
2020-11-02 04:09:48 +13:00
)
func (manager *DesktopManagerCtx) ClipboardGetBinary(mime string) ([]byte, error) {
cmd := exec.Command("xclip", "-selection", "clipboard", "-o", "-t", mime)
2021-01-29 09:19:31 +13:00
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
msg := strings.TrimSpace(string(stderr.Bytes()))
return nil, fmt.Errorf("%s", msg)
2021-01-29 09:19:31 +13:00
}
return stdout.Bytes(), nil
2020-11-02 04:09:48 +13:00
}
func (manager *DesktopManagerCtx) ClipboardSetBinary(mime string, data []byte) error {
cmd := exec.Command("xclip", "-selection", "clipboard", "-i", "-t", mime)
cmd.Stdin = bytes.NewReader(data)
2021-01-29 09:19:31 +13:00
var stderr bytes.Buffer
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
msg := strings.TrimSpace(string(stderr.Bytes()))
return fmt.Errorf("%s", msg)
}
return nil
2020-11-02 04:09:48 +13:00
}
func (manager *DesktopManagerCtx) ClipboardGetTargets() ([]string, error) {
cmd := exec.Command("xclip", "-selection", "clipboard", "-o", "-t", "TARGETS")
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
msg := strings.TrimSpace(string(stderr.Bytes()))
return nil, fmt.Errorf("%s", msg)
}
var response []string
targets := strings.Split(string(stdout.Bytes()), "\n")
for _, target := range targets {
if target == "" {
continue
}
if !strings.Contains(target, "/") {
continue
}
response = append(response, target)
}
return response, nil
}
func (manager *DesktopManagerCtx) ClipboardGetPlainText() (string, error) {
bytes, err := manager.ClipboardGetBinary("STRING")
return string(bytes), err
}
func (manager *DesktopManagerCtx) ClipboardSetPlainText(data string) error {
return manager.ClipboardSetBinary("STRING", []byte(data))
}
func (manager *DesktopManagerCtx) ClipboardGetRichText() (string, error) {
bytes, err := manager.ClipboardGetBinary("text/html")
return string(bytes), err
}
func (manager *DesktopManagerCtx) ClipboardSetRichText(data string) error {
return manager.ClipboardSetBinary("text/html", []byte(data))
}