clipboard_wayland.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //go:build linux || freebsd
  2. package clipboard
  3. import (
  4. "bytes"
  5. "github.com/ayn2op/clipboard"
  6. "os"
  7. "os/exec"
  8. )
  9. var wayland bool
  10. func Init() error {
  11. if _, ok := os.LookupEnv("WAYLAND_DISPLAY"); !ok {
  12. return clipboard.Init()
  13. }
  14. if _, err := exec.LookPath("wl-copy"); err != nil {
  15. return err
  16. }
  17. if _, err := exec.LookPath("wl-paste"); err != nil {
  18. return err
  19. }
  20. wayland = true
  21. return nil
  22. }
  23. func Read(t Format) ([]byte, error) {
  24. if !wayland {
  25. return clipboard.Read(clipboard.Format(t))
  26. }
  27. // -n: Don't print a newline at the end
  28. // -t type: MIME type specifier
  29. cmd := exec.Command("wl-paste", "-nt", formatToType(t))
  30. outBuffer := bytes.Buffer{}
  31. cmd.Stdout = &outBuffer
  32. if err := cmd.Run(); err != nil {
  33. return nil, err
  34. }
  35. return outBuffer.Bytes(), nil
  36. }
  37. func Write(t Format, buf []byte) error {
  38. if !wayland {
  39. return clipboard.Write(clipboard.Format(t), buf)
  40. }
  41. // -t type: MIME type specifier
  42. cmd := exec.Command("wl-copy", "-t", formatToType(t))
  43. cmd.Stdin = bytes.NewReader(buf)
  44. return cmd.Run()
  45. }
  46. func formatToType(t Format) string {
  47. switch t {
  48. case FmtImage:
  49. return "image"
  50. case FmtText:
  51. fallthrough
  52. default:
  53. return "text/plain;charset=utf-8"
  54. }
  55. }