clipboard_unix.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Copyright 2013 @atotto. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:build freebsd || linux || netbsd || openbsd || solaris || dragonfly
  5. // +build freebsd linux netbsd openbsd solaris dragonfly
  6. package clipboard
  7. import (
  8. "errors"
  9. "os/exec"
  10. )
  11. const (
  12. xsel = "xsel"
  13. xclip = "xclip"
  14. )
  15. var (
  16. // Primary choose primary mode on unix
  17. Primary bool
  18. pasteCmdArgs, copyCmdArgs []string
  19. xselPasteArgs = []string{xsel, "--output", "--clipboard"}
  20. xselCopyArgs = []string{xsel, "--input", "--clipboard"}
  21. xclipPasteArgs = []string{xclip, "-out", "-selection", "clipboard"}
  22. xclipCopyArgs = []string{xclip, "-in", "-selection", "clipboard"}
  23. errMissingCommands = errors.New("No clipboard utilities available. Please install xsel or xclip")
  24. )
  25. func init() {
  26. pasteCmdArgs = xclipPasteArgs
  27. copyCmdArgs = xclipCopyArgs
  28. if _, err := exec.LookPath(xclip); err == nil {
  29. return
  30. }
  31. pasteCmdArgs = xselPasteArgs
  32. copyCmdArgs = xselCopyArgs
  33. if _, err := exec.LookPath(xsel); err == nil {
  34. return
  35. }
  36. Unsupported = true
  37. }
  38. func getPasteCommand() *exec.Cmd {
  39. if Primary {
  40. pasteCmdArgs = pasteCmdArgs[:1]
  41. }
  42. return exec.Command(pasteCmdArgs[0], pasteCmdArgs[1:]...)
  43. }
  44. func getCopyCommand() *exec.Cmd {
  45. if Primary {
  46. copyCmdArgs = copyCmdArgs[:1]
  47. }
  48. return exec.Command(copyCmdArgs[0], copyCmdArgs[1:]...)
  49. }
  50. func readAll() (string, error) {
  51. if Unsupported {
  52. return "", errMissingCommands
  53. }
  54. pasteCmd := getPasteCommand()
  55. out, err := pasteCmd.Output()
  56. if err != nil {
  57. return "", err
  58. }
  59. return string(out), nil
  60. }
  61. func writeAll(text string) error {
  62. if Unsupported {
  63. return errMissingCommands
  64. }
  65. copyCmd := getCopyCommand()
  66. in, err := copyCmd.StdinPipe()
  67. if err != nil {
  68. return err
  69. }
  70. if err := copyCmd.Start(); err != nil {
  71. return err
  72. }
  73. if _, err := in.Write([]byte(text)); err != nil {
  74. return err
  75. }
  76. if err := in.Close(); err != nil {
  77. return err
  78. }
  79. return copyCmd.Wait()
  80. }