-
Notifications
You must be signed in to change notification settings - Fork 5
/
clipboard_unix.go
228 lines (193 loc) · 5.54 KB
/
clipboard_unix.go
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
// The MIT License (MIT)
// Copyright (c) 2016 Alessandro Arzilli
// https://github.com/aarzilli/nucular/blob/master/LICENSE
// +build freebsd linux netbsd openbsd solaris dragonfly
package clipboard
import (
"errors"
"fmt"
"os"
"time"
"github.com/BurntSushi/xgb"
"github.com/BurntSushi/xgb/xproto"
"github.com/sevlyar/go-daemon"
)
const debugClipboardRequests = false
var (
x *xgb.Conn
win xproto.Window
clipboardText string
selnotify chan bool
clipboardAtom, primaryAtom, textAtom, targetsAtom, atomAtom xproto.Atom
targetAtoms []xproto.Atom
clipboardAtomCache = map[xproto.Atom]string{}
doneCh = make(chan interface{})
)
func start() error {
var err error
xServer := os.Getenv("DISPLAY")
if xServer == "" {
return errors.New("could not identify xserver")
}
x, err = xgb.NewConnDisplay(xServer)
if err != nil {
return fmt.Errorf("%w", err)
}
selnotify = make(chan bool, 1)
win, err = xproto.NewWindowId(x)
if err != nil {
return fmt.Errorf("%w", err)
}
setup := xproto.Setup(x)
s := setup.DefaultScreen(x)
err = xproto.CreateWindowChecked(x, s.RootDepth, win, s.Root, 100, 100, 1, 1, 0, xproto.WindowClassInputOutput, s.RootVisual, 0, []uint32{}).Check()
if err != nil {
return fmt.Errorf("%w", err)
}
clipboardAtom = internAtom(x, "CLIPBOARD")
primaryAtom = internAtom(x, "PRIMARY")
textAtom = internAtom(x, "UTF8_STRING")
targetsAtom = internAtom(x, "TARGETS")
atomAtom = internAtom(x, "ATOM")
targetAtoms = []xproto.Atom{targetsAtom, textAtom}
go eventLoop()
return nil
}
func set(text string) error {
d := &daemon.Context{}
_, err := d.Reborn()
if err != nil {
fmt.Errorf("unable to run: %w", err)
}
defer d.Release()
// The following will run as a daemon.
if err := start(); err != nil {
return fmt.Errorf("init clipboard: %w", err)
}
clipboardText = text
ssoc := xproto.SetSelectionOwnerChecked(x, win, clipboardAtom, xproto.TimeCurrentTime)
if err := ssoc.Check(); err != nil {
return fmt.Errorf("setting clipboard: %w", err)
}
// Wait for the SelectionClear event.
<-doneCh
return nil
}
func get() (string, error) {
if err := start(); err != nil {
return "", fmt.Errorf("init clipboard: %w", err)
}
return getSelection(clipboardAtom)
}
func getSelection(selAtom xproto.Atom) (string, error) {
csc := xproto.ConvertSelectionChecked(x, win, selAtom, textAtom, selAtom, xproto.TimeCurrentTime)
err := csc.Check()
if err != nil {
return "", fmt.Errorf("convert selection check: %w", err)
}
select {
case r := <-selnotify:
if !r {
return "", nil
}
gpc := xproto.GetProperty(x, true, win, selAtom, textAtom, 0, 5*1024*1024)
gpr, err := gpc.Reply()
if err != nil {
return "", fmt.Errorf("grp reply: %w", err)
}
if gpr.BytesAfter != 0 {
return "", errors.New("clipboard too large")
}
return string(gpr.Value[:gpr.ValueLen]), nil
case <-time.After(1 * time.Second):
return "", errors.New("clipboard retrieval failed, timeout")
}
}
func eventLoop() {
for {
e, err := x.WaitForEvent()
if err != nil {
fmt.Fprintln(os.Stderr, "WaitForEvent error")
continue
}
switch e := e.(type) {
case xproto.SelectionRequestEvent:
if debugClipboardRequests {
tgtname := lookupAtom(e.Target)
fmt.Fprintln(os.Stderr, "SelectionRequest", e, textAtom, tgtname, "isPrimary:", e.Selection == primaryAtom, "isClipboard:", e.Selection == clipboardAtom)
}
t := clipboardText
switch e.Target {
case textAtom:
if debugClipboardRequests {
fmt.Fprintln(os.Stderr, "Sending as text")
}
cpc := xproto.ChangePropertyChecked(x, xproto.PropModeReplace, e.Requestor, e.Property, textAtom, 8, uint32(len(t)), []byte(t))
if cpc.Check() == nil {
sendSelectionNotify(e)
} else {
fmt.Fprintln(os.Stderr, err)
}
case targetsAtom:
if debugClipboardRequests {
fmt.Fprintln(os.Stderr, "Sending targets")
}
buf := make([]byte, len(targetAtoms)*4)
for i, atom := range targetAtoms {
xgb.Put32(buf[i*4:], uint32(atom))
}
cpc := xproto.ChangePropertyChecked(x, xproto.PropModeReplace, e.Requestor, e.Property, atomAtom, 32, uint32(len(targetAtoms)), buf)
if cpc.Check() == nil {
sendSelectionNotify(e)
} else {
fmt.Fprintln(os.Stderr, err)
}
default:
if debugClipboardRequests {
fmt.Fprintln(os.Stderr, "Skipping")
}
e.Property = 0
sendSelectionNotify(e)
}
case xproto.SelectionNotifyEvent:
selnotify <- (e.Property == clipboardAtom) || (e.Property == primaryAtom)
case xproto.SelectionClearEvent:
// Client loses ownership of a selection, so daemon process exit.
doneCh <- struct{}{}
}
}
}
func lookupAtom(at xproto.Atom) string {
if s, ok := clipboardAtomCache[at]; ok {
return s
}
reply, err := xproto.GetAtomName(x, at).Reply()
if err != nil {
panic(err)
}
// If we're here, it means we didn't have ths ATOM id cached. So cache it.
atomName := string(reply.Name)
clipboardAtomCache[at] = atomName
return atomName
}
func sendSelectionNotify(e xproto.SelectionRequestEvent) {
sn := xproto.SelectionNotifyEvent{
Time: e.Time,
Requestor: e.Requestor,
Selection: e.Selection,
Target: e.Target,
Property: e.Property}
sec := xproto.SendEventChecked(x, false, e.Requestor, 0, string(sn.Bytes()))
err := sec.Check()
if err != nil {
fmt.Println(err)
}
}
func internAtom(conn *xgb.Conn, n string) xproto.Atom {
iac := xproto.InternAtom(conn, true, uint16(len(n)), n)
iar, err := iac.Reply()
if err != nil {
panic(err)
}
return iar.Atom
}