clipboard_linux.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. // Copyright 2021 The golang.design Initiative Authors.
  2. // All rights reserved. Use of this source code is governed
  3. // by a MIT license that can be found in the LICENSE file.
  4. //
  5. // Written by Changkun Ou <changkun.de>
  6. //go:build linux
  7. package clipboard
  8. import (
  9. "bytes"
  10. "context"
  11. "fmt"
  12. "log/slog"
  13. "os/exec"
  14. "strings"
  15. "sync"
  16. "time"
  17. )
  18. var (
  19. // Clipboard tools in order of preference
  20. clipboardTools = []struct {
  21. name string
  22. readCmd []string
  23. writeCmd []string
  24. readImg []string
  25. writeImg []string
  26. available bool
  27. }{
  28. {
  29. name: "xclip",
  30. readCmd: []string{"xclip", "-selection", "clipboard", "-o"},
  31. writeCmd: []string{"xclip", "-selection", "clipboard"},
  32. readImg: []string{"xclip", "-selection", "clipboard", "-t", "image/png", "-o"},
  33. writeImg: []string{"xclip", "-selection", "clipboard", "-t", "image/png"},
  34. },
  35. {
  36. name: "xsel",
  37. readCmd: []string{"xsel", "--clipboard", "--output"},
  38. writeCmd: []string{"xsel", "--clipboard", "--input"},
  39. readImg: []string{"xsel", "--clipboard", "--output"},
  40. writeImg: []string{"xsel", "--clipboard", "--input"},
  41. },
  42. {
  43. name: "wl-clipboard",
  44. readCmd: []string{"wl-paste", "-n"},
  45. writeCmd: []string{"wl-copy"},
  46. readImg: []string{"wl-paste", "-t", "image/png", "-n"},
  47. writeImg: []string{"wl-copy", "-t", "image/png"},
  48. },
  49. }
  50. selectedTool int = -1
  51. toolMutex sync.Mutex
  52. lastChangeTime time.Time
  53. changeTimeMu sync.Mutex
  54. )
  55. func initialize() error {
  56. toolMutex.Lock()
  57. defer toolMutex.Unlock()
  58. if selectedTool >= 0 {
  59. return nil // Already initialized
  60. }
  61. // Check which clipboard tool is available
  62. for i, tool := range clipboardTools {
  63. cmd := exec.Command("which", tool.name)
  64. if err := cmd.Run(); err == nil {
  65. clipboardTools[i].available = true
  66. if selectedTool < 0 {
  67. selectedTool = i
  68. slog.Debug("Clipboard tool found", "tool", tool.name)
  69. }
  70. }
  71. }
  72. if selectedTool < 0 {
  73. slog.Warn(
  74. "No clipboard utility found on system. Copy/paste functionality will be disabled. See https://opencode.ai/docs/troubleshooting/ for more information.",
  75. )
  76. return fmt.Errorf(`%w: No clipboard utility found. Install one of the following:
  77. For X11 systems:
  78. apt install -y xclip
  79. # or
  80. apt install -y xsel
  81. For Wayland systems:
  82. apt install -y wl-clipboard
  83. If running in a headless environment, you may also need:
  84. apt install -y xvfb
  85. # and run:
  86. Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
  87. export DISPLAY=:99.0`, errUnavailable)
  88. }
  89. return nil
  90. }
  91. func read(t Format) (buf []byte, err error) {
  92. // Ensure clipboard is initialized before attempting to read
  93. if err := initialize(); err != nil {
  94. slog.Debug("Clipboard read failed: not initialized", "error", err)
  95. return nil, err
  96. }
  97. toolMutex.Lock()
  98. tool := clipboardTools[selectedTool]
  99. toolMutex.Unlock()
  100. switch t {
  101. case FmtText:
  102. return readText(tool)
  103. case FmtImage:
  104. return readImage(tool)
  105. default:
  106. return nil, errUnsupported
  107. }
  108. }
  109. func readText(tool struct {
  110. name string
  111. readCmd []string
  112. writeCmd []string
  113. readImg []string
  114. writeImg []string
  115. available bool
  116. }) ([]byte, error) {
  117. // First check if clipboard contains text
  118. cmd := exec.Command(tool.readCmd[0], tool.readCmd[1:]...)
  119. out, err := cmd.Output()
  120. if err != nil {
  121. // Check if it's because clipboard contains non-text data
  122. if tool.name == "xclip" {
  123. // xclip returns error when clipboard doesn't contain requested type
  124. checkCmd := exec.Command("xclip", "-selection", "clipboard", "-t", "TARGETS", "-o")
  125. targets, _ := checkCmd.Output()
  126. if bytes.Contains(targets, []byte("image/png")) &&
  127. !bytes.Contains(targets, []byte("UTF8_STRING")) {
  128. return nil, errUnavailable
  129. }
  130. }
  131. return nil, errUnavailable
  132. }
  133. return out, nil
  134. }
  135. func readImage(tool struct {
  136. name string
  137. readCmd []string
  138. writeCmd []string
  139. readImg []string
  140. writeImg []string
  141. available bool
  142. }) ([]byte, error) {
  143. if tool.name == "xsel" {
  144. // xsel doesn't support image types well, return error
  145. return nil, errUnavailable
  146. }
  147. cmd := exec.Command(tool.readImg[0], tool.readImg[1:]...)
  148. out, err := cmd.Output()
  149. if err != nil {
  150. return nil, errUnavailable
  151. }
  152. // Verify it's PNG data
  153. if len(out) < 8 ||
  154. !bytes.Equal(out[:8], []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}) {
  155. return nil, errUnavailable
  156. }
  157. return out, nil
  158. }
  159. func write(t Format, buf []byte) (<-chan struct{}, error) {
  160. // Ensure clipboard is initialized before attempting to write
  161. if err := initialize(); err != nil {
  162. return nil, err
  163. }
  164. toolMutex.Lock()
  165. tool := clipboardTools[selectedTool]
  166. toolMutex.Unlock()
  167. var cmd *exec.Cmd
  168. switch t {
  169. case FmtText:
  170. if len(buf) == 0 {
  171. // Write empty string
  172. cmd = exec.Command(tool.writeCmd[0], tool.writeCmd[1:]...)
  173. cmd.Stdin = bytes.NewReader([]byte{})
  174. } else {
  175. cmd = exec.Command(tool.writeCmd[0], tool.writeCmd[1:]...)
  176. cmd.Stdin = bytes.NewReader(buf)
  177. }
  178. case FmtImage:
  179. if tool.name == "xsel" {
  180. // xsel doesn't support image types well
  181. return nil, errUnavailable
  182. }
  183. if len(buf) == 0 {
  184. // Clear clipboard
  185. cmd = exec.Command(tool.writeCmd[0], tool.writeCmd[1:]...)
  186. cmd.Stdin = bytes.NewReader([]byte{})
  187. } else {
  188. cmd = exec.Command(tool.writeImg[0], tool.writeImg[1:]...)
  189. cmd.Stdin = bytes.NewReader(buf)
  190. }
  191. default:
  192. return nil, errUnsupported
  193. }
  194. if err := cmd.Run(); err != nil {
  195. return nil, errUnavailable
  196. }
  197. // Update change time
  198. changeTimeMu.Lock()
  199. lastChangeTime = time.Now()
  200. currentTime := lastChangeTime
  201. changeTimeMu.Unlock()
  202. // Create change notification channel
  203. changed := make(chan struct{}, 1)
  204. go func() {
  205. for {
  206. time.Sleep(time.Second)
  207. changeTimeMu.Lock()
  208. if !lastChangeTime.Equal(currentTime) {
  209. changeTimeMu.Unlock()
  210. changed <- struct{}{}
  211. close(changed)
  212. return
  213. }
  214. changeTimeMu.Unlock()
  215. }
  216. }()
  217. return changed, nil
  218. }
  219. func watch(ctx context.Context, t Format) <-chan []byte {
  220. recv := make(chan []byte, 1)
  221. // Ensure clipboard is initialized before starting watch
  222. if err := initialize(); err != nil {
  223. close(recv)
  224. return recv
  225. }
  226. ti := time.NewTicker(time.Second)
  227. // Get initial clipboard content
  228. var lastContent []byte
  229. if b := Read(t); b != nil {
  230. lastContent = make([]byte, len(b))
  231. copy(lastContent, b)
  232. }
  233. go func() {
  234. defer close(recv)
  235. defer ti.Stop()
  236. for {
  237. select {
  238. case <-ctx.Done():
  239. return
  240. case <-ti.C:
  241. b := Read(t)
  242. if b == nil {
  243. continue
  244. }
  245. // Check if content changed
  246. if !bytes.Equal(lastContent, b) {
  247. recv <- b
  248. lastContent = make([]byte, len(b))
  249. copy(lastContent, b)
  250. }
  251. }
  252. }
  253. }()
  254. return recv
  255. }
  256. // Helper function to check clipboard content type for xclip
  257. func getClipboardTargets() []string {
  258. cmd := exec.Command("xclip", "-selection", "clipboard", "-t", "TARGETS", "-o")
  259. out, err := cmd.Output()
  260. if err != nil {
  261. return nil
  262. }
  263. return strings.Split(string(out), "\n")
  264. }