summaryrefslogtreecommitdiffhomepage
path: root/packages/tui/internal/clipboard/clipboard_linux.go
blob: 101906395ac4576bf01d2c505ece78b549a9e1f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>

//go:build linux

package clipboard

import (
	"bytes"
	"context"
	"fmt"
	"log/slog"
	"os"
	"os/exec"
	"strings"
	"sync"
	"time"
)

var (
	// Clipboard tools in order of preference
	clipboardTools = []struct {
		name      string
		readCmd   []string
		writeCmd  []string
		readImg   []string
		writeImg  []string
		available bool
	}{
		{
			name:     "xclip",
			readCmd:  []string{"xclip", "-selection", "clipboard", "-o"},
			writeCmd: []string{"xclip", "-selection", "clipboard"},
			readImg:  []string{"xclip", "-selection", "clipboard", "-t", "image/png", "-o"},
			writeImg: []string{"xclip", "-selection", "clipboard", "-t", "image/png"},
		},
		{
			name:     "xsel",
			readCmd:  []string{"xsel", "--clipboard", "--output"},
			writeCmd: []string{"xsel", "--clipboard", "--input"},
			readImg:  []string{"xsel", "--clipboard", "--output"},
			writeImg: []string{"xsel", "--clipboard", "--input"},
		},
		{
			name:     "wl-copy",
			readCmd:  []string{"wl-paste", "-n"},
			writeCmd: []string{"wl-copy"},
			readImg:  []string{"wl-paste", "-t", "image/png", "-n"},
			writeImg: []string{"wl-copy", "-t", "image/png"},
		},
	}

	selectedTool   int = -1
	toolMutex      sync.Mutex
	lastChangeTime time.Time
	changeTimeMu   sync.Mutex
)

func initialize() error {
	toolMutex.Lock()
	defer toolMutex.Unlock()

	if selectedTool >= 0 {
		return nil // Already initialized
	}

	order := []string{"xclip", "xsel", "wl-copy"}
	if os.Getenv("WAYLAND_DISPLAY") != "" {
		order = []string{"wl-copy", "xclip", "xsel"}
	}

	for _, name := range order {
		for i, tool := range clipboardTools {
			if tool.name == name {
				cmd := exec.Command("which", tool.name)
				if err := cmd.Run(); err == nil {
					clipboardTools[i].available = true
					if selectedTool < 0 {
						selectedTool = i
						slog.Debug("Clipboard tool found", "tool", tool.name)
					}
				}
				break
			}
		}
	}

	if selectedTool < 0 {
		slog.Warn(
			"No clipboard utility found on system. Copy/paste functionality will be disabled. See https://opencode.ai/docs/troubleshooting/ for more information.",
		)
		return fmt.Errorf(`%w: No clipboard utility found. Install one of the following:

For X11 systems:
	apt install -y xclip
	# or
	apt install -y xsel

For Wayland systems:
	apt install -y wl-clipboard

If running in a headless environment, you may also need:
	apt install -y xvfb
	# and run:
	Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
	export DISPLAY=:99.0`, errUnavailable)
	}

	return nil
}

func read(t Format) (buf []byte, err error) {
	// Ensure clipboard is initialized before attempting to read
	if err := initialize(); err != nil {
		slog.Debug("Clipboard read failed: not initialized", "error", err)
		return nil, err
	}

	toolMutex.Lock()
	tool := clipboardTools[selectedTool]
	toolMutex.Unlock()

	switch t {
	case FmtText:
		return readText(tool)
	case FmtImage:
		return readImage(tool)
	default:
		return nil, errUnsupported
	}
}

func readText(tool struct {
	name      string
	readCmd   []string
	writeCmd  []string
	readImg   []string
	writeImg  []string
	available bool
}) ([]byte, error) {
	// First check if clipboard contains text
	cmd := exec.Command(tool.readCmd[0], tool.readCmd[1:]...)
	out, err := cmd.Output()
	if err != nil {
		// Check if it's because clipboard contains non-text data
		if tool.name == "xclip" {
			// xclip returns error when clipboard doesn't contain requested type
			checkCmd := exec.Command("xclip", "-selection", "clipboard", "-t", "TARGETS", "-o")
			targets, _ := checkCmd.Output()
			if bytes.Contains(targets, []byte("image/png")) &&
				!bytes.Contains(targets, []byte("UTF8_STRING")) {
				return nil, errUnavailable
			}
		}
		return nil, errUnavailable
	}

	return out, nil
}

func readImage(tool struct {
	name      string
	readCmd   []string
	writeCmd  []string
	readImg   []string
	writeImg  []string
	available bool
}) ([]byte, error) {
	if tool.name == "xsel" {
		// xsel doesn't support image types well, return error
		return nil, errUnavailable
	}

	cmd := exec.Command(tool.readImg[0], tool.readImg[1:]...)
	out, err := cmd.Output()
	if err != nil {
		return nil, errUnavailable
	}

	// Verify it's PNG data
	if len(out) < 8 ||
		!bytes.Equal(out[:8], []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}) {
		return nil, errUnavailable
	}

	return out, nil
}

func write(t Format, buf []byte) (<-chan struct{}, error) {
	// Ensure clipboard is initialized before attempting to write
	if err := initialize(); err != nil {
		return nil, err
	}

	toolMutex.Lock()
	tool := clipboardTools[selectedTool]
	toolMutex.Unlock()

	var cmd *exec.Cmd
	switch t {
	case FmtText:
		if len(buf) == 0 {
			// Write empty string
			cmd = exec.Command(tool.writeCmd[0], tool.writeCmd[1:]...)
			cmd.Stdin = bytes.NewReader([]byte{})
		} else {
			cmd = exec.Command(tool.writeCmd[0], tool.writeCmd[1:]...)
			cmd.Stdin = bytes.NewReader(buf)
		}
	case FmtImage:
		if tool.name == "xsel" {
			// xsel doesn't support image types well
			return nil, errUnavailable
		}
		if len(buf) == 0 {
			// Clear clipboard
			cmd = exec.Command(tool.writeCmd[0], tool.writeCmd[1:]...)
			cmd.Stdin = bytes.NewReader([]byte{})
		} else {
			cmd = exec.Command(tool.writeImg[0], tool.writeImg[1:]...)
			cmd.Stdin = bytes.NewReader(buf)
		}
	default:
		return nil, errUnsupported
	}

	if err := cmd.Run(); err != nil {
		return nil, errUnavailable
	}

	// Update change time
	changeTimeMu.Lock()
	lastChangeTime = time.Now()
	currentTime := lastChangeTime
	changeTimeMu.Unlock()

	// Create change notification channel
	changed := make(chan struct{}, 1)
	go func() {
		for {
			time.Sleep(time.Second)
			changeTimeMu.Lock()
			if !lastChangeTime.Equal(currentTime) {
				changeTimeMu.Unlock()
				changed <- struct{}{}
				close(changed)
				return
			}
			changeTimeMu.Unlock()
		}
	}()

	return changed, nil
}

func watch(ctx context.Context, t Format) <-chan []byte {
	recv := make(chan []byte, 1)

	// Ensure clipboard is initialized before starting watch
	if err := initialize(); err != nil {
		close(recv)
		return recv
	}

	ti := time.NewTicker(time.Second)

	// Get initial clipboard content
	var lastContent []byte
	if b := Read(t); b != nil {
		lastContent = make([]byte, len(b))
		copy(lastContent, b)
	}

	go func() {
		defer close(recv)
		defer ti.Stop()

		for {
			select {
			case <-ctx.Done():
				return
			case <-ti.C:
				b := Read(t)
				if b == nil {
					continue
				}

				// Check if content changed
				if !bytes.Equal(lastContent, b) {
					recv <- b
					lastContent = make([]byte, len(b))
					copy(lastContent, b)
				}
			}
		}
	}()
	return recv
}

// Helper function to check clipboard content type for xclip
func getClipboardTargets() []string {
	cmd := exec.Command("xclip", "-selection", "clipboard", "-t", "TARGETS", "-o")
	out, err := cmd.Output()
	if err != nil {
		return nil
	}
	return strings.Split(string(out), "\n")
}