diff --git a/README.md b/README.md index 41fdd57..5d0b61b 100644 --- a/README.md +++ b/README.md @@ -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: @@ -26,10 +26,6 @@ Notes: * Text string only * UTF-8 text encoding only (no conversion) -TODO: - -* Clipboard watcher(?) - ## Commands: paste shell command: diff --git a/clipboard.go b/clipboard.go index d7907d3..6dec15b 100644 --- a/clipboard.go +++ b/clipboard.go @@ -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() @@ -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 diff --git a/cmd/monitor/main.go b/cmd/monitor/main.go new file mode 100644 index 0000000..c157732 --- /dev/null +++ b/cmd/monitor/main.go @@ -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..") + } + } + } +}