-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsync.go
More file actions
106 lines (86 loc) · 1.79 KB
/
sync.go
File metadata and controls
106 lines (86 loc) · 1.79 KB
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
package main
import (
"bytes"
"context"
"fmt"
"sync"
"time"
ipc "github.com/james-barrow/golang-ipc"
"golang.design/x/clipboard"
)
type Syncer struct {
mtx sync.Mutex
socket commSocket
clipboardContent []byte
wg sync.WaitGroup
ctx context.Context
cancelFunc context.CancelFunc
}
type commSocket interface {
Read() (*ipc.Message, error)
Write(msgType int, message []byte) error
StatusCode() ipc.Status
}
func (s *Syncer) Start(ctx context.Context, socket commSocket) {
s.mtx.Lock()
defer s.mtx.Unlock()
s.socket = socket
s.clipboardContent = clipboard.Read(clipboard.FmtText)
s.wg.Add(2)
s.ctx, s.cancelFunc = context.WithCancel(ctx)
go func() {
<-ctx.Done()
s.Stop()
}()
go func() {
defer s.wg.Done()
defer fmt.Println("socket listener stopped")
for {
msg, err := socket.Read()
if err != nil {
fmt.Printf("got error on read: %v\n", err)
break
}
if msg.MsgType == 1 {
s.mtx.Lock()
clipboard.Write(clipboard.FmtText, msg.Data)
s.clipboardContent = msg.Data
s.mtx.Unlock()
}
}
}()
initChan := make(chan struct{})
go func() {
defer s.wg.Done()
for {
if socket.StatusCode() == ipc.Connected {
break
}
time.Sleep(100 * time.Millisecond)
}
close(initChan)
defer fmt.Println("clipboard listener stopped")
clipboardChanges := clipboard.Watch(s.ctx, clipboard.FmtText)
for newContent := range clipboardChanges {
s.mtx.Lock()
if !bytes.Equal(newContent, s.clipboardContent) {
_ = socket.Write(1, newContent)
s.clipboardContent = newContent
}
s.mtx.Unlock()
}
}()
<-initChan
}
func (s *Syncer) Stop() {
s.mtx.Lock()
defer s.mtx.Unlock()
if s.ctx != nil {
s.cancelFunc()
}
s.wg.Wait()
s.ctx = nil
}
func (s *Syncer) ForceSync() {
_ = s.socket.Write(1, s.clipboardContent)
}