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

added watcher functionality #31

Open
wants to merge 5 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
6 changes: 1 addition & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

# Clipboard for Go

Provide copying and pasting to the Clipboard for Go.
Provide copying, pasting and monitoring clipboard functionality for Go.

Build:

Expand All @@ -26,10 +26,6 @@ Notes:
* Text string only
* UTF-8 text encoding only (no conversion)

TODO:

* Clipboard watcher(?)

## Commands:

paste shell command:
Expand Down
29 changes: 29 additions & 0 deletions clipboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
// Package clipboard read/write on clipboard
package clipboard

import (
"time"
)

// ReadAll read string from clipboard
func ReadAll() (string, error) {
return readAll()
Expand All @@ -15,6 +19,31 @@ func WriteAll(text string) error {
return writeAll(text)
}

// Monitor starts monitoring the clipboard for changes. When
// a change is detected, it is sent over the channel.
func Monitor(interval time.Duration, stopCh <-chan struct{}, changes chan<- string) error {
defer close(changes)

currentValue, err := ReadAll()
if err != nil {
return err
}

for {
select {
case <-stopCh:
return nil
default:
newValue, _ := ReadAll()
if newValue != currentValue {
currentValue = newValue
changes <- currentValue
}
}
time.Sleep(interval)
}
}

// Unsupported might be set true during clipboard init, to help callers decide
// whether or not to offer clipboard options.
var Unsupported bool
30 changes: 30 additions & 0 deletions cmd/monitor/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package main

import (
"log"
"time"

"github.com/spy16/clipboard"
)

func main() {
changes := make(chan string, 10)
stopCh := make(chan struct{})

go clipboard.Monitor(time.Second, stopCh, changes)

// Watch for changes
for {
select {
case <-stopCh:
break
default:
change, ok := <-changes
if ok {
log.Printf("change received: '%s'", change)
} else {
log.Printf("channel has been closed. exiting..")
}
}
}
}