From 13699549a75fd499d18f8da06a10a26b4dd6a8c3 Mon Sep 17 00:00:00 2001 From: Gabriel Nelle Date: Sun, 28 Oct 2018 20:58:23 +0100 Subject: [PATCH 1/2] clipboard watching capability --- watcher.go | 42 ++++++++++++++++++++++++++++++++++++++++++ watcher_test.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 watcher.go create mode 100644 watcher_test.go diff --git a/watcher.go b/watcher.go new file mode 100644 index 0000000..6a477ba --- /dev/null +++ b/watcher.go @@ -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 +} diff --git a/watcher_test.go b/watcher_test.go new file mode 100644 index 0000000..984393a --- /dev/null +++ b/watcher_test.go @@ -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) + } +} From 69528ff1d54a6f49a4b2ebc8dd726391d4ee9cdb Mon Sep 17 00:00:00 2001 From: Gabriel Nelle Date: Sun, 28 Oct 2018 22:33:30 +0100 Subject: [PATCH 2/2] fix module path --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 68ec980..8125ff6 100644 --- a/go.mod +++ b/go.mod @@ -1 +1 @@ -module github.com/atotto/clipboard +module github.com/tehsphinx/clipboard