Command line client for Write.as https://write.as/apps/cli
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
2.3 KiB

  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. // +build freebsd linux netbsd openbsd solaris dragonfly
  5. package clipboard
  6. import (
  7. "errors"
  8. "os/exec"
  9. )
  10. const (
  11. xsel = "xsel"
  12. xclip = "xclip"
  13. termuxClipboardGet = "termux-clipboard-get"
  14. termuxClipboardSet = "termux-clipboard-set"
  15. )
  16. var (
  17. Primary bool
  18. pasteCmdArgs []string
  19. copyCmdArgs []string
  20. xselPasteArgs = []string{xsel, "--output", "--clipboard"}
  21. xselCopyArgs = []string{xsel, "--input", "--clipboard"}
  22. xclipPasteArgs = []string{xclip, "-out", "-selection", "clipboard"}
  23. xclipCopyArgs = []string{xclip, "-in", "-selection", "clipboard"}
  24. termuxPasteArgs = []string{termuxClipboardGet}
  25. termuxCopyArgs = []string{termuxClipboardSet}
  26. missingCommands = errors.New("No clipboard utilities available. Please install xsel, xclip, or Termux:API add-on for termux-clipboard-get/set.")
  27. )
  28. func init() {
  29. pasteCmdArgs = xclipPasteArgs
  30. copyCmdArgs = xclipCopyArgs
  31. if _, err := exec.LookPath(xclip); err == nil {
  32. return
  33. }
  34. pasteCmdArgs = xselPasteArgs
  35. copyCmdArgs = xselCopyArgs
  36. if _, err := exec.LookPath(xsel); err == nil {
  37. return
  38. }
  39. pasteCmdArgs = termuxPasteArgs
  40. copyCmdArgs = termuxCopyArgs
  41. if _, err := exec.LookPath(termuxClipboardSet); err == nil {
  42. if _, err := exec.LookPath(termuxClipboardGet); err == nil {
  43. return
  44. }
  45. }
  46. Unsupported = true
  47. }
  48. func getPasteCommand() *exec.Cmd {
  49. if Primary {
  50. pasteCmdArgs = pasteCmdArgs[:1]
  51. }
  52. return exec.Command(pasteCmdArgs[0], pasteCmdArgs[1:]...)
  53. }
  54. func getCopyCommand() *exec.Cmd {
  55. if Primary {
  56. copyCmdArgs = copyCmdArgs[:1]
  57. }
  58. return exec.Command(copyCmdArgs[0], copyCmdArgs[1:]...)
  59. }
  60. func readAll() (string, error) {
  61. if Unsupported {
  62. return "", missingCommands
  63. }
  64. pasteCmd := getPasteCommand()
  65. out, err := pasteCmd.Output()
  66. if err != nil {
  67. return "", err
  68. }
  69. return string(out), nil
  70. }
  71. func writeAll(text string) error {
  72. if Unsupported {
  73. return missingCommands
  74. }
  75. copyCmd := getCopyCommand()
  76. in, err := copyCmd.StdinPipe()
  77. if err != nil {
  78. return err
  79. }
  80. if err := copyCmd.Start(); err != nil {
  81. return err
  82. }
  83. if _, err := in.Write([]byte(text)); err != nil {
  84. return err
  85. }
  86. if err := in.Close(); err != nil {
  87. return err
  88. }
  89. return copyCmd.Wait()
  90. }