Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clipboard watcher #38

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1 +1 @@
module github.com/atotto/clipboard
module github.com/tehsphinx/clipboard
42 changes: 42 additions & 0 deletions watcher.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package clipboard

import (
"context"
"time"
)

// Watch returns a channel for new clipboard content whenever it changes.
// It will return current clipboard content if not empty when initialized.
// Interval is the time between clipboard checks. Take into account that clickboard
// checks need a few milliseconds as well.
func Watch(interval time.Duration) (<-chan string, context.CancelFunc) {
var (
ch = make(chan string)
lastContent string
ctx, cancel = context.WithCancel(context.Background())
)

go func() {
defer close(ch)

for {
time.Sleep(interval)

select {
case <-ctx.Done():
return
default:
}

content, err := ReadAll()
if err != nil || content == "" || content == lastContent {
continue
}

lastContent = content
ch <- content
}
}()

return ch, cancel
}
44 changes: 44 additions & 0 deletions watcher_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package clipboard

import (
"fmt"
"testing"
"time"
)

func TestChange(t *testing.T) {
testStrings := []string{
"content 1",
"content 2",
"content 3",
}

WriteAll("")
ch, cancel := Watch(20 * time.Millisecond)

go func() {
for _, c := range testStrings {
WriteAll(c)
time.Sleep(100 * time.Millisecond)
}

// check if rewriting the same content doesn't affect the test
WriteAll("content 3")
time.Sleep(100 * time.Millisecond)

cancel()
}()

var i int
for c := range ch {
fmt.Println(i, testStrings[i], c)
if c != testStrings[i] {
t.Errorf("want %s, got %s", testStrings[i], c)
}
i++
}

if i != 3 {
t.Errorf("want %d, got %d", 3, i)
}
}