clipboard_linux.go 1.3 KB

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